问:
UML and Code Relationship
I understand that the main goal of UML is to communicate. UML intends to provide a design of a system and Code really is the actual building block of the system.

My question is if code an uml are suppose to directly mirror each other. Let me explain:

I am working on a java program that uses a web service to display movie show times.

So far I have managed to make simple gui with AWT and Swing that displays show times.

The program has 16 classes and a friend of mine extended my code on a git however he added the following to all the classes.

package ShowTimesFrUSA;

I wanted to present my program with designs of UML with a package Diagram. However I already divided my classes into different packages differently from the way it is coded. Packages:UI (AWT and Swing) , Controllers, Moviemonitor, MovieService, USAmovies <<server>>

I just want to show the dependencies between the class groups in my code as part of the requirements for this presentation and the package diagram is really good for that. But I am unsure if the packages in the model should directly mirror the way packages are coded in java?

答:
When you start thinking about a solution to your problem, and draw a class diagram to communicate, you are indeed designing the classes you will need in your program at the business logic level. At this level, UML and code should be in sync. Of course, the code will have more information, such as complete implemented methods.
At the UI code level, usually UML classes do not help or communicate much. </p>

Title: UML and Code Relationship


来源: stackexchange

问:
How to install PyAutoGUI
I am running OS X El Capitan v. 10.11.3

I am trying to install PyAutoGUI

On Terminal, I did the following successfully:

```<code>sudo pip3 install pyobjc-core
sudo pip3 install pyobjc
</code>```

When I tried running "sudo pip3 install pyautogui" I got the following error in Terminal:

Command "python setup.py egg_info" failed with error code 1 in
  /private/tmp/pip-build-skuvquyu/pyscreeze

I am not sure what to do about this so if anyone has any advice, I would appreciate it.

Thanks

答:
Found an answer to the problem

On Linux, this is:

```<code>sudo pip3 install python3-xlib

sudo apt-get install scrot

sudo apt-get install python3-tk

sudo apt-get install python3-dev

sudo pip3 install pyautogui
</code>```

ta daaaa :D

ContentLicense: CC BY-SA 3.0

Title: How to install PyAutoGUI

Body:
I am running OS X El Capitan v. 10.11.3

I am trying to install PyAutoGUI

On Terminal, I did the following successfully:

sudo pip3 install pyobjc-core
sudo pip3 install pyobjc

When I tried running "sudo pip3 install pyautogui" I got the following error in Terminal:

Command "python setup.py egg_info" failed with error code 1 in
  /private/tmp/pip-build-skuvquyu/pyscreeze

I am not sure what to do about this so if anyone has any advice, I would appreciate it.

Thanks

Body:
Found an answer to the problem

On Linux, this is:

sudo pip3 install python3-xlib

sudo apt-get install scrot

sudo apt-get install python3-tk

sudo apt-get install python3-dev

sudo pip3 install pyautogui

ta daaaa :D

ContentLicense: CC BY-SA 4.0


问:
Error 500: Premature end of script headers
I get a "Premature end of script headers: contactform.cgi" error message when running the below script.  What frustrates me is that I ran this as a .php on another server and it worked.  However, I had to change servers and they only support CGI PHP.  However, it doesn't work.  I don't think the code is wrong, but take a look just in case.

I've read around and some have said it's a permissions issue.  Could this be the case for me?

I know that the "display_errors" and "error_reporting" statements will display errors in the error log, but if I don't have access to the server, how can I check the logs?

```<code>#!/usr/local/bin/php

<?php

print "Content-type: text/html\n\n";
use CGI::Carp qw(fatalsToBrowser);
ini_set('display_errors',1);
error_reporting(E_ALL);

if(isset($_POST['email'])) {

//Email this form to me
$email_to = "myemail@site.com";

function died($error) {
    // your error code can go here
    echo "Oops... something's wrong. ";
    echo "Fix the error(s) below:<br /><br />";
    echo $error."<br /><br />";
    die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['subject']) ||
    !isset($_POST['comments'])) {
    died('There appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$subject = $_POST['subject']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Subject: ".clean_string($subject)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";

//Email Subject (put here to include subject from form)
$email_subject = "SUBJECT | ".clean_string($subject)."";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

<!-- include your own success html here -->

<?php
header("Location: thankyou.html");
}
?>
</code>```

答:
After many diff's, this was what was missing from the httpd.conf file on the server in question:

```<code>AddHandler php5-script .php
</code>```

Solved the issue.

Body:
I get a "Premature end of script headers: contactform.cgi" error message when running the below script.  What frustrates me is that I ran this as a .php on another server and it worked.  However, I had to change servers and they only support CGI PHP.  However, it doesn't work.  I don't think the code is wrong, but take a look just in case.

I've read around and some have said it's a permissions issue.  Could this be the case for me?

I know that the "display_errors" and "error_reporting" statements will display errors in the error log, but if I don't have access to the server, how can I check the logs?

#!/usr/local/bin/php

<?php

print "Content-type: text/html\n\n";
use CGI::Carp qw(fatalsToBrowser);
ini_set('display_errors',1);
error_reporting(E_ALL);

if(isset($_POST['email'])) {

//Email this form to me
$email_to = "myemail@site.com";

function died($error) {
    // your error code can go here
    echo "Oops... something's wrong. ";
    echo "Fix the error(s) below:

";
    echo $error."

";
    die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['subject']) ||
    !isset($_POST['comments'])) {
    died('There appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$subject = $_POST['subject']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.
';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.
';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.
';
}
if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Subject: ".clean_string($subject)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";

//Email Subject (put here to include subject from form)
$email_subject = "SUBJECT | ".clean_string($subject)."";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

<?php
header("Location: thankyou.html");
}
?>

Body:
After many diff's, this was what was missing from the httpd.conf file on the server in question:

AddHandler php5-script .php

Solved the issue.


问:
pip freeze doesn't show opencv in Linux/Mint
I've installed OpenCV on Linux Mint and I can import it in python

```<code>(cv_env)➜  cv_env python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
>>> import cv2
>>> import numpy
>>> import scipy
</code>```

But when I want to see it in pip freeze, it doesn't appear:

```<code>(cv_env)➜  cv_env pip freeze
argparse==1.2.1
caffi==1.0.2
coffee==0.1.0
ffmpeg-python==0.1.6
future==0.16.0
imutils==0.4.3
numpy==1.13.3
pandas==0.20.3
python-dateutil==2.6.1
pytz==2017.2
scipy==0.19.1
six==1.11.0
wsgiref==0.1.2
</code>```

Also, I tried to import it via PyCharm's Project Interpreter. It wants to installation with pip. (pip install opencv-python and pip install cv2)

When I installed that, I followed these steps

What is the problem that I cannot see?

答:
Those instructions are outdated, and using apt-get puts pieces outside of the virtual environment, where pip won't see them to freeze.

Within a virtual environment, try

```<code>pip install --upgrade pip
pip install opencv-python
</code>```

The --upgrade might not be necessary, but has helped me out of weird pip failures in the past.

Body:
I've installed OpenCV on Linux Mint and I can import it in python

(cv_env)➜  cv_env python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
>>> import cv2
>>> import numpy
>>> import scipy

But when I want to see it in pip freeze, it doesn't appear:

(cv_env)➜  cv_env pip freeze
argparse==1.2.1
caffi==1.0.2
coffee==0.1.0
ffmpeg-python==0.1.6
future==0.16.0
imutils==0.4.3
numpy==1.13.3
pandas==0.20.3
python-dateutil==2.6.1
pytz==2017.2
scipy==0.19.1
six==1.11.0
wsgiref==0.1.2

Also, I tried to import it via PyCharm's Project Interpreter. It wants to installation with pip. (pip install opencv-python and pip install cv2)

When I installed that, I followed these steps

What is the problem that I cannot see?

Body:
Those instructions are outdated, and using apt-get puts pieces outside of the virtual environment, where pip won't see them to freeze.

Within a virtual environment, try

pip install --upgrade pip
pip install opencv-python

The --upgrade might not be necessary, but has helped me out of weird pip failures in the past.


问:
Access denied when deleting folders created in SQL Server
I am creating directories with xp_cmdshell but I can't delete them after because of the permission, I am not even allowed to see the owner of the folders.
I have to enter in safe mode to be able of delete the folders.
I am using SQL Server 2008.</p>

答:
Danger, Will Robinson, Danger!

This sounds like it might not be ideal from several angles - security, future-proofing, and scalability. Assuming none of those are priorities for your code, crack on with Edgard's answer.

Otherwise, I would question any design that has the DBMS (directly) write folders in the file system. I don't question that you have your reasons, it's just that there are some very big, but very non-obvious risks that won't bite you until later when you're already committed to the course. There may be less risky and more straightforward ways to do whatever you're doing.


问:
How to retrieve raster data in GeoMesa with a single query given tempospatial search criteria
According to How are GeoTIFFs persisted in GeoMesa?

```<code>GeoMesa's raster data is indexed by spatial extent solely.
</code>```

Can I also save time info with the raster data? Else, for each raster I will have to persist another record holding its time info. Therefore, in order to retrieve my raster using a tempospatial query (is WMS capable for this? according to [1] it seems to be) I will have to retrieve both files; this means for x raster ==> x+1 GeoMesa hits (retrievals).

[1] http://docs.geoserver.org/stable/en/user/services/wms/time.html

答:
Currently, no, you cannot save time info with the raster data.

WMS does support time and time range queries.  That capability isn't wired up completely in the AccumuloRasterStore.

As an alternative, GeoMesa does allow for storing blobs and creating pointers to them on the way. The GeoMesa BlobStore doesn't allow for WMS access, but it is a nifty, extensible capability.

Body:
According to How are GeoTIFFs persisted in GeoMesa?

GeoMesa's raster data is indexed by spatial extent solely.

Can I also save time info with the raster data? Else, for each raster I will have to persist another record holding its time info. Therefore, in order to retrieve my raster using a tempospatial query (is WMS capable for this? according to [1] it seems to be) I will have to retrieve both files; this means for x raster ==> x+1 GeoMesa hits (retrievals).

[1] http://docs.geoserver.org/stable/en/user/services/wms/time.html


问:
How to run TopoJSON?
I need to convert a geojson file to topojson and possibly simplify the topojson file. I've managed to install Node.js and the topojson package. But I have no idea how to run topojson.

The wiki lists a bunch of command line options, but where do I run those commands? I've tried running them both in the command prompt and the node shell. Node, GDAL, ogr2ogr and TopoJSON are all new concepts for me, so I'm a bit confused and overwhelmed.

I'm running on Windows by the way.

答:
It has been changed to geo2topo

1) Run

```<code>sudo npm install -g geo2topo
</code>```

2) check if it returns the path

```<code>which geo2topo
</code>```

It should give the path /usr/bin/geo2topo

3) Use it to convert your geojson file

```<code>geo2topo -o output.json input.json
</code>```

Title: How to run TopoJSON?

Body:
It has been changed to geo2topo

1) Run

sudo npm install -g geo2topo

2) check if it returns the path

which geo2topo

It should give the path /usr/bin/geo2topo

3) Use it to convert your geojson file

geo2topo -o output.json input.json


问:
How do I assemble pieces of HTML into a DOMDocument?
It appears that loadHTML and loadHTMLFile for a files representing sections of an HTML document seem to fill in html and body tags for each section, as revealed when I output with the following:

```<code>$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('*');

if( !is_null($elements) ) {
    foreach( $elements as $element ) {
        echo "<br/>". $element->nodeName. ": ";

        $nodes = $element->childNodes;
        foreach( $nodes as $node ) {
            echo $node->nodeValue. "\n";
        }
    }
}
</code>```

Since I plan to assemble these parts into the larger document within my own code, and I've been instructed to use DOMDocument to do it, what can I do to prevent this behavior?

答:
The closest you can get is to use the DOMDocumentFragment.

Then you can do:

```<code>$doc = new DOMDocument();
...
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$someElement->appendChild($f);
</code>```

However, this expects XML, not HTML.

In any case, I think you're creating an artificial problem. Since you know the behavior is to create the html and body tags you can just extract the elements in the file from within the body tag and then import the, to the DOMDocument where you're assembling the final file. See DOMDocument::importNode.

ContentLicense: CC BY-SA 2.5

Body:
It appears that loadHTML and loadHTMLFile for a files representing sections of an HTML document seem to fill in html and body tags for each section, as revealed when I output with the following:

$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('*');

if( !is_null($elements) ) {
    foreach( $elements as $element ) {
        echo "
". $element->nodeName. ": ";

        $nodes = $element->childNodes;
        foreach( $nodes as $node ) {
            echo $node->nodeValue. "\n";
        }
    }
}

Since I plan to assemble these parts into the larger document within my own code, and I've been instructed to use DOMDocument to do it, what can I do to prevent this behavior?

Body:
The closest you can get is to use the DOMDocumentFragment.

Then you can do:

$doc = new DOMDocument();
...
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$someElement->appendChild($f);

However, this expects XML, not HTML.

In any case, I think you're creating an artificial problem. Since you know the behavior is to create the html and body tags you can just extract the elements in the file from within the body tag and then import the, to the DOMDocument where you're assembling the final file. See DOMDocument::importNode.


问:
Note be able to create tables in database and insert values
I am using MAMP as my localhost environment and i am trying to pass values from html form to database through php.when i submit my form i face following error:

INSERT INTO social (facebook, google, twitter) VALUES ('sdf','sdf','sdf')
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'firsttest.social' doesn't exist

html:

<form name='form' method='post' action="m.php">

Fb : <input type="text" name="fb" >
google : <input type="text" name="google" >
twitter : <input type="text" name="twitter" >

<input type="submit" name="save_to_db" value="Submit">

</form>
```
</div>
</div>
</p>

<p><strong>PHP:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
  if(isset($_POST['save_to_db'])){

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "firsttest";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // sql to create table
    $sql = "CREATE TABLE social (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    facebook VARCHAR(30) NOT NULL,
    google VARCHAR(30) NOT NULL,
    twitter VARCHAR(50),
    reg_date TIMESTAMP
    )";

    $sql = "INSERT INTO social (facebook, google, twitter)
    VALUES ('".$_POST["fb"]."','".$_POST["google"]."','".$_POST["twitter"]."')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
}
?></code>```

答:
You're not executing the CREATE TABLE query, but instead, you overwrite it with the INSERT query instantly.

Try using a debug tool like xdebug or something, so you could walk step by step through your code, that will help you find bugs in your code easily.

Also, creating a database table each time you want to save data to the database is not wise. Try setting up the whole database before starting to work with it.

Body:
I am using MAMP as my localhost environment and i am trying to pass values from html form to database through php.when i submit my form i face following error:

INSERT INTO social (facebook, google, twitter) VALUES ('sdf','sdf','sdf')
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'firsttest.social' doesn't exist

html:

<form name='form' method='post' action="m.php">

Fb : <input type="text" name="fb" >
google : <input type="text" name="google" >
twitter : <input type="text" name="twitter" >

<input type="submit" name="save_to_db" value="Submit">

</form>

PHP:

<?php
  if(isset($_POST['save_to_db'])){

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "firsttest";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // sql to create table
    $sql = "CREATE TABLE social (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    facebook VARCHAR(30) NOT NULL,
    google VARCHAR(30) NOT NULL,
    twitter VARCHAR(50),
    reg_date TIMESTAMP
    )";

    $sql = "INSERT INTO social (facebook, google, twitter)
    VALUES ('".$_POST["fb"]."','".$_POST["google"]."','".$_POST["twitter"]."')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }

$conn = null;
}
?>


问:
Production API Key for Google Maps on Android

I have created an API Key in the Google Console API Credentials Page.

I have restricted access to Android Apps

I have added my package and the SHA-1 Key (generated using keytool and local keystore file).

I have added the key generated to the google_maps_api.xml under src/main/res/values/ folder.

When I build the release app and have it downloaded from my website, then google maps is showing as expected.
However, when I push this to play store for beta testing, google maps doesn't show.

I have tried multiple tutorials but nothing seems to work so far.

What else should I be doing? Any suggestion will be most welcome.

答:
I had same issue,  because sometimes  google_maps_api.xml file created as two types (release and debug one).
You can solve this by

1.Creating release version of  google_maps_api.xml

or

2.Providing your API_KEY directly on manifest.xml like

```<code><meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSkjoivhTt2F1vv_14nYsF90cqpRK0FeyLbU8" />
</code>```

Body:
I had same issue,  because sometimes  google_maps_api.xml file created as two types (release and debug one).
You can solve this by

1.Creating release version of  google_maps_api.xml

or

2.Providing your API_KEY directly on manifest.xml like

<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSkjoivhTt2F1vv_14nYsF90cqpRK0FeyLbU8" />


问:
Android Studio Update Problems
Android Studio updated to 3.0 and I'm having a lot of issues with my project. Currently there is an error at launch that I can't find a way to solve.

Here is error stack:

```<code>Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/nikitagudkovs/.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.5.2/1b94ab7ec707e2220a0d1a7517488d1843236345/auto-value-1.5.2.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing autovalue/shaded/com/google$/common/collect/$ImmutableMap.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForJivaDebug'.
> com.android.build.api.transform.TransformException:     com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException:
Failed to process /Users/nikitagudkovs/.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.5.2/1b94ab7ec707e2220a0d1a7517488d1843236345/auto-value-1.5.2.jar
</code>```

答: Try Build > Clean Project and rebuild again.

Title: Android Studio Update Problems

Body:
Android Studio updated to 3.0 and I'm having a lot of issues with my project. Currently there is an error at launch that I can't find a way to solve.

Here is error stack:

Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/nikitagudkovs/.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.5.2/1b94ab7ec707e2220a0d1a7517488d1843236345/auto-value-1.5.2.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing autovalue/shaded/com/google$/common/collect/$ImmutableMap.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForJivaDebug'.
> com.android.build.api.transform.TransformException:     com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException:
Failed to process /Users/nikitagudkovs/.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.5.2/1b94ab7ec707e2220a0d1a7517488d1843236345/auto-value-1.5.2.jar


问:
How to increase the value of a fraction in a loop with Python
Im was trying to do a loop, increasing the numerator by 1 each iteration, but I got this error:

ZeroDivisionError: Fraction(1, 0)

My code is something like this:

```<code>from fractions import Fraction
x = Fraction(0,48)
z = x.numerator
limit = (48,48)
while x == limit:
    print("cycle " + str(z))
    x += Fraction(1,0)
print("loop finished!")
</code>```

答:
If all you need is a list of fractions, you could simply create them with a list comprehension:

```<code>>>> from fractions import Fraction
>>> n = 48
>>> [Fraction(i, n) for i in range(n + 1)]
[Fraction(0, 1), Fraction(1, 48), Fraction(1, 24), Fraction(1, 16), Fraction(1, 12), Fraction(5, 48), Fraction(1, 8), Fraction(7, 48), Fraction(1, 6), Fraction(3, 16), Fraction(5, 24), Fraction(11, 48), Fraction(1, 4), Fraction(13, 48), Fraction(7, 24), Fraction(5, 16), Fraction(1, 3), Fraction(17, 48), Fraction(3, 8), Fraction(19, 48), Fraction(5, 12), Fraction(7, 16), Fraction(11, 24), Fraction(23, 48), Fraction(1, 2), Fraction(25, 48), Fraction(13, 24), Fraction(9, 16), Fraction(7, 12), Fraction(29, 48), Fraction(5, 8), Fraction(31, 48), Fraction(2, 3), Fraction(11, 16), Fraction(17, 24), Fraction(35, 48), Fraction(3, 4), Fraction(37, 48), Fraction(19, 24), Fraction(13, 16), Fraction(5, 6), Fraction(41, 48), Fraction(7, 8), Fraction(43, 48), Fraction(11, 12), Fraction(15, 16), Fraction(23, 24), Fraction(47, 48), Fraction(1, 1)]
</code>```

In Python, you usually don't need to increment any counter manually.

Body:
Im was trying to do a loop, increasing the numerator by 1 each iteration, but I got this error:

ZeroDivisionError: Fraction(1, 0)

My code is something like this:

from fractions import Fraction
x = Fraction(0,48)
z = x.numerator
limit = (48,48)
while x == limit:
    print("cycle " + str(z))
    x += Fraction(1,0)
print("loop finished!")

Body:
If all you need is a list of fractions, you could simply create them with a list comprehension:

>>> from fractions import Fraction
>>> n = 48
>>> [Fraction(i, n) for i in range(n + 1)]
[Fraction(0, 1), Fraction(1, 48), Fraction(1, 24), Fraction(1, 16), Fraction(1, 12), Fraction(5, 48), Fraction(1, 8), Fraction(7, 48), Fraction(1, 6), Fraction(3, 16), Fraction(5, 24), Fraction(11, 48), Fraction(1, 4), Fraction(13, 48), Fraction(7, 24), Fraction(5, 16), Fraction(1, 3), Fraction(17, 48), Fraction(3, 8), Fraction(19, 48), Fraction(5, 12), Fraction(7, 16), Fraction(11, 24), Fraction(23, 48), Fraction(1, 2), Fraction(25, 48), Fraction(13, 24), Fraction(9, 16), Fraction(7, 12), Fraction(29, 48), Fraction(5, 8), Fraction(31, 48), Fraction(2, 3), Fraction(11, 16), Fraction(17, 24), Fraction(35, 48), Fraction(3, 4), Fraction(37, 48), Fraction(19, 24), Fraction(13, 16), Fraction(5, 6), Fraction(41, 48), Fraction(7, 8), Fraction(43, 48), Fraction(11, 12), Fraction(15, 16), Fraction(23, 24), Fraction(47, 48), Fraction(1, 1)]

In Python, you usually don't need to increment any counter manually.


问:
Stop Excel Scientific Notation Conversion
Is there a way to STOP EXCEL from converting data into Scientific Notation?

Microsoft Excel apparently assumes that any data that contains numbers and an E is supposed to be scientific notation and converts it.

17195E000039 automatically changes to 1.7195E+43

17221E000112 automatically changes to 1.7221E+116

Is there a way to prevent Excel from doing this so it doesn't continue to cause problems for all of us users who never want to use SCIENTIFIC NOTATION ever? I cannot foresee any time where I will EVER want to have anything converted to scientific notation. This useless functionality only causes problems.

How do I stop Excel from trying to convert text into scientific without manually performing some operation first?

Unfortunately, the data comes from another system that exports to excel that I cannot change. I cannot manually change the page beforehand and going through afterwards sucks.

答:
Is there a way to STOP EXCEL from converting data into Scientific Notation?

As explained by @Scott Craner: For you, No.

This is something that happens automatically when the data is written - by the time you see it it is too late.


问:
How to display multiple routes in one page using Ember js?
I'm new to Ember and I'm stuck with an issue that I cannot solve. I have two routes - home and lhstree. When /home is called, I need both the routes to be rendered ie. lhstree should be rendered within home template. For this purpose, I used named outlet. That worked fine.
But the problem is, I need to supply data to the lhstree template. But the model hook for the lhstree template is never called. I even tried adding alert messages in the model hook, but that too is never executed. The below is my code. Any help is appreciated.

router.js:

```<code>Router.map(function() {
 this.route('home');
 this.route('lhstree');
});
</code>```

home.hbs:

```<code><html>
<head>
</head>
<body>
    Home hbs rendering
    {{outlet 'lhstree'}}
</body>
</html>
</code>```

home.js:

```<code>export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }
});
</code>```

lhstree.hbs:

```<code><ul>
  {{#each model as |player|}}
    <li>{{player}}</li>
  {{/each}}
</ul>
</code>```

lhstree.js:

```<code>model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
}
</code>```

As I mentioned, the model hook of lhstree route is never called. So, the player names Player1 and Player2 are never displayed when home template is rendered.

答: While rendering a template you can only set a template to an outlet, not a route. Therefore, in your case lhstree.hbs is called but lhstree.js route will not be called. If you want to pass data to the template in your outlet, you can call set the data in your home route. You can take a look at this twiddle.

Body:
I'm new to Ember and I'm stuck with an issue that I cannot solve. I have two routes - home and lhstree. When /home is called, I need both the routes to be rendered ie. lhstree should be rendered within home template. For this purpose, I used named outlet. That worked fine.
But the problem is, I need to supply data to the lhstree template. But the model hook for the lhstree template is never called. I even tried adding alert messages in the model hook, but that too is never executed. The below is my code. Any help is appreciated.

router.js:

Router.map(function() {
 this.route('home');
 this.route('lhstree');
});

home.hbs:

    Home hbs rendering
    {{outlet 'lhstree'}}

home.js:

export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }
});

lhstree.hbs:

  {{#each model as |player|}}

{{player}}

  {{/each}}

lhstree.js:

model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
}

As I mentioned, the model hook of lhstree route is never called. So, the player names Player1 and Player2 are never displayed when home template is rendered.


问:
Print double quotations with WshShell.Sendkeys and windows batch
I have a script that changes the users directory and prefills the input with a command, so he only has to look it over and change values before pressing enter. The command that's going to be written requires double quotations and I cannot get it to print this in the input. I've tried various of escape characters like ^", \", "", """ and {"} but I get none of them to work. I use the WshShell for this but if it's not possible using it and there's a better way that will solve this then I'm all ears.

The goal is that the user will see this in command window:

```<code>command.exe parameter="hello" parameter2="world"
</code>```

The .bat file:

```<code>@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "echo Hello World!{ENTER}"
%SendKeys% "cd C:\temp{ENTER}"
%SendKeys% "command.exe parameter="hello" parameter2="world""
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
</code>```

Source for batscript: https://stackoverflow.com/a/22772040/1350598

答:
Use %SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'" and change the last line by WshShell.SendKeys(eval(WScript.Arguments(0)));. Note that you need to add the apostrophe ' at begin-end of all strings; that is:

```<code>@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "'echo Hello World!{ENTER}'"
%SendKeys% "'cd C:\temp{ENTER}'"
%SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'"
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(eval(WScript.Arguments(0)));
</code>```

Body:
I have a script that changes the users directory and prefills the input with a command, so he only has to look it over and change values before pressing enter. The command that's going to be written requires double quotations and I cannot get it to print this in the input. I've tried various of escape characters like ^", \", "", """ and {"} but I get none of them to work. I use the WshShell for this but if it's not possible using it and there's a better way that will solve this then I'm all ears.

The goal is that the user will see this in command window:

command.exe parameter="hello" parameter2="world"

The .bat file:

@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "echo Hello World!{ENTER}"
%SendKeys% "cd C:\temp{ENTER}"
%SendKeys% "command.exe parameter="hello" parameter2="world""
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

Source for batscript: https://stackoverflow.com/a/22772040/1350598

Body:
Use %SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'" and change the last line by WshShell.SendKeys(eval(WScript.Arguments(0)));. Note that you need to add the apostrophe ' at begin-end of all strings; that is:

@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start cmd.exe program
start "" cmd
rem Send whatever you want to previous cmd.exe
%SendKeys% "'echo Hello World!{ENTER}'"
%SendKeys% "'cd C:\temp{ENTER}'"
%SendKeys% "'command.exe parameter=\u0022hello\u0022 parameter2=\u0022world\u0022'"
set /P "="
ECHO TERMINATE ORIGINAL BATCH
goto :EOF
@end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(eval(WScript.Arguments(0)));


问:
Failed to check against Nt Authority\System SID
I have a process which can be spawned by a service with either NT AUTHORITY\Network Service or NT AUTHORITY\System, and i need to check for it. So i have written a code like this:

```<code>if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken)) {

        GetTokenInformation(hToken, 1, 0, 0, &dwOut);
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
            hTokenUser = (TOKEN_USER*)malloc( dwOut );
            if (!GetTokenInformation(hToken, TokenUser, hTokenUser, dwOut, &dwOut))
                return false;
        }
        else
            return false;

        PSID psid = NULL;
        SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
        AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &psid);

        if (EqualSid(psid, hTokenUser->User.Sid)) {
            bResult = TRUE;
        }
}
</code>```

So what i do, i get current process token, and i get a SID from it using GetTokenInfo then i create the NT_AUTHORITY\System SID, using AllocateAndInitializeSid, and i compare two values together, however, it never works, when the process is run under NT_AUTHORITY\System check is always failing. Is this the correct way to get NT_AUTHORITY\System SID and compare it with the process sid?

答:
Your code leaks handles and memory but it does provide the correct result on my machine. It might be different on your system so it would really help if you print out the result and GetLastError of every function call to help you debug. You should also code your function so you can tell the difference between errors and a negative (successful) result.

```<code>HRESULT isSystemUser()
{
    HRESULT hr = E_FAIL;
    HANDLE hToken;
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
    {
        TOKEN_USER *pTU = NULL;
        DWORD dwOut;
        GetTokenInformation(hToken, TokenUser, 0, 0, &dwOut);
        hr = HRESULT_FROM_WIN32(GetLastError());
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            pTU = (TOKEN_USER*) malloc(dwOut), hr = E_OUTOFMEMORY;
        if (pTU)
        {
            if (GetTokenInformation(hToken, TokenUser, pTU, dwOut, &dwOut))
            {
                PSID psid = NULL;
                SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
                if (AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &psid))
                {
                    hr = EqualSid(psid, pTU->User.Sid) ? S_OK : S_FALSE;
                    FreeSid(psid);
                }
                else
                    hr = HRESULT_FROM_WIN32(GetLastError());

            }
            else
                hr = HRESULT_FROM_WIN32(GetLastError());
            free(pTU);
        }
        CloseHandle(hToken);
    }
    else
        hr = HRESULT_FROM_WIN32(GetLastError());
    return hr;
}

...

    printf("isSystemUser=%d\n", isSystemUser()); // 0 = true, 1 = false, < 0 = error
</code>```

and when running it:

```<code>C:\windows\system32>c:\test.exe
isSystemUser=0

C:\windows\system32>whoami
nt authority\system
</code>```

Is it possible that you are not actually running as the real System user? What does ConvertSidToStringSid return for your TokenUser?

Body:
I have a process which can be spawned by a service with either NT AUTHORITY\Network Service or NT AUTHORITY\System, and i need to check for it. So i have written a code like this:

if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken)) {

        GetTokenInformation(hToken, 1, 0, 0, &dwOut);
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
            hTokenUser = (TOKEN_USER*)malloc( dwOut );
            if (!GetTokenInformation(hToken, TokenUser, hTokenUser, dwOut, &dwOut))
                return false;
        }
        else
            return false;

        PSID psid = NULL;
        SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
        AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &psid);

        if (EqualSid(psid, hTokenUser->User.Sid)) {
            bResult = TRUE;
        }
}

So what i do, i get current process token, and i get a SID from it using GetTokenInfo then i create the NT_AUTHORITY\System SID, using AllocateAndInitializeSid, and i compare two values together, however, it never works, when the process is run under NT_AUTHORITY\System check is always failing. Is this the correct way to get NT_AUTHORITY\System SID and compare it with the process sid?

Body:
Your code leaks handles and memory but it does provide the correct result on my machine. It might be different on your system so it would really help if you print out the result and GetLastError of every function call to help you debug. You should also code your function so you can tell the difference between errors and a negative (successful) result.

HRESULT isSystemUser()
{
    HRESULT hr = E_FAIL;
    HANDLE hToken;
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
    {
        TOKEN_USER *pTU = NULL;
        DWORD dwOut;
        GetTokenInformation(hToken, TokenUser, 0, 0, &dwOut);
        hr = HRESULT_FROM_WIN32(GetLastError());
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            pTU = (TOKEN_USER*) malloc(dwOut), hr = E_OUTOFMEMORY;
        if (pTU)
        {
            if (GetTokenInformation(hToken, TokenUser, pTU, dwOut, &dwOut))
            {
                PSID psid = NULL;
                SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
                if (AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &psid))
                {
                    hr = EqualSid(psid, pTU->User.Sid) ? S_OK : S_FALSE;
                    FreeSid(psid);
                }
                else
                    hr = HRESULT_FROM_WIN32(GetLastError());

            }
            else
                hr = HRESULT_FROM_WIN32(GetLastError());
            free(pTU);
        }
        CloseHandle(hToken);
    }
    else
        hr = HRESULT_FROM_WIN32(GetLastError());
    return hr;
}

...

    printf("isSystemUser=%d\n", isSystemUser()); // 0 = true, 1 = false, < 0 = error

and when running it:

C:\windows\system32>c:\test.exe
isSystemUser=0

C:\windows\system32>whoami
nt authority\system

Is it possible that you are not actually running as the real System user? What does ConvertSidToStringSid return for your TokenUser?


问:
Vertical align of different buttons inside a div
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<div class="Languages">
    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>

 <div class="Languages">
    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>  </code>```

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

答:
The thing is you're not taking into account the line heights.
Actually, I would do everything using em and %, this is cross-platform and multi-screen solution.
Here's my result (every element that has position: relative; should also have float:left):

https://jsfiddle.net/525n53y8/

```<code>    .a {
  height: .45em;
  margin-top: 1.575em
}

.b {
  height: .9em;
  margin-top: 1.4em;
}

.c {
  height: 1.8em;
  margin-top: .9em;
}

.d {
  height: 3.6em;
}
</code>```

every element that has css: "position: relative;" should also have float:left;
then the solution in em and % (see fiddle) would be for blocks:
https://jsfiddle.net/k3e84v0x/

```<code>    .a {
  height: 5px;
  margin-top: 28.5px;
}

.b {
  height: 25px;
  margin-top: 18.5px;
}

.c {
  height: 45px;
  margin-top: 8.5px;
}

.d {
  height: 62px;
}
</code>```

Body:
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }

    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

Body:
The thing is you're not taking into account the line heights.
Actually, I would do everything using em and %, this is cross-platform and multi-screen solution.
Here's my result (every element that has position: relative; should also have float:left):

https://jsfiddle.net/525n53y8/

    .a {
  height: .45em;
  margin-top: 1.575em
}

.b {
  height: .9em;
  margin-top: 1.4em;
}

.c {
  height: 1.8em;
  margin-top: .9em;
}

.d {
  height: 3.6em;
}

every element that has css: "position: relative;" should also have float:left;
then the solution in em and % (see fiddle) would be for blocks:
https://jsfiddle.net/k3e84v0x/

    .a {
  height: 5px;
  margin-top: 28.5px;
}

.b {
  height: 25px;
  margin-top: 18.5px;
}

.c {
  height: 45px;
  margin-top: 8.5px;
}

.d {
  height: 62px;
}


问:
Can I restore a modified removed file with Mercurial?
I was deleting some files, but I also deleted a modified file that I hadn't done the commit yet.

Is there any way to restore this file?

Mercurial has deleted the local file too.

答: Unless you commit a file there's nothing to recover from. However if there file was committed at least once then you can use this to help you restore it: How can I recover a removed file in Mercurial (if at all)?</p>


问:
Make fragment transition animate views simultaneously
I am replacing a fragment A with a fragment B and animating this. Fragment B has a RelativeLayout with a TextView and a ListView. What I could see is that the views in fragment B are being animated separately, the TextView slides in with a different velocity than the list item 1 subtitle, while list item 1 title and icon appear instantly without animation, I would like the whole view to animate at the same time, is this possible to achieve?

```<code>    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment existing = fragmentManager.findFragmentById(R.id.welcome_content);
    if (existing != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            fragmentToLoad.setAllowEnterTransitionOverlap(true);
            fragmentToLoad.setEnterTransition(new Slide(Gravity.RIGHT));
        }
        fragmentTransaction.remove(existing);
    }
    fragmentTransaction.add(R.id.welcome_content, fragmentToLoad);
    fragmentTransaction.commitNow();
</code>```

答:
Apply android:transitionGroup="true" to the root layout of FragmentB.

From docs of ViewGroup#setTransitionGroup(boolean):

Changes whether or not this ViewGroup should be treated as a single entity during Activity Transitions. If false, the ViewGroup won't transition, only its children. If true, the entire ViewGroup will transition together.

Body:
I am replacing a fragment A with a fragment B and animating this. Fragment B has a RelativeLayout with a TextView and a ListView. What I could see is that the views in fragment B are being animated separately, the TextView slides in with a different velocity than the list item 1 subtitle, while list item 1 title and icon appear instantly without animation, I would like the whole view to animate at the same time, is this possible to achieve?

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment existing = fragmentManager.findFragmentById(R.id.welcome_content);
    if (existing != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            fragmentToLoad.setAllowEnterTransitionOverlap(true);
            fragmentToLoad.setEnterTransition(new Slide(Gravity.RIGHT));
        }
        fragmentTransaction.remove(existing);
    }
    fragmentTransaction.add(R.id.welcome_content, fragmentToLoad);
    fragmentTransaction.commitNow();


问:
Hide errors in console chrome?
Currently user of google Chrome, I wish when I'm in my console, that my javascript errors are not displayed.
I have long this feature on the forums, without success!</p>

答: In the Console click the "Default levels" drop down, then select "Errors" to un-check it. This will hide error messages from the console.

Title: Hide errors in console chrome?


问:
Visual Studio add-in for validating string.Format method
string.Format is a very risky method. There are a lot of thing that could go wrong, without any compilation errors:

```<code>string.Format("{0{", text);
string.Format("{1}", text);
string.Format("(0)", text);
string.Format("{0}", text1, text2);
</code>```

I'm looking for a way to find this problems in compilation time. If I remember correctly, Resharper find some of those errors, but it's too rich for my blood.

答:
Resharper does that for you -- even at edit time :-).

However be aware that things like

```<code>String.Format("{0} blabla", foo, bar);
</code>```

Do not generate an error (after all, deciding to hide a value is perfectly fine).

Body:
string.Format is a very risky method. There are a lot of thing that could go wrong, without any compilation errors:

string.Format("{0{", text);
string.Format("{1}", text);
string.Format("(0)", text);
string.Format("{0}", text1, text2);

I'm looking for a way to find this problems in compilation time. If I remember correctly, Resharper find some of those errors, but it's too rich for my blood.

Body:
Resharper does that for you -- even at edit time :-).

However be aware that things like

String.Format("{0} blabla", foo, bar);

Do not generate an error (after all, deciding to hide a value is perfectly fine).


问:
perform onclick event in reactjs
I am trying to make an application using reactjs.below is the code which present in my main app.js:

```<code>class App extends Component {
    return (
        <div>
            <ExampleTable
                header={() => <TopBar/>}
            />
            <AddExampleModal/>
            <ChartModal/>
            <CompatibilityAlert/>
        </div>
    )
  }
}
</code>```

where Top Bat,AddExampleModal , ChartModal and CompatibilityAlert are loaded from other js files.

Chartmodal contains:

```<code>class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={true}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
</code>```

Topbar contains :

```<code>class TopBar extends Component {
    render{
            return (
            <Button
                style={styles.button}
                type='primary'
               // onClick={() => changechartshow()}
            >
                Show Graph
            </Button>
           )
         }
      }
</code>```

The thing is that in the app file,i want to toggle the visibility of chartmodal using the button in the topbar.

答:
You can add a state in your App component and pass an handler to update the state from the TopBar component. Based on this state you can toggle the visibility of ChartModal.

```<code>class App extends Component {
    state = {
      isVisible: true
    }
    toggleVisibility = () => {
       this.setState(prevState => ({isVisible: !prevState.isVisible}))
    }
    return (
        <div>
            <ExampleTable
                header={() => <TopBar toggleVisibility={this.toggleVisibility}/>}
            />
            <AddExampleModal/>
            {this.state.isVisible ? <ChartModal/>: null }
            <CompatibilityAlert/>
        </div>
    )
  }
}
</code>```

Now in your TopBar you will call this function as

```<code>class TopBar extends Component {
    render{
        return (
        <Button
            style={styles.button}
            type='primary'
            onClick={() => this.props.toggleVisibility()}
        >
            Show Graph
        </Button>
       )
     }
  }
</code>```

Read the React docs here on Lifting the state up for a detailed explanation

Title: perform onclick event in reactjs

Body:
I am trying to make an application using reactjs.below is the code which present in my main app.js:

class App extends Component {
    return (

            <ExampleTable
                header={() => <TopBar/>}
            />
            <AddExampleModal/>
            <ChartModal/>
            <CompatibilityAlert/>

    )
  }
}

where Top Bat,AddExampleModal , ChartModal and CompatibilityAlert are loaded from other js files.

Chartmodal contains:

class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={true}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >

HOWDY

            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}

Topbar contains :

class TopBar extends Component {
    render{
            return (
            <Button
                style={styles.button}
                type='primary'
               // onClick={() => changechartshow()}
            >
                Show Graph
            </Button>
           )
         }
      }

The thing is that in the app file,i want to toggle the visibility of chartmodal using the button in the topbar.

Body:
You can add a state in your App component and pass an handler to update the state from the TopBar component. Based on this state you can toggle the visibility of ChartModal.

class App extends Component {
    state = {
      isVisible: true
    }
    toggleVisibility = () => {
       this.setState(prevState => ({isVisible: !prevState.isVisible}))
    }
    return (
        <div>
            <ExampleTable
                header={() => <TopBar toggleVisibility={this.toggleVisibility}/>}
            />
            <AddExampleModal/>
            {this.state.isVisible ? <ChartModal/>: null }
            <CompatibilityAlert/>
        </div>
    )
  }
}

Now in your TopBar you will call this function as

class TopBar extends Component {
    render{
        return (
        <Button
            style={styles.button}
            type='primary'
            onClick={() => this.props.toggleVisibility()}
        >
            Show Graph
        </Button>
       )
     }
  }

Read the React docs here on Lifting the state up for a detailed explanation


问:
“Error 42P01: relation does not exist” (non public schema in PostgreSQL)
I want to create a foreign key but I got Error 42P01: relation solicitantes does not exist.

I have to schemas: public and laboratorio.

My table is called procedencias. I want to create a foreign key to solicitantes table. Both belongs to laboratorio schema. Even the autocomplete of the target table field works and find the table.

I see that:

I can create the foreing key to any tables of the public schema.

I can't create the foreing key to any tables of the laboratorio schema.
Error when creating a foreign key.

I am using Jetbrains DataGrip software.

This is the DDL of the table called "solicitantes":

```<code>CREATE TABLE laboratorio.solicitantes
(
  id_solicitante serial NOT NULL,
  nombre_solicitante character varying(100) NOT NULL,
  CONSTRAINT solicitantes_pkey PRIMARY KEY (id_solicitante)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE laboratorio.solicitantes
  OWNER TO roby;

CREATE UNIQUE INDEX solicitantes_id_solicitante_uindex
  ON laboratorio.solicitantes
  USING btree
  (id_solicitante);

CREATE UNIQUE INDEX solicitantes_nombre_solicitante_uindex
  ON laboratorio.solicitantes
  USING btree
  (nombre_solicitante COLLATE pg_catalog."default");
</code>```

I think I have to specify the schema name but I don't know where to do it in DataGrip.

答: have you tried to add the explicit schema to the table solicitantes?</p>

Body:
I want to create a foreign key but I got Error 42P01: relation solicitantes does not exist.

I have to schemas: public and laboratorio.

My table is called procedencias. I want to create a foreign key to solicitantes table. Both belongs to laboratorio schema. Even the autocomplete of the target table field works and find the table.

I see that:

I can create the foreing key to any tables of the public schema.

I can't create the foreing key to any tables of the laboratorio schema.
Error when creating a foreign key.

I am using Jetbrains DataGrip software.

This is the DDL of the table called "solicitantes":

CREATE TABLE laboratorio.solicitantes
(
  id_solicitante serial NOT NULL,
  nombre_solicitante character varying(100) NOT NULL,
  CONSTRAINT solicitantes_pkey PRIMARY KEY (id_solicitante)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE laboratorio.solicitantes
  OWNER TO roby;

CREATE UNIQUE INDEX solicitantes_id_solicitante_uindex
  ON laboratorio.solicitantes
  USING btree
  (id_solicitante);

CREATE UNIQUE INDEX solicitantes_nombre_solicitante_uindex
  ON laboratorio.solicitantes
  USING btree
  (nombre_solicitante COLLATE pg_catalog."default");

I think I have to specify the schema name but I don't know where to do it in DataGrip.


问:
How to make footer stick to the bottom
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

```<code><div id="footer">
<div class="container">
    <div class="row">
        <h3 class="footertext">About Us:</h3>
        <br>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/w8lycl.jpg" class="img-circle" alt="the-brains">
              <br>
              <h4 class="footertext">Programmer</h4>
              <p class="footertext">You can thank all the crazy programming here to this guy.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi60.tinypic.com/2z7enpc.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Artist</h4>
              <p class="footertext">All the images here are hand drawn by this man.<br>
            </center>
          </div>
          <div class="col-md-4">
            <center>
              <img src="http://oi61.tinypic.com/307n6ux.jpg" class="img-circle" alt="...">
              <br>
              <h4 class="footertext">Designer</h4>
              <p class="footertext">This pretty site and the copy it holds are all thanks to this guy.<br>
            </center>
          </div>
        </div>
        <div class="row">

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

I tried to use

```<code><div class="footer navbar-fixed-bottom">
</code>```

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

```<code>    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}
</code>```

Here is what I mean by ugly. I did try to set html and body height as 100% in css

答:
Please show us what you mean by "looks ugly" so we can help you, because we can't really understand your issue.

I'd say the problem could be in what the parent of #footer div.

Title: How to make footer stick to the bottom

Body:
I am having a problem with my footer. I am trying to force it to the bottom, but it always looks ugly.

Here is the code:

About Us:

Programmer

You can thank all the crazy programming here to this guy.

Artist

All the images here are hand drawn by this man.

Designer

This pretty site and the copy it holds are all thanks to this guy.

I tried to use

but in that case my text ,which is located over the footer, get overlapped by footer

Here is css I used:

    #footer {
padding-top: 100px
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Sets the fixed height of the footer here */
  height: 280px;
  background:
  /* color overlay */
    linear-gradient(
      rgba(240, 212, 0, 0.45),
      rgba(0, 0, 0, 0.45)
    ),
    /* image to overlay */
    url(222.png);
}
.footertext {
  color: #ffffff;
}

Here is what I mean by ugly. I did try to set html and body height as 100% in css


问:
Marshaling LPBYTE
I have hex_data struct as output of a function of a DLL.

```<code>typedef struct hex_data
{
 USHORT usLength;
 LPBYTE lpbData;
 } HEXDATA
</code>```

where lpbData is a pointer to the byte stream and usLength is the length of the byte stream pointed to by lpbData. Now I need to marshal this struct to a C# struct. What unmanged type I should use for lpbData in below struct definition:

```<code>[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
 public struct HEXDATA {
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 usLength;
        [MarshalAs(UnmanagedType.?????)]
        public byte[] lpbData;
    } ;
</code>```

Thanks

答:
LPBYTE is a pointer to a byte array.  Since its a pointer to an array, you would use the LPArray type.

https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-arrays

Title: Marshaling LPBYTE

Body:
I have hex_data struct as output of a function of a DLL.

typedef struct hex_data
{
 USHORT usLength;
 LPBYTE lpbData;
 } HEXDATA

where lpbData is a pointer to the byte stream and usLength is the length of the byte stream pointed to by lpbData. Now I need to marshal this struct to a C# struct. What unmanged type I should use for lpbData in below struct definition:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
 public struct HEXDATA {
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 usLength;
        [MarshalAs(UnmanagedType.?????)]
        public byte[] lpbData;
    } ;

Thanks


问:
How to import codes in .html file which are placed in a txt file ?
So, what i want is this. I have an HTML File and i want the code to load from a text file. So, the browser should get the code from that text file and read it as a part of the HTML code. Here is an example:

Suppose I have an HTML File whose code is :-

```<code><html>
<head></head>
<body>

<div src="code.txt"></div> [ I made this code. I know this code does not exist.]

</body>
</html>
</code>```

And i have text file named 'code.text' :

```<code><h2>Welcome</h2>
<img src="sample.jpg">
<p>This is the paragraph.</p>
</code>```

So, instead of writing code in the actual HTML File, i saved the codes in a text file and want to use them whenever i want. I know the following code does not exist.

```<code><div src="code.text"></div>

I made up this code just to show what i want.
</code>```

**

Just tell me the way i can achieve this purpose.

**

Thanks,

Waiting for your answer !

答:
You can load the content of this with jQuery ajax. Your div will look like this:

And you call the document using ajax:

```<code>$.ajax("code.text").done( html =>{ $('#content').html(html) });
</code>```

You can view more on http://api.jquery.com/jquery.ajax/

Body:
So, what i want is this. I have an HTML File and i want the code to load from a text file. So, the browser should get the code from that text file and read it as a part of the HTML code. Here is an example:

Suppose I have an HTML File whose code is :-

 [ I made this code. I know this code does not exist.]

And i have text file named 'code.text' :

Welcome

This is the paragraph.

So, instead of writing code in the actual HTML File, i saved the codes in a text file and want to use them whenever i want. I know the following code does not exist.

I made up this code just to show what i want.

**

Just tell me the way i can achieve this purpose.

**

Thanks,

Waiting for your answer !

Body:
You can load the content of this with jQuery ajax. Your div will look like this: <div id="content"></div>

And you call the document using ajax:

$.ajax("code.text").done( html =>{ $('#content').html(html) });

You can view more on http://api.jquery.com/jquery.ajax/


问:
bash: append newline when redirecting file
Here is how I read a file row by row:

```<code>while read ROW
do
...
done < file
</code>```

I don't use the other syntax

```<code>cat file | while read ROW
do
...
done
</code>```

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

```<code>(cat file; echo) | while read ROW
do
...
done
</code>```

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?

答:
```<code>#!/bin/bash

while read ROW
 ...
done < <(cat file ; echo)
</code>```

Body:
Here is how I read a file row by row:

while read ROW
do
...
done < file

I don't use the other syntax

cat file | while read ROW
do
...
done

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

(cat file; echo) | while read ROW
do
...
done

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?


问:
Date range from today's date ordered by DD/MM/YYYY for the next week
My table column titled "property_appointment" is formatted as DD/MM/YYYY and it is too far gone to change to a default date and time setting due to the amount of data that exists.

What I am having trouble with is getting a range of appointments (sorted by the date) to show from today's date going forward, i.e. the query should show the next 6 appointments in the system from today's date. Currently it is showing appointments scheduled for next year that are booked, which isn't helpful when I want to see a small forecast for the upcoming week, as it is sorting the dates by descending order. It hasn't been instructed to show appointments from today onwards and I have tried many things but I still cannot figure this out.

I know the date format is making this very difficult to achieve, but is there a workaround for my current date format to achieve the above? Any help is much appreciated!

```<code>if($properties = $db->prepare("
SELECT id
     , property_address_line_1
     , property_appointment
     , property_appointment_type
  FROM users
  JOIN properties
    ON id = property_user_id
 WHERE id = ?
 ORDER
    BY STR_TO_DATE(property_appointment,'%d/%m/%Y') DESC
 LIMIT 6
 "))
</code>```

答:
```<code>SELECT id
     , property_address_line_1
     , property_appointment
     , property_appointment_type
  FROM users
  JOIN properties
    ON id = property_user_id
 WHERE id = ?
   AND STR_TO_DATE(property_appointment,'%d/%m/%Y')  > CURDATE()
 ORDER BY STR_TO_DATE(property_appointment,'%d/%m/%Y')
 LIMIT 6
</code>```

Body:
My table column titled "property_appointment" is formatted as DD/MM/YYYY and it is too far gone to change to a default date and time setting due to the amount of data that exists.

What I am having trouble with is getting a range of appointments (sorted by the date) to show from today's date going forward, i.e. the query should show the next 6 appointments in the system from today's date. Currently it is showing appointments scheduled for next year that are booked, which isn't helpful when I want to see a small forecast for the upcoming week, as it is sorting the dates by descending order. It hasn't been instructed to show appointments from today onwards and I have tried many things but I still cannot figure this out.

I know the date format is making this very difficult to achieve, but is there a workaround for my current date format to achieve the above? Any help is much appreciated!

if($properties = $db->prepare("
SELECT id
     , property_address_line_1
     , property_appointment
     , property_appointment_type
  FROM users
  JOIN properties
    ON id = property_user_id
 WHERE id = ?
 ORDER
    BY STR_TO_DATE(property_appointment,'%d/%m/%Y') DESC
 LIMIT 6
 "))


问:
geojson as url source + turf.js + manipulation of subset of features' properties
mapbox-gl-js version: >=0.27.0 <=0.38.0

(1) I have a Feature geojson type of a single polygon adding to my map from a url source.

(2) I also have a FeatureCollection geojson type of ~4k polygons adding to the map also from a url source.

I use turf.intersect between (1) and (2) to select the intersecting polygons of (2).

I then store the intersecting polygons [a sub-set of (2)] to an array.

I then manipulate the values of some properties of those intersecting polygons
with simple math.

I now want to update (2) with the resulting values of the array.

I would love to use something like setData to update (2), but that is not possible for a subset which also is not (a) a geojson data object or (b) a url to one as specified in the docs.

Hopefully I have explained this sufficiently.  If so, what is the suggested workflow in this case?

答:
Mapbox is not good at sharing if you let it load the GeoJSON; see https://github.com/mapbox/mapbox-gl-js/issues/1762 If you want to manipulate the data yourself, you should load it yourself, then pass it to Mapbox. For example:</p>

```<code>// load your data via ajax however you want
const promises = {
  polygon: $.get('.../geojson.json'),
  collection: $.get('.../feature-collection.json'),
};

// setup your map
const map = new mapboxgl.Map({...});
map.on('load', () => {
  RSVP.hash(promises).then((data) => {
    map.addSource('my-data', {
      type: 'geojson',
      // transform does intersection and updates,
      // then outputs a GeoJSON formatted object
      data: transform(data.polygon, data.collection),
    });
  });
});
</code>```

Body:
Mapbox is not good at sharing if you let it load the GeoJSON; see https://github.com/mapbox/mapbox-gl-js/issues/1762 If you want to manipulate the data yourself, you should load it yourself, then pass it to Mapbox. For example:

// load your data via ajax however you want
const promises = {
  polygon: $.get('.../geojson.json'),
  collection: $.get('.../feature-collection.json'),
};

// setup your map
const map = new mapboxgl.Map({...});
map.on('load', () => {
  RSVP.hash(promises).then((data) => {
    map.addSource('my-data', {
      type: 'geojson',
      // transform does intersection and updates,
      // then outputs a GeoJSON formatted object
      data: transform(data.polygon, data.collection),
    });
  });
});


问:
C -error: expected ';', ',' or ')' before '=' token
I need help. It's displaying "error: expected ';', ',' or ')' before '=' token"
at line 5 (at the getRandom method) when i try to build and then run it. I've gone through it several times over and over again and i can't seem to figure out what the problem could be</p>

```<code>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}

int totalPoints = 0;
int pointsInCircle = 0;

void *countPoints (void *X) {
    for (int i = 0; i < totalPoints; i++) {
        double X = getRandom();
        double Y = getRandom();
        if (X*X + Y*Y <= 1)pointsInCircle++;
    }
    return NULL;
}

int main()
{
    srand(time(NULL));
    pthread_t thread;
    printf ("Enter total points for experiment : ");
    scanf  ("%d" , totalPoints);
    pthread_create(&thread, NULL, &countPoints, NULL);
    pthread_join(thread, NULL);

    double PI = (4.0 * pointsInCircle) / totalPoints;
    printf ("Approximate value for PI for total points %d is: %d " , totalPoints, PI);

    return 0;
}
</code>```

答:
```<code>double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}
</code>```

This is not C.

```<code>double getRandom (double min, double max) {
    return min + (rand() * (max - min) / RAND_MAX);
}
</code>```

When you call it with no actual arguments in your code

```<code>    double X = getRandom();
    double Y = getRandom();
</code>```

you should replace these calls with

```<code>    double X = getRandom(-1, 1);
    double Y = getRandom(-1, 1);
</code>```

Body:
I need help. It's displaying "error: expected ';', ',' or ')' before '=' token"
at line 5 (at the getRandom method) when i try to build and then run it. I've gone through it several times over and over again and i can't seem to figure out what the problem could be

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}

int totalPoints = 0;
int pointsInCircle = 0;

void *countPoints (void *X) {
    for (int i = 0; i < totalPoints; i++) {
        double X = getRandom();
        double Y = getRandom();
        if (X*X + Y*Y <= 1)pointsInCircle++;
    }
    return NULL;
}

int main()
{
    srand(time(NULL));
    pthread_t thread;
    printf ("Enter total points for experiment : ");
    scanf  ("%d" , totalPoints);
    pthread_create(&thread, NULL, &countPoints, NULL);
    pthread_join(thread, NULL);

    double PI = (4.0 * pointsInCircle) / totalPoints;
    printf ("Approximate value for PI for total points %d is: %d " , totalPoints, PI);

    return 0;
}

Body:
double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}

This is not C.

double getRandom (double min, double max) {
    return min + (rand() * (max - min) / RAND_MAX);
}

When you call it with no actual arguments in your code

    double X = getRandom();
    double Y = getRandom();

you should replace these calls with

    double X = getRandom(-1, 1);
    double Y = getRandom(-1, 1);


问:
How to make datastore query faster without adding indices
I have the following simple query:

```<code> client = datastore.Client('fmy_project')
 query = client.query(kind='kind1')
 query.add_filter('x', '=','y')
 for row in query.fetch():
   #process the row and save to file
</code>```

It takes me for 100 rows 5 seconds to fetch the results when working from a local machine. This is awfully slow.

when i make strace on the python process i get many rows of:

recvmsg(9, 0x7ffffc9ee9f0, 0)           = -1 EAGAIN (Resource temporarily unavailable)

poll([{fd=8, events=POLLIN}, {fd=9, events=POLLIN}], 2, 200) = 0 (Timeout)

Is there a way to say datastore to fetch everything in one go or make a certain other optimization?

I googled and did not find any related option

答:
Are you saying it takes 5 seconds only to fetch? Without processing the data in your for loop at the end?

Generally it's better if you:

Fetch the data (fetch returns a list of the data)

Process the data on the returned list itself (do not save to datastore within your loop!)

Save multiple rows at once using "put_multi"

ndb.put_multi(dataList)

See docs here: https://cloud.google.com/datastore/docs/concepts/entities#batch_operations

Body:
I have the following simple query:

 client = datastore.Client('fmy_project')
 query = client.query(kind='kind1')
 query.add_filter('x', '=','y')
 for row in query.fetch():
   #process the row and save to file

It takes me for 100 rows 5 seconds to fetch the results when working from a local machine. This is awfully slow.

when i make strace on the python process i get many rows of:

recvmsg(9, 0x7ffffc9ee9f0, 0)           = -1 EAGAIN (Resource temporarily unavailable)

poll([{fd=8, events=POLLIN}, {fd=9, events=POLLIN}], 2, 200) = 0 (Timeout)

Is there a way to say datastore to fetch everything in one go or make a certain other optimization?

I googled and did not find any related option


问:
Add jQuery-Knob in Angular 2
I am new to Angular 2.0 and using aspnetboilerplate template.

I am trying to integrate jQuery-Knob.

First, I included jquery.knob.min.js in scripts in .angular-cli.json:

```<code>"scripts":
[
    "../src/bsb-theme/js/jquery.validate.js",
    "../src/bsb-theme/js/jquery.knob.min.js"
]
</code>```

Then, I made an input in dashboard.component.html:

```<code><input type="text" class="knob" value="40"
    data-width="125"
    data-height="125"
    data-thickness="0.25"
    data-angleArc="250"
    data-angleoffset="-35"
    data-fgColor="#00BCD4">
</code>```

But the output is a text box only.

答:
jQuery-Knob doesn't work out-of-the-box with Angular 2.

Try this library: https://github.com/xzegga/angular2-knob

Usage

IMPORTING ANGULAR MODULE:

import { KnobModule } from "angular2-knob";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [KnobModule]
  bootstrap: [AppComponent]
})
```

<h3>HTML USE:</h3>

<pre class="lang-js prettyprint-override"><code><div ui-knob [value]="value" [options]="knOptions"></div>
</code>```

CONFIGURING OPTIONS IN ANGULAR COMPONENT:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  knOptions = {
    readOnly: true,
    size: 140,
    unit: '%',
    textColor: '#000000',
    fontSize: '32',
    fontWeigth: '700',
    fontFamily: 'Roboto',
    valueformat: 'percent',
    value: 0,
    max: 100
    trackWidth: 19,
    barWidth: 20,
    trackColor: '#D8D8D8',
    barColor: '#FF6F17',
    subText: {
      enabled: true,
      fontFamily: 'Verdana',
      font: '14',
      fontWeight: 'bold',
      text: 'Overall',
      color: '#000000',
      offset: 7
    },
  }
  value = 45;
}
```

Title: Add jQuery-Knob in Angular 2

Body:
I am new to Angular 2.0 and using aspnetboilerplate template.

I am trying to integrate jQuery-Knob.

First, I included jquery.knob.min.js in scripts in .angular-cli.json:

"scripts":
[
    "../src/bsb-theme/js/jquery.validate.js",
    "../src/bsb-theme/js/jquery.knob.min.js"
]

Then, I made an input in dashboard.component.html:

<input type="text" class="knob" value="40"
    data-width="125"
    data-height="125"
    data-thickness="0.25"
    data-angleArc="250"
    data-angleoffset="-35"
    data-fgColor="#00BCD4">

But the output is a text box only.

Body:
jQuery-Knob doesn't work out-of-the-box with Angular 2.

Try this library: https://github.com/xzegga/angular2-knob

Usage

IMPORTING ANGULAR MODULE:

import { KnobModule } from "angular2-knob";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [KnobModule]
  bootstrap: [AppComponent]
})

HTML USE:

<div ui-knob [value]="value" [options]="knOptions"></div>

CONFIGURING OPTIONS IN ANGULAR COMPONENT:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  knOptions = {
    readOnly: true,
    size: 140,
    unit: '%',
    textColor: '#000000',
    fontSize: '32',
    fontWeigth: '700',
    fontFamily: 'Roboto',
    valueformat: 'percent',
    value: 0,
    max: 100
    trackWidth: 19,
    barWidth: 20,
    trackColor: '#D8D8D8',
    barColor: '#FF6F17',
    subText: {
      enabled: true,
      fontFamily: 'Verdana',
      font: '14',
      fontWeight: 'bold',
      text: 'Overall',
      color: '#000000',
      offset: 7
    },
  }
  value = 45;
}


答:
Open Console Settings

Then check User messages only option.

It should works.

Title: Hide errors in console chrome?

Body:
Currently user of google Chrome, I wish when I'm in my console, that my javascript errors are not displayed.
I have long this feature on the forums, without success!


问:
UISplitViewController delegate methods not called
I am using a UISplitViewController inside a UITabBarController with a plain UIViewController in the master pane of the split view and a UINavigationController in the detail pane, which itself contains a vanilla UIViewController.

I am aware that Apple advise to use split views at the root level only, however I have seen other applications (eg, Amazon- 'Wish List' tab) that use split views in tabs so I'm sure it's possible.

My problem is that the delegate methods of the split view, ie. those in UISplitViewControllerDelegate do not get called, which prevents me from creating my pop-over menu when switching into Portrait mode.

The methods in question are the following -

```<code>// Called when a button should be added to a toolbar for a hidden view controller
- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc;

// Called when the view is shown again in the split view, invalidating the button and popover controller
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem;

// Called when the view controller is shown in a popover so the delegate can take action like hiding other popovers.
- (void)splitViewController: (UISplitViewController*)svc popoverController: (UIPopoverController*)pc willPresentViewController:(UIViewController *)aViewController;
</code>```

The UISplitViewController does receive the rotation notifications.

I can get the willShowViewController method to be called if I force the status bar orientation to landscape right (or left) at the beginning of the app launch, using

```<code> [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
</code>```

However, the willHideViewController doesn't get called.  And I don't want to force the app to start in landscape.  If I do the same thing but force it to portrait, I don't receive the callbacks.

I don't understand why the split view controller is not calling it's delegate methods when it is otherwise behaving correctly.  These methods should be called from its method-

```<code>- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
</code>```

internally, and when I breakpoint inside this, I can check that the delegate is set and that it is still alive.

Been stuck on this all day!  Everything else is working great and I'm very pleased that the splitview / tabbar / navbar combination is working well. I just need these notifications.

Should I perhaps just call them manually when I rotate? Seems very wrong when the `UISplitViewController' should be doing this.

答: Solved, it has to be at either root level or a direct subview of a tabBar which also must be at root level. Annoying!</p>

Body:
I am using a UISplitViewController inside a UITabBarController with a plain UIViewController in the master pane of the split view and a UINavigationController in the detail pane, which itself contains a vanilla UIViewController.

I am aware that Apple advise to use split views at the root level only, however I have seen other applications (eg, Amazon- 'Wish List' tab) that use split views in tabs so I'm sure it's possible.

My problem is that the delegate methods of the split view, ie. those in UISplitViewControllerDelegate do not get called, which prevents me from creating my pop-over menu when switching into Portrait mode.

The methods in question are the following -

// Called when a button should be added to a toolbar for a hidden view controller
- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc;

// Called when the view is shown again in the split view, invalidating the button and popover controller
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem;

// Called when the view controller is shown in a popover so the delegate can take action like hiding other popovers.
- (void)splitViewController: (UISplitViewController*)svc popoverController: (UIPopoverController*)pc willPresentViewController:(UIViewController *)aViewController;

The UISplitViewController does receive the rotation notifications.

I can get the willShowViewController method to be called if I force the status bar orientation to landscape right (or left) at the beginning of the app launch, using

 [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];

However, the willHideViewController doesn't get called.  And I don't want to force the app to start in landscape.  If I do the same thing but force it to portrait, I don't receive the callbacks.

I don't understand why the split view controller is not calling it's delegate methods when it is otherwise behaving correctly.  These methods should be called from its method-

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

internally, and when I breakpoint inside this, I can check that the delegate is set and that it is still alive.

Been stuck on this all day!  Everything else is working great and I'm very pleased that the splitview / tabbar / navbar combination is working well. I just need these notifications.

Should I perhaps just call them manually when I rotate? Seems very wrong when the `UISplitViewController' should be doing this.


问:
Rapid AWS autoscaling
How do you configure AWS autoscaling to scale up quickly? I've setup an AWS autoscaling group with an ELB. All is working well, except it takes several minutes before the new instances are added and are online. I came across the following in a post about Puppet and autoscaling:

The time to scale can be lowered from several minutes to a few seconds if the AMI you use for a group of nodes is already up to date.

http://puppetlabs.com/blog/rapid-scaling-with-auto-generated-amis-using-puppet/

Is this true? Can time to scale be reduced to a few seconds? Would using puppet add any performance boosts?

I also read that smaller instances start quicker than larger ones:

Small Instance 1.7 GB of memory, 1 EC2 Compute Unit (1 virtual core with 1 EC2 Compute Unit), 160 GB of instance storage, 32-bit platform with a base install of CentOS 5.3 AMI

Amount of time from launch of instance to availability:
      Between 5 and 6 minutes us-east-1c

Large Instance 7.5 GB of memory, 4 EC2 Compute Units (2 virtual cores with 2 EC2 Compute Units each), 850 GB of instance storage, 64-bit platform with a base install of CentOS 5.3 AMI

Amount of time from launch of instance to availability:

  Between 11 and 18 minutes us-east-1c

Both were started via command line using Amazons tools.

http://www.philchen.com/2009/04/21/how-long-does-it-take-to-launch-an-amazon-ec2-instance

I note that the article is old and my c1.xlarge instances are certainly not taking 18min to launch. Nonetheless, would configuring an autoscale group with 50 micro instances (with an up scale policy of 100% capacity increase) be more efficient than one with 20 large instances? Or potentially creating two autoscale groups, one of micros for quick launch time and one of large instances to add CPU grunt a few minutes later? All else being equal, how much quicker does a t1.micro come online than a c1.xlarge?

答:
How soon ASG responds would depend on 3 things:

1. Step - how much to increase by % or fixed number - a large step - you can rapidly increase. ASG will launch the entire Step in one go

2. Cooldown Period - This applies 'how soon' the next increase can happen. If the previous increase step is still within the defined cooldown period (seconds), ASG will wait and not take action for next increase yet. Having a small cooldown period will enable next Step quicker.

3 AMI type- how much time a AMI takes to launch, this depends on type of AMI - many factors come into play. All things equal Fully Baked AMIs launch much faster

Title: Rapid AWS autoscaling


问:
Changing Date Format in Dataset
I tried looking this one up online, but I guess I'm not sure how I should phrase the question without a full explanation.

I've got a webform with a search bar. When you enter in a search term, it queries a database and pulls information and populates a gridview. I'm using the following code:

```<code> string find = "SELECT tblShipments.ShipmentID as [Shipment ID], tblShipmentsAssets.DateShip as [Date Shipped],  FROM tblShipments INNER JOIN(tblAssets INNER JOIN tblShipmentsAssets ON tblAssets.AssetID = tblShipmentsAssets.AssetIDFK) ON tblShipments.ShipmentID = tblShipmentsAssets.ShipmentIDFK where(AssetIDFK like '%' + @assetidfk + '%' )";

        OleDbCommand comm = new OleDbCommand(find, con);
        comm.Parameters.Add("@assetidfk", OleDbType.Char).Value = TxtSearch.Text;

        con.Open();
        comm.ExecuteNonQuery();
        OleDbDataAdapter da = new OleDbDataAdapter();
        da.SelectCommand = comm;
        DataSet ds = new DataSet();
        da.Fill(ds, "AssetIDFK");
        SearchGridView.DataSource = ds;
        SearchGridView.DataBind();
</code>```

In the past, I've simply populated a gridview solely with aspx code using <asp:SqlDataSource> and there I was able to get at the columns that held dates withing the <columns> tag and add in a DataFormatString="{0:d}" to get the format I wanted:

```<code> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" HorizontalAlign="Center">
         <Columns>
            <asp:BoundField DataField="NextCal" HeaderText="Calibration Due"  DataFormatString="{0:d}" >
            </asp:BoundField>

        </Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>" ProviderName="<%$ ConnectionStrings:Database.ProviderName %>" SelectCommand="SELECT , [NextCal] FROM [tblAssets]"></asp:SqlDataSource>
</code>```

With my C# method of populating the gridview, I have no <Columns> section to change the data format. I would then assume I need to do this in the code behind, however I'm not sure how to do that.

答:
Figured out what I was doing wrong:

By having <AutoGenerateColumns ="true">, my columns were (big surprise) being automatically generated and then me adding in columns under the  tag in .aspx was generating duplicate columns.

I changed it to <AutoGenerateColumns ="false">, manually entered my columns in under the  tag and used the DataFormatString="{0:MM/dd/yyyy hh:mm tt}"to change the date format.

Sorry for the dumb question. Hopefully this will help someone avoid the same mistake..

Title: Changing Date Format in Dataset

Body:
I tried looking this one up online, but I guess I'm not sure how I should phrase the question without a full explanation.

I've got a webform with a search bar. When you enter in a search term, it queries a database and pulls information and populates a gridview. I'm using the following code:

 string find = "SELECT tblShipments.ShipmentID as [Shipment ID], tblShipmentsAssets.DateShip as [Date Shipped],  FROM tblShipments INNER JOIN(tblAssets INNER JOIN tblShipmentsAssets ON tblAssets.AssetID = tblShipmentsAssets.AssetIDFK) ON tblShipments.ShipmentID = tblShipmentsAssets.ShipmentIDFK where(AssetIDFK like '%' + @assetidfk + '%' )";

        OleDbCommand comm = new OleDbCommand(find, con);
        comm.Parameters.Add("@assetidfk", OleDbType.Char).Value = TxtSearch.Text;

        con.Open();
        comm.ExecuteNonQuery();
        OleDbDataAdapter da = new OleDbDataAdapter();
        da.SelectCommand = comm;
        DataSet ds = new DataSet();
        da.Fill(ds, "AssetIDFK");
        SearchGridView.DataSource = ds;
        SearchGridView.DataBind();

In the past, I've simply populated a gridview solely with aspx code using <asp:SqlDataSource> and there I was able to get at the columns that held dates withing the <columns> tag and add in a DataFormatString="{0:d}" to get the format I wanted:

 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" HorizontalAlign="Center">
         <Columns>
            <asp:BoundField DataField="NextCal" HeaderText="Calibration Due"  DataFormatString="{0:d}" >
            </asp:BoundField>

        </Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>" ProviderName="<%$ ConnectionStrings:Database.ProviderName %>" SelectCommand="SELECT , [NextCal] FROM [tblAssets]"></asp:SqlDataSource>

With my C# method of populating the gridview, I have no <Columns> section to change the data format. I would then assume I need to do this in the code behind, however I'm not sure how to do that.