问:
How can I hide the start of an element instead of the end when it get's overlapped?
I am trying to get a div element to hide the beginning of it's text opposed to the end. If this does not make sense, please see the fiddle -
 http://jsfiddle.net/L7zd8uyb/1/

As you reduce the width of the screen, 'paragraph' will hide behind the right-most div. Is it possible to reach this div and then start to hide 'some' behind the left-most div?

HTML:

```<code><div id="leftside">Left</div>
<div id="rightside">Right</div>

<div>
    <span>Some paragraph.</span>
</div>
</code>```

CSS:

```<code>#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: red;
}
span {
  margin-left: 200px;
}
</code>```

Note: The JSFiddle was simplified from the example provided in this question - How can I prevent HTML elements from overlapping or sliding under one another?

答:
Your margin-left: 200px is preventing it from being overlapped by your #leftside div.

Try this for your CSS:

```<code>#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
  z-index: 2; /* this will overlap #rightside */
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: green;
  z-index: 1; /* this will overlap span */
}
span {
  position: fixed;
  left: 40%; /* change this to what you need, depending on #leftside */
}
</code>```

Body:
I am trying to get a div element to hide the beginning of it's text opposed to the end. If this does not make sense, please see the fiddle -
 http://jsfiddle.net/L7zd8uyb/1/

As you reduce the width of the screen, 'paragraph' will hide behind the right-most div. Is it possible to reach this div and then start to hide 'some' behind the left-most div?

HTML:

Left

Right

    Some paragraph.

CSS:

#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: red;
}
span {
  margin-left: 200px;
}

Note: The JSFiddle was simplified from the example provided in this question - How can I prevent HTML elements from overlapping or sliding under one another?

Body:
Your margin-left: 200px is preventing it from being overlapped by your #leftside div.

Try this for your CSS:

#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
  z-index: 2; /* this will overlap #rightside */
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: green;
  z-index: 1; /* this will overlap span */
}
span {
  position: fixed;
  left: 40%; /* change this to what you need, depending on #leftside */
}


来源: stackexchange

问:
How to add a JQuery Box to Carousel
I'm trying to add a jquery box to this carousel

http://jsbin.com/iduyu

Here's the source

http://jsbin.com/iduyu/edit

I'm trying to add  tag to every  and after that it stops working. I'm not sure were I should make changes to add a box (lightbox or any other box that has next and previous buttons)

Thank you for any guide and help.

答: here is the demo http://ask.altervista.org/demo/jquery-photo-carousel-that-looks-like-a-real-carousel/</p>

ContentLicense: CC BY-SA 2.5

Title: How to add a JQuery Box to Carousel


问:
SSH2 Not Working On New Server
We have changed hosting companies and where ssh2 was working it no longer works. We have ssh2 enabled on the new server along with allow_url_fopen enabled.

The only difference I can see is that the old server used PHP 5.4.45 and the new server is using PHP 5.6.28.

However, I now get the following error.
Could not open remote file: ssh2.sftp://Resource id #337/my/directory/file.txt

Here is an example of my code:

```<code>$remote_host = "myhostinfohere";
$remote_port = 22;
$remote_user = "myuser";
$remote_pass = "mypassword";
$remote_dir = "/my/directory/";
$remote_file = 'file.txt';

try {
    $remote_conn = ssh2_connect($remote_host, $remote_port);
} catch (Exception $e) {
    die("could not connect to ".$remote_host);
}

try {
    ssh2_auth_password($remote_conn, $remote_user, $remote_pass);
} catch (Exception $e) {
    die("Password failed on ".$remote_host);
}

$sftp = ssh2_sftp($remote_conn);

$fetch_string = "ssh2.sftp://$sftp" . $remote_dir . $remote_file;

//If I add this it says it doesn't exists for some reason even though I can see the file if I log in remotely.
$fileExists = file_exists($fetch_string);
if (!$fileExists) {
    die('File does not exist');
}

$stream = fopen($fetch_string, 'r');

if (!$stream) {
    die("Could not open remote file: " . $fetch_string . "\n");
}
</code>```

Again, this same code works on the old server but doesn't on the new server. What am I missing? I can easily copy the file to my server with ssh2_scp_recv() which works fine so I'm not sure what is happening with the fopen() function.

答:
Here $fetch_string = "ssh2.sftp://$sftp" . $remote_dir . $remote_file;

use intval($sftp) instead of $sftp

ContentLicense: CC BY-SA 3.0

Title: SSH2 Not Working On New Server

Body:
We have changed hosting companies and where ssh2 was working it no longer works. We have ssh2 enabled on the new server along with allow_url_fopen enabled.

The only difference I can see is that the old server used PHP 5.4.45 and the new server is using PHP 5.6.28.

However, I now get the following error.
Could not open remote file: ssh2.sftp://Resource id #337/my/directory/file.txt

Here is an example of my code:

$remote_host = "myhostinfohere";
$remote_port = 22;
$remote_user = "myuser";
$remote_pass = "mypassword";
$remote_dir = "/my/directory/";
$remote_file = 'file.txt';

try {
    $remote_conn = ssh2_connect($remote_host, $remote_port);
} catch (Exception $e) {
    die("could not connect to ".$remote_host);
}

try {
    ssh2_auth_password($remote_conn, $remote_user, $remote_pass);
} catch (Exception $e) {
    die("Password failed on ".$remote_host);
}

$sftp = ssh2_sftp($remote_conn);

$fetch_string = "ssh2.sftp://$sftp" . $remote_dir . $remote_file;

//If I add this it says it doesn't exists for some reason even though I can see the file if I log in remotely.
$fileExists = file_exists($fetch_string);
if (!$fileExists) {
    die('File does not exist');
}

$stream = fopen($fetch_string, 'r');

if (!$stream) {
    die("Could not open remote file: " . $fetch_string . "\n");
}

Again, this same code works on the old server but doesn't on the new server. What am I missing? I can easily copy the file to my server with ssh2_scp_recv() which works fine so I'm not sure what is happening with the fopen() function.


问:
Scripting in VS 2015 for Unity 5.5.2 project, needing to upgrade to C# v.6+
Scripting in VS 2015 for Unity 5.5.2 project, needing to upgrade to C# v.6+
I have VS community 2015 version 14 update 3. I am working in Unity 5.5.2 and trying to learn the game engine. I am trying to create some scripts which opens up into VS. Upon trying to add default initializers for properties of my class it gives an error. For some reason the program loads using C# version 4.
I would like to upgrade this to version 6, but when I have read other solutions to change the C# version it has always been going to the projects property page.

Snesh Prajapati's example doesn't work as the property page didn't have those options.

After trying David De Sloovere's solution some reason (maybe being a Unity project) the screen just flashes and no page is loaded when I try to bring up the projects property page. I even went and deleted the project.config file that was created, to not luck to get the properties page back displaying.

答:
You are out of luck here.  Unity uses an older version of C# (4.4 as of Unity 5.5).

To see the exact version of C# you are using, run the line Debug.Log(System.Enviroment.Version); and check your log.


问:
Parsing JSON Issue with Google Apps
I am not able to parse JSON using Google Apps. The payload is coming from Microsoft Teams. When I dump the payload info using json.postData.getDataAsString() I receive the below:

```<code>{"type":"message",
  "Id":"1490878296446",
  "timestamp":"2017-03-30T12:51:36.857Z",
  "localTimestamp":null,
  "serviceUrl":"https://smba.trafficmanager.net/amer-client-ss.msg/",
  "channelId":"msteams",
  "from":{"id":"394724749272","name":"Test, User"},
  "conversation":{"isGroup":true,"id":"39482095823@thread.skype;messageid=1490878296446","name":null},
  "Recipient":null,
  "textFormat":"plain",
  "attachmentLayout":null,
  "membersAdded":null,
  "membersRemoved":null,
  "topicName":null,
  "historyDisclosed":null,
  "Locale":null,
  "text":"Test message",
  "Summary":null,
  "attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span contenteditable=\"false\" itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Testing</span><span contenteditable=\"false\" itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"1\"></span> Hi there</div>","name":null,"thumbnailUrl":null}],
  "entities":[{"type":"mention","mentioned":{"id":"28:22e50a9b-80cc-4eab-a092-ce64796d28d7","name":""}},{"type":"clientInfo","locale":"en-US","country":"US","platform":"Windows"}],
"channelData":{"teamsChannelId":"19:c5a0767fdc434c8097444a6f7488ae6d@thread.skype","teamsTeamId":"984720987342876876@thread.skype","channel":{"id":"2098374239872-7@thread.skype"},"team":{"id":"19:8fce7e8df8084d62bc0ddb5d77830131@thread.skype"},"onBehalfOf":"[{\"itemid\":0,\"mri\":\"1f265431-39ad-43f7-8dbe-93ee5cc43777\",\"mentionType\":\"webhook\",\"displayName\":\"Testing\"}]","tenant":{"id":"cf857d10-00c4-44ac-8e8a-33f3f8a6d701"}},"action":null,"replyToId":null,"value":null}
</code>```

Using dot syntax like I do with Slack isn't letting me delve into that payload. Here is the code I am trying to use:

```<code>function doPost(json) {
    var parameters = json.parameters;
    var text = String(parameters);
    var datetime = new Date();
    var date = datetime.toDateString();
    var spreadsheet = SpreadsheetApp.openById('myspreadsheetid');
    var sheet = spreadsheet.getSheetByName('mysheetname');
    sheet.appendRow([text,date])
};
</code>```

The above works fine with a payload from a Slack webhook. Here is what that payload looks like:

```<code>token=fihwEGHwpoerihKe&team_id=T04U18AG8
&team_domain=mydomain&service_id=234211
&channel_id=C2QJ4SQL0
&channel_name=testchannel
&timestamp=1490881481.055677
&user_id=U0KDGEBJB
&user_name=test.user
&text=my test message
&trigger_word=my test message
</code>```

答:
While I don't understand why this is necessary the solution is below:

First I need to convert the MSTeams payload into a string, then parse it into an object. Removing either of those steps or changing the order does not work.

```<code>function doPost(json) {
    var jsonstring = json.postData.getDataAsString()
    var jsonobject = JSON.parse(jsonstring);
    var text = String(jsonobject.text);
...//the rest of the webapp follows
</code>```

Title: Parsing JSON Issue with Google Apps

Body:
I am not able to parse JSON using Google Apps. The payload is coming from Microsoft Teams. When I dump the payload info using json.postData.getDataAsString() I receive the below:

{"type":"message",
  "Id":"1490878296446",
  "timestamp":"2017-03-30T12:51:36.857Z",
  "localTimestamp":null,
  "serviceUrl":"https://smba.trafficmanager.net/amer-client-ss.msg/",
  "channelId":"msteams",
  "from":{"id":"394724749272","name":"Test, User"},
  "conversation":{"isGroup":true,"id":"39482095823@thread.skype;messageid=1490878296446","name":null},
  "Recipient":null,
  "textFormat":"plain",
  "attachmentLayout":null,
  "membersAdded":null,
  "membersRemoved":null,
  "topicName":null,
  "historyDisclosed":null,
  "Locale":null,
  "text":"Test message",
  "Summary":null,
  "attachments":[{"contentType":"text/html","contentUrl":null,"content":"
Testing Hi there
","name":null,"thumbnailUrl":null}],
  "entities":[{"type":"mention","mentioned":{"id":"28:22e50a9b-80cc-4eab-a092-ce64796d28d7","name":""}},{"type":"clientInfo","locale":"en-US","country":"US","platform":"Windows"}],
"channelData":{"teamsChannelId":"19:c5a0767fdc434c8097444a6f7488ae6d@thread.skype","teamsTeamId":"984720987342876876@thread.skype","channel":{"id":"2098374239872-7@thread.skype"},"team":{"id":"19:8fce7e8df8084d62bc0ddb5d77830131@thread.skype"},"onBehalfOf":"[{\"itemid\":0,\"mri\":\"1f265431-39ad-43f7-8dbe-93ee5cc43777\",\"mentionType\":\"webhook\",\"displayName\":\"Testing\"}]","tenant":{"id":"cf857d10-00c4-44ac-8e8a-33f3f8a6d701"}},"action":null,"replyToId":null,"value":null}

Using dot syntax like I do with Slack isn't letting me delve into that payload. Here is the code I am trying to use:

function doPost(json) {
    var parameters = json.parameters;
    var text = String(parameters);
    var datetime = new Date();
    var date = datetime.toDateString();
    var spreadsheet = SpreadsheetApp.openById('myspreadsheetid');
    var sheet = spreadsheet.getSheetByName('mysheetname');
    sheet.appendRow([text,date])
};

The above works fine with a payload from a Slack webhook. Here is what that payload looks like:

token=fihwEGHwpoerihKe&team_id=T04U18AG8
&team_domain=mydomain&service_id=234211
&channel_id=C2QJ4SQL0
&channel_name=testchannel
&timestamp=1490881481.055677
&user_id=U0KDGEBJB
&user_name=test.user
&text=my test message
&trigger_word=my test message

Body:
While I don't understand why this is necessary the solution is below:

First I need to convert the MSTeams payload into a string, then parse it into an object. Removing either of those steps or changing the order does not work.

function doPost(json) {
    var jsonstring = json.postData.getDataAsString()
    var jsonobject = JSON.parse(jsonstring);
    var text = String(jsonobject.text);
...//the rest of the webapp follows


问:
is it possible to track "Add to cart" event without using google tag manager
I have already try to track Add to cart Button using Google tag manager.

But I want to do it without using google tag manager.

i don't know it's possible or not.if you guys have any suggest let me know

thank's

答:
You can use a custom tracking event to do that. How is that possible? First of all you should have the analytics js library loaded in the page. It matters if this is done through GTM or by putting the GA snippet yourself.
If you put the analytics.js in the page without using GTM, you can add an onClick event on your add to cart button. When this button is clicked you can call the function like below

```<code>ga('send', 'event', eventCategory, eventAction, eventLabel, eventValue);
</code>```

The variables eventCategory, eventAction, eventLabel, eventValue will be strings that represent how you want to see this event reported in GA.
The second case that the analytics.js library is loaded through GTM is kinda trickier. That is because gtm uses a different tracker for each tag fired. What you have to do is find the correct one to send your event. To find the correct tracker either you can implement a named tracker on the page or call the function

```<code>ga(function(tracker) {
  // Logs the tracker created above to the console.
  console.log(tracker);
});
</code>```

To get the tracker name. All the parameters will depend on the context of what you want to do but I think you can move on with this info.

Body:
You can use a custom tracking event to do that. How is that possible? First of all you should have the analytics js library loaded in the page. It matters if this is done through GTM or by putting the GA snippet yourself.
If you put the analytics.js in the page without using GTM, you can add an onClick event on your add to cart button. When this button is clicked you can call the function like below

ga('send', 'event', eventCategory, eventAction, eventLabel, eventValue);

The variables eventCategory, eventAction, eventLabel, eventValue will be strings that represent how you want to see this event reported in GA.
The second case that the analytics.js library is loaded through GTM is kinda trickier. That is because gtm uses a different tracker for each tag fired. What you have to do is find the correct one to send your event. To find the correct tracker either you can implement a named tracker on the page or call the function

ga(function(tracker) {
  // Logs the tracker created above to the console.
  console.log(tracker);
});

To get the tracker name. All the parameters will depend on the context of what you want to do but I think you can move on with this info.


问:
How to mention the region for a lambda function in AWS using cli
I am trying to create a lambda function in a particular region using aws-cli. I am not sure how to create it. Looking at this doc and couldn't find any parameter related to region. http://docs.aws.amazon.com/cli/latest/reference/lambda/create-function.html

Thank you.

答:
The region is a common option to all AWS CLI commands. If you want to explicitly include the region in your command, simply include --region us-east-1, for example, to run your command in the us-east-1 region.

If this parameter is not specified explicitly, it will be implicitly derived from your configuration. This could be environment variables, your CLI's config file, or even inherited from an IAM instance profile.

A safe command to verify this is aws lambda list-functions. This is a read-only command that lists your functions; it will only list functions in the region that was implicitly supplied via your configuation. You can explicitly supply a region to this function and observe that the results will change if you have functions in one region but not the other.

Further Reading

AWS Documentation - Configuring the AWS Command Line Interface

AWS Documentation - Configuration and Credential Files

AWS Documentation - AWS CLI Options


问:
php Mysql issue with a prepared query in joint table
I'm creating an app, and I have a joint table between Blog posts and Comments.
So let say I have a page with the list of posts, when I want to see the detail view then I put the Id of that post in parameter in the url which I hydrate my setters with somewhere in my app.
In that detail view of the post I have a form to add comments; however when I try to insert the IDs of both the post and the comment itself, It doesn't work here is my query/method that does that:

```<code>Public function insertPost(Articles $article)
    {
//here I insert the comment
        $sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment)
                                                    VALUES (?,NOW())');
        $sql->execute(array($article->getContent()));

//here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
        $sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article)
SELECT comments.id, articles.id
FROM comments, articles
WHERE comments.id = (SELECT id FROM comments ORDER BY id DESC LIMIT 0,1)
                                                    AND articles.id = "'.$article->getId().'" ');
        $sql2->execute();
    }
</code>```

Do you guys see anything wrong?

Thanks for your help!

答:
After you insert your comment we can grab the comment id and article id like so :</p>

```<code>$sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment) VALUES (?,NOW())');
$sql->execute(array($article->getContent()));

$comment_id = $this->getBdd()->lastInsertId();

$article_id = $article->getId();

$sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article) VALUES(?, ?)');

 $sql2->execute([$comment_id, $article_id]);
</code>```

Body:
I'm creating an app, and I have a joint table between Blog posts and Comments.
So let say I have a page with the list of posts, when I want to see the detail view then I put the Id of that post in parameter in the url which I hydrate my setters with somewhere in my app.
In that detail view of the post I have a form to add comments; however when I try to insert the IDs of both the post and the comment itself, It doesn't work here is my query/method that does that:

Public function insertPost(Articles $article)
    {
//here I insert the comment
        $sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment)
                                                    VALUES (?,NOW())');
        $sql->execute(array($article->getContent()));

//here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
        $sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article)
SELECT comments.id, articles.id
FROM comments, articles
WHERE comments.id = (SELECT id FROM comments ORDER BY id DESC LIMIT 0,1)
                                                    AND articles.id = "'.$article->getId().'" ');
        $sql2->execute();
    }

Do you guys see anything wrong?

Thanks for your help!

Body:
After you insert your comment we can grab the comment id and article id like so :

$sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment) VALUES (?,NOW())');
$sql->execute(array($article->getContent()));

$comment_id = $this->getBdd()->lastInsertId();

$article_id = $article->getId();

$sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article) VALUES(?, ?)');

 $sql2->execute([$comment_id, $article_id]);


问:
set text to textview if an image has been selected from gallery
I have a textview: Click to add an image behind an imageview.

when user click, it will open the gallery. If user select an image it will be displayed in the imageview.

I want to set the textview text to blank if an image has been selected.

I tried inside imageview on click:

```<code>        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
        ImageViewText.setText("");
</code>```

the problem here is the textview will be blank in the moment user click on the imageview. What I want is to reset it if user really selected an image.

Any ideas?

答:
As you are using startActivityForResult(), you will get an image path imageUri from Intent in onActivityResult() method if an image selected successfully.

Add condition to Check RESULT_OK and REQUEST_CODE. If both true then set image to imageView and set textView value blank("") or change visibility to GONE or INVISIBLE.

Try this:

```<code>@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CODE) {
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

                // Set image
                imageView.setImageBitmap(selectedImage);
                // Set text
                textView.setText("");

                // Alternative
                // textView.setVisibility(View.GONE); or
                // textView.setVisibility(View.INVISIBLE);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}
</code>```

Hope this will help~

Body:
I have a textview: Click to add an image behind an imageview.

when user click, it will open the gallery. If user select an image it will be displayed in the imageview.

I want to set the textview text to blank if an image has been selected.

I tried inside imageview on click:

        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
        ImageViewText.setText("");

the problem here is the textview will be blank in the moment user click on the imageview. What I want is to reset it if user really selected an image.

Any ideas?

Body:
As you are using startActivityForResult(), you will get an image path imageUri from Intent in onActivityResult() method if an image selected successfully.

Add condition to Check RESULT_OK and REQUEST_CODE. If both true then set image to imageView and set textView value blank("") or change visibility to GONE or INVISIBLE.

Try this:

@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CODE) {
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

                // Set image
                imageView.setImageBitmap(selectedImage);
                // Set text
                textView.setText("");

                // Alternative
                // textView.setVisibility(View.GONE); or
                // textView.setVisibility(View.INVISIBLE);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}

Hope this will help~


问:
ConstraintLayout - centering views with next to each other vertically or horizontally
How to center align 3 buttons with next to each other vertically using ConstraintLayout?

To be clear, i want to convert this simple layout structure into flat UI using ConstraintLayout

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
</FrameLayout>
</code>```

I have obtained a nearest solution as follows

```<code><android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"/>

 </android.support.constraint.ConstraintLayout>
</code>```

But clearly, you can see that the obtained output does not match to the required one. i don't want any margin or space in between the 3 buttons, all i want is to center align those 3 buttons next to each other vertically just like they are in a LinearLayout which has a vertical orientation.

答:
Proper solution

It is good that you have created the chain between those 3 views. Having a chain you can specify the chain "style" and it will affect how views are distributed along the chain axis. The chain style can be controlled by "chain" button right below the view:

Click on it few times to toggle between all 3 modes:

spread (the default one)

spread_inside

packed

As you can see - packed is the one that you want.

Setting the chain style will result in adding following attribute to the first child in the chain, so you can do it also from XML:

app:layout_constraintVertical_chainStyle="packed"

Naive solution

Solution proposed in the other answer may look like it works, but in reality it is not a proper solution for your problem. Consider the case when you have views with different heights, lets say the bottom one is larger. That solution will lock the middle view in center and position other views above and below. It will not result in a "centered group" (only the middle view would be centered). You can see the comparison in the image below:

Body:
How to center align 3 buttons with next to each other vertically using ConstraintLayout?

To be clear, i want to convert this simple layout structure into flat UI using ConstraintLayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
</FrameLayout>

I have obtained a nearest solution as follows

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"/>

 </android.support.constraint.ConstraintLayout>

But clearly, you can see that the obtained output does not match to the required one. i don't want any margin or space in between the 3 buttons, all i want is to center align those 3 buttons next to each other vertically just like they are in a LinearLayout which has a vertical orientation.


问:
Redux form clearing field values
I am using the redux  to hide and show components based on a value.
When I am switching between options I would like to clear the values.

How do I clear values from the state when switching between fields that are hiding and showing?

What is the recommended way validating each field?

Is it possible to completely remove the field from the state?

```<code><div>
    <form>
      <Fields
       component={RadioButtonGroupField}
       names={['radioButtonGroup', 'nameTextField', 'nickNameTextField']}
      />
    </ form>
</div>

function RadioButtonGroupField(fields) {
    return(
      <div>
        <RadioButtonGroupComponent
          {...fields.radioButtonGroup.input}
          {...fields.radioButtonGroup.meta}
        />
        {
          (fields.radioButtonGroup.input.value === 'name' ||
          fields.radioButtonGroup.input.value === 'both') &&
          <NameTextFieldComponent
            {...fields.radioButtonGroup.input}
            {...fields.radioButtonGroup.meta}
          />
        }
        {
          (fields.radioButtonGroup.input.value === 'nickname' ||
          fields.radioButtonGroup.input.value === 'both') &&
           <NicknameTextFieldComponent
            {...fields.radioButtonGroup.input}
            {...fields.radioButtonGroup.meta}
          />
        }
      </div>
     );
  }
</code>```

答:
Why does it matter if the other value is in the state? Seems like you could, upon submission, look at your radio value to determine which of the other values to use.

However, to answer your question, you could potentially put an onChange listener on your radio field, and (not forgetting to call the fields.radioButtonGroup.input.onChange()) dispatch a change(value==='name' ? 'nickname' : 'name', null) action to destroy the value in the input you want to ignore.

Title: Redux form clearing field values

Body:
I am using the redux  to hide and show components based on a value.
When I am switching between options I would like to clear the values.

How do I clear values from the state when switching between fields that are hiding and showing?

What is the recommended way validating each field?

Is it possible to completely remove the field from the state?

    <form>
      <Fields
       component={RadioButtonGroupField}
       names={['radioButtonGroup', 'nameTextField', 'nickNameTextField']}
      />
    </ form>

function RadioButtonGroupField(fields) {
    return(

        <RadioButtonGroupComponent
          {...fields.radioButtonGroup.input}
          {...fields.radioButtonGroup.meta}
        />
        {
          (fields.radioButtonGroup.input.value === 'name' ||
          fields.radioButtonGroup.input.value === 'both') &&
          <NameTextFieldComponent
            {...fields.radioButtonGroup.input}
            {...fields.radioButtonGroup.meta}
          />
        }
        {
          (fields.radioButtonGroup.input.value === 'nickname' ||
          fields.radioButtonGroup.input.value === 'both') &&
           <NicknameTextFieldComponent
            {...fields.radioButtonGroup.input}
            {...fields.radioButtonGroup.meta}
          />
        }

     );
  }


问:
What am I doing wrong when trying to run the this java test command for LWJGL?
I'm attempting to use the lwjgl library and I'm starting from scratch on a new Windows 7 install.

I downloaded the latest JDK 6 from the Oracle website.  After installing it, I found that commands like "java" or "javac" weren't being recognized from a windows cmd prompt.  So, I edited my path variable and appended the jdk's bin folder to it.

Now the java commands work.

So, I download the latest lwjgl, extract it and read the installation instructions on their website:

Download the distribution Unpack the
  archive, file contents (in sub
  folders) should include (amongst other
  things):

lwjgl.dll lwjglaudio.dll lwjgl.jar
  lwjgl_util.jar lwjgl_test.jar

  Test
  LWJGL by opening a command prompt, and
  navigating to the folder where the
  archive was extracted. Once navigated,
  issue the following command: (all in
  one line, space before each -option)

java -cp .;res;jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\jinput.jar;-Djava.library.path=native\windows org.lwjgl.test.WindowCreationTest

A window should appear and you should
  see the following output:

Found  display modes 240, 320,
  WindowCreationTest Display created
  Moving to 100, 100 Window created 600,
  800, Game

So, I extracted it and navigated to the extracted folder in a cmd prompt.

I then executed the test command specified above and I get the following error:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>java
  -cp .;res;jar\lwjgl.jar;jar\ lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\ji
  nput.jar;-Djava.library.path=native\windows
  org.lwjgl.test.WindowCreationTest

  The
  following keys are available: ESCAPE:
  Exit test ARROW Keys:     Move window
  when in non-fullscreen mode L:

  List selectable display modes 0-8:

  Selection of display modes F:

  Toggle fullscreen SHIFT-F:

  Toggle fullscreen with
  Display.destroy()/create() cycle
  Exception in thread "main"
  java.lang.UnsatisfiedLinkError: no
  lwjgl in java.libr ary.path
          at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1734)
          at java.lang.Runtime.loadLibrary0(Runtime.java:823)
          at java.lang.System.loadLibrary(System.java:1028)
          at org.lwjgl.Sys$1.run(Sys.java:73)
          at java.security.AccessController.doPrivileged(Native
  Method)
          at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
          at org.lwjgl.Sys.loadLibrary(Sys.java:82)
          at org.lwjgl.Sys.(Sys.java:99)
          at org.lwjgl.opengl.Display.(Display.java:130)
          at org.lwjgl.test.WindowCreationTest.initialize(WindowCreationTest.java:
  82)
          at org.lwjgl.test.WindowCreationTest.main(WindowCreationTest.java:286)

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>

Why am I getting that error?  I don't understand why there should be linking errors.  In the command that I attempted to execute it clearly spells out the path to those native dll's it needs:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>java
  -cp .;res;jar\lwjgl.jar;jar\ lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\ji
  nput.jar;-Djava.library.path=native\windows
  org.lwjgl.test.WindowCreationTest

I've confirmed that the relative path "native\windows" contains those dependencies:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6\native\windows>dir

  Volume in drive C has no label.

  Volume Serial Number is 2061-75F6

Directory of C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6\native\windows

11/24/2010  12:35 AM              .

  11/24/2010  12:35 AM              ..

  10/18/2010  08:44 PM            31,232 jinput-dx8.dll

  10/18/2010  08:44 PM            65,024 jinput-dx8_64.dll

  10/18/2010  08:44 PM            29,696 jinput-raw.dll

  10/18/2010  08:44 PM            62,464 jinput-raw_64.dll

  10/18/2010  08:44 PM           197,120 lwjgl.dll

  10/18/2010  08:44 PM           305,664 lwjgl64.dll

  10/18/2010  08:44 PM            56,832 OpenAL32.dll

  10/18/2010  08:44 PM           157,184 OpenAL64.dll

                8 File(s)        905,216 bytes

                2 Dir(s)  155,163,058,176 bytes free

Can anyone help point out what I'm doing wrong? Can anyone reproduce this by downloading the LWJGL library and attempting to run the test command given in the installation instructions?

答:
It seems that you do not have a space between your classpath argument (-cp jar1.jar;jar2.jar) and your system property setting (-D..).

E.g. your classpath looks like this-cp .;res;jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwr...;-Djava.library.path=native\windows. This way java will interpret your property setting of native library path argument like a classpath!

Just add a space between those arguments and you should be up and running, this is the corrected command (also tested on Windows 7):

```<code>java -cp jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwjgl_util.jar -Djava.library.path=native\windows org.lwjgl.test.WindowCreationTest
</code>```

Note that I removed the unused jars from the classpath since you only want to run the WindowCreationTest example.

Body:
It seems that you do not have a space between your classpath argument (-cp jar1.jar;jar2.jar) and your system property setting (-D..).

E.g. your classpath looks like this-cp .;res;jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwr...;-Djava.library.path=native\windows. This way java will interpret your property setting of native library path argument like a classpath!

Just add a space between those arguments and you should be up and running, this is the corrected command (also tested on Windows 7):

java -cp jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwjgl_util.jar -Djava.library.path=native\windows org.lwjgl.test.WindowCreationTest

Note that I removed the unused jars from the classpath since you only want to run the WindowCreationTest example.


问:
How to get values from Dtype object in a dataframe
I have a dataframe with this column structure:

```<code>```
In [179]: df.dtypes
Out[179]:
layer         int32
row           int32
column        int32
segment       int32
reach         int32
Qin         float64
Qaquifer    float64
Qout        float64
Qovr        float64
Qprecip     float64
Qet         float64
stage       float64
depth       float64
width       float64
Cond        float64
Qwt         float64
deltaUZ     float64
GWh         float64
kstpkper     object
k             int32
i             int32
j             int32
dtype: object

In [180]: df.kstpkper
Out[180]:
0          (0, 0)
1          (0, 0)
2          (0, 0)
3          (0, 0)
4          (0, 0)
5          (0, 0)
            ...
18207    (35, 10)
18208    (35, 10)
18209    (35, 10)
18210    (35, 10)
18211    (35, 10)
18212    (35, 10)
Name: kstpkper, dtype: object
```
</code>```

I would like to split kstpkper variable in two and add them to my dataframe.  Is it possible?

How can I call each element in kstpkper variable?

Any help would be appreciated.

答:
An efficient way to do it would be to construct a new dataframe from kstpkper values and join it with the existing dataframe

Consider the test dataframe df

```<code>df = pd.DataFrame(dict(
        A=[1, 2, 3],
        kstpkper=[(0, 0), (1, 2), (5, 11)],
        C=np.ones(3)
    ))

print(df)

   A    C kstpkper
0  1  1.0   (0, 0)
1  2  1.0   (1, 2)
2  3  1.0  (5, 11)
</code>```

Then we construct and join like this

```<code>df.join(pd.DataFrame(df.kstpkper.tolist(), df.index, ['kstpkper1', 'kstpkper2']))

   A    C kstpkper  kstpkper1  kstpkper2
0  1  1.0   (0, 0)          0          0
1  2  1.0   (1, 2)          1          2
2  3  1.0  (5, 11)          5         11
</code>```

Body:
I have a dataframe with this column structure:

In [179]: df.dtypes
Out[179]:
layer         int32
row           int32
column        int32
segment       int32
reach         int32
Qin         float64
Qaquifer    float64
Qout        float64
Qovr        float64
Qprecip     float64
Qet         float64
stage       float64
depth       float64
width       float64
Cond        float64
Qwt         float64
deltaUZ     float64
GWh         float64
kstpkper     object
k             int32
i             int32
j             int32
dtype: object

In [180]: df.kstpkper
Out[180]:
0          (0, 0)
1          (0, 0)
2          (0, 0)
3          (0, 0)
4          (0, 0)
5          (0, 0)
            ...
18207    (35, 10)
18208    (35, 10)
18209    (35, 10)
18210    (35, 10)
18211    (35, 10)
18212    (35, 10)
Name: kstpkper, dtype: object

I would like to split kstpkper variable in two and add them to my dataframe.  Is it possible?

How can I call each element in kstpkper variable?

Any help would be appreciated.

Body:
An efficient way to do it would be to construct a new dataframe from kstpkper values and join it with the existing dataframe

Consider the test dataframe df

df = pd.DataFrame(dict(
        A=[1, 2, 3],
        kstpkper=[(0, 0), (1, 2), (5, 11)],
        C=np.ones(3)
    ))

print(df)

   A    C kstpkper
0  1  1.0   (0, 0)
1  2  1.0   (1, 2)
2  3  1.0  (5, 11)

Then we construct and join like this

df.join(pd.DataFrame(df.kstpkper.tolist(), df.index, ['kstpkper1', 'kstpkper2']))

   A    C kstpkper  kstpkper1  kstpkper2
0  1  1.0   (0, 0)          0          0
1  2  1.0   (1, 2)          1          2
2  3  1.0  (5, 11)          5         11


问:
Xcode8.3 constantly crashes after update
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.</p>

```<code>Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}
</code>```

答:
Try cleaning your Xcode's derived data. That seemed to solve the problem for me.
Run this on your terminal:</p>

```<code>rm -rf ~/Library/Developer/Xcode/DerivedData/
</code>```

Body:
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.

Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}

Body:
Try cleaning your Xcode's derived data. That seemed to solve the problem for me.
Run this on your terminal:

rm -rf ~/Library/Developer/Xcode/DerivedData/


问:
Issue with AWS cognito sample app
I am trying to run this AWS cognito sample app from https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoSync-Sample/Swift. I can add new data set but as soon as i try to sync/refresh i get this below error. I am not trying with any provider. Just simple sync of data.

And Here is the steps i did -

1.Downloaded the sample app from github.

2.Installed AWSCognito using pod as given

3.And Created a identity pool in Amazon cognito console

4.and updated the constants in Constants.swift -

static let COGNITO_REGIONTYPE = AWSRegionType.USEast1
static let COGNITO_IDENTITY_POOL_ID = "us-east-1_XXXXXXXXX"

Here is the error from my console -

```<code>2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:179 | __51-[AWSCognitoSQLiteManager initializeDatasetTables:]_block_invoke | sqlString = 'INSERT INTO CognitoMetadata(Dataset,ModifiedBy,IdentityId) VALUES (?,?,?)'
2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:282 | __53-[AWSCognitoSQLiteManager loadDatasetMetadata:error:]_block_invoke | query = 'SELECT LastSyncCount, LastModified, ModifiedBy, CreationDate, DataStorage, RecordCount FROM CognitoMetadata WHERE IdentityId = ? and Dataset = ?'
2016-05-11 15:43:49.647 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}]
2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{
Connection = close;
"Content-Length" = 218;
"Content-Type" = "application/x-amz-json-1.1";
Date = "Wed, 11 May 2016 10:13:50 GMT";
"x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+";
"x-amzn-ErrorType" = "ValidationException:";
"x-amzn-RequestId" = "0ec70838-1761-11e6-91c2-e77b976ab658";
}]
2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}]
2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}]
2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{
Connection = close;
"Content-Length" = 218;
"Content-Type" = "application/x-amz-json-1.1";
Date = "Wed, 11 May 2016 10:13:51 GMT";
"x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+";
"x-amzn-ErrorType" = "ValidationException:";
"x-amzn-RequestId" = "0f7792fc-1761-11e6-9ad4-59d8bf47e69e";
}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}]
2016-05-11 15:43:52.169 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSCognitoService.m line:176 | __36-[AWSCognito refreshDatasetMetadata]_block_invoke147 | Unable to list datasets: Error Domain=com.amazon.cognito.AWSCognitoErrorDomain Code=-4000 "(null)"
</code>```

What am i missing? I am very new to AWS services, any guidance would be much appreciated.

Thanks,
Richa

答:
Yes, this is almost always using a user pool id instead of a identity pool. </p>

<p>Note that if you enter the correct identity pool id when initializing AWSCognitoCredentialsProvider() it will work in simulator, even with a wrong id in your info.plist AWS dictionary descriptor. But on device it's going to use the info.plist pool id, and fail if it's wrong. That bit me, so make sure your pool id is correct in both locations. </p>

Title: Issue with AWS cognito sample app

Body:
I am trying to run this AWS cognito sample app from https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoSync-Sample/Swift. I can add new data set but as soon as i try to sync/refresh i get this below error. I am not trying with any provider. Just simple sync of data.

And Here is the steps i did -

1.Downloaded the sample app from github.

2.Installed AWSCognito using pod as given

3.And Created a identity pool in Amazon cognito console

4.and updated the constants in Constants.swift -

static let COGNITO_REGIONTYPE = AWSRegionType.USEast1
static let COGNITO_IDENTITY_POOL_ID = "us-east-1_XXXXXXXXX"

Here is the error from my console -

2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:179 | __51-[AWSCognitoSQLiteManager initializeDatasetTables:]_block_invoke | sqlString = 'INSERT INTO CognitoMetadata(Dataset,ModifiedBy,IdentityId) VALUES (?,?,?)'
2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:282 | __53-[AWSCognitoSQLiteManager loadDatasetMetadata:error:]_block_invoke | query = 'SELECT LastSyncCount, LastModified, ModifiedBy, CreationDate, DataStorage, RecordCount FROM CognitoMetadata WHERE IdentityId = ? and Dataset = ?'
2016-05-11 15:43:49.647 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}]
2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{
Connection = close;
"Content-Length" = 218;
"Content-Type" = "application/x-amz-json-1.1";
Date = "Wed, 11 May 2016 10:13:50 GMT";
"x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+";
"x-amzn-ErrorType" = "ValidationException:";
"x-amzn-RequestId" = "0ec70838-1761-11e6-91c2-e77b976ab658";
}]
2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}]
2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}]
2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{
Connection = close;
"Content-Length" = 218;
"Content-Type" = "application/x-amz-json-1.1";
Date = "Wed, 11 May 2016 10:13:51 GMT";
"x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+";
"x-amzn-ErrorType" = "ValidationException:";
"x-amzn-RequestId" = "0f7792fc-1761-11e6-9ad4-59d8bf47e69e";
}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}]
2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}]
2016-05-11 15:43:52.169 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSCognitoService.m line:176 | __36-[AWSCognito refreshDatasetMetadata]_block_invoke147 | Unable to list datasets: Error Domain=com.amazon.cognito.AWSCognitoErrorDomain Code=-4000 "(null)"

What am i missing? I am very new to AWS services, any guidance would be much appreciated.

Thanks,
Richa

Body:
Yes, this is almost always using a user pool id instead of a identity pool.

Note that if you enter the correct identity pool id when initializing AWSCognitoCredentialsProvider() it will work in simulator, even with a wrong id in your info.plist AWS dictionary descriptor. But on device it's going to use the info.plist pool id, and fail if it's wrong. That bit me, so make sure your pool id is correct in both locations.


问:
Multidimensional array keys merge into single value
I want to make all multidimensional keys merge into single key of output array. My input array be like:

```<code>Array
(
    [field1] => test
    [field2] => test
    [field3] => test
    [field4] => Array
        (
            [field5] => test
            [field6] => test
            [field7] => test
            [field8] => test
            [field9] => test
            [field10] => test
            [field11] => test
        )
)
</code>```

I want output be like:

```<code>Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field5
    [4] => field4/field6
    [5] => field4/field7
    [6] => field4/field8
    [7] => field4/field9
    [8] => field4/field10
    [9] => field4/field11
)
</code>```

My code be like:

```<code>function get_data($config_data, $final_arr=array()) {
    foreach($config_data as $key =>$value) {
        if(is_array($value)) {
            $final_arr[]=$key.'=>'.get_data($value, $final_arr[$key]);
        } else {
            $final_arr[]=$key;
        }
    }
    return $final_arr;
}
</code>```

答:
You need some form of position marker for that. Take a look at this simple example: </p>

```<code><?php
$input = [
    'field1' => 'test',
    'field2' => 'test',
    'field3' => 'test',
    'field4' => [
        'field41' => 'test',
        'field42' => 'test',
        'field43' => 'test',
    ],
    'field5' => [
        'field51' => 'test',
        'field52' => [
            'field521' => 'test',
        ],
    ],
    'field6' => 'test',
];
$output = [];
$position = [];
$assembleData = function($data) use (&$assembleData, &$output, &$position) {
    foreach ($data as $key=>$val) {
        array_push($position, $key);
        if (is_array($val)) {
            $assembleData($val);
        } else {
            $output[] = implode('/', $position);
        }
        array_pop($position);
    }
};
$assembleData($input);
print_r($output);
</code>```

<p>The output of that is: </p>

```<code>Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field41
    [4] => field4/field42
    [5] => field4/field43
    [6] => field5/field51
    [7] => field5/field52/field521
    [8] => field6
)
</code>```

Body:
I want to make all multidimensional keys merge into single key of output array. My input array be like:

Array
(
    [field1] => test
    [field2] => test
    [field3] => test
    [field4] => Array
        (
            [field5] => test
            [field6] => test
            [field7] => test
            [field8] => test
            [field9] => test
            [field10] => test
            [field11] => test
        )
)

I want output be like:

Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field5
    [4] => field4/field6
    [5] => field4/field7
    [6] => field4/field8
    [7] => field4/field9
    [8] => field4/field10
    [9] => field4/field11
)

My code be like:

function get_data($config_data, $final_arr=array()) {
    foreach($config_data as $key =>$value) {
        if(is_array($value)) {
            $final_arr[]=$key.'=>'.get_data($value, $final_arr[$key]);
        } else {
            $final_arr[]=$key;
        }
    }
    return $final_arr;
}

Body:
You need some form of position marker for that. Take a look at this simple example:

<?php
$input = [
    'field1' => 'test',
    'field2' => 'test',
    'field3' => 'test',
    'field4' => [
        'field41' => 'test',
        'field42' => 'test',
        'field43' => 'test',
    ],
    'field5' => [
        'field51' => 'test',
        'field52' => [
            'field521' => 'test',
        ],
    ],
    'field6' => 'test',
];
$output = [];
$position = [];
$assembleData = function($data) use (&$assembleData, &$output, &$position) {
    foreach ($data as $key=>$val) {
        array_push($position, $key);
        if (is_array($val)) {
            $assembleData($val);
        } else {
            $output[] = implode('/', $position);
        }
        array_pop($position);
    }
};
$assembleData($input);
print_r($output);

The output of that is:

Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4/field41
    [4] => field4/field42
    [5] => field4/field43
    [6] => field5/field51
    [7] => field5/field52/field521
    [8] => field6
)


问:
How to check if a multidimensional array is empty or not?
Basically, I have a multidimensional array, and I need to check whether or not it is simply empty, or not.

I currently have an if statement trying to do this with:

```<code>if(!empty($csv_array))
{
    //My code goes here if the array is not empty
}
</code>```

Although, that if statement is being activated whether the multidimensional array is empty or not.

This is what the array looks like when empty:

```<code>Array
(
    [0] => Array
        (
        )

)
</code>```

This is what the array looks like when it has a few elements in it:

```<code>Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [1] => question1
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [2] => Array
        (
            [1] => question2
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [3] => Array
        (
            [1] => question3
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

)
</code>```

My array elements always start at 1, and not 0. Long story why, and no point explaining since it is off-topic to this question.

If needed, this is the code that is creating the array. It is being pulled from an uploaded CSV file.

```<code>$csv_array = array(array());
if (!empty($_FILES['upload_csv']['tmp_name']))
{
    $file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
}

if($file)
{
    while (($line = fgetcsv($file)) !== FALSE)
    {
        $csv_array[] = array_combine(range(1, count($line)), array_values($line));
    }

    fclose($file);
}
</code>```

So in conclusion, I need to modify my if statement to check whether the array is empty or not.

Thanks in advance!

答:
If you don't know the structure of the multidimensional array

```<code>public function isEmpty(array $array): bool
{
    $empty = true;

    array_walk_recursive($array, function ($leaf) use (&$empty) {
        if ($leaf === [] || $leaf === '') {
            return;
        }

        $empty = false;
    });

    return $empty;
}
</code>```

Just keep in mind all leaf nodes will be parsed.

Body:
Basically, I have a multidimensional array, and I need to check whether or not it is simply empty, or not.

I currently have an if statement trying to do this with:

if(!empty($csv_array))
{
    //My code goes here if the array is not empty
}

Although, that if statement is being activated whether the multidimensional array is empty or not.

This is what the array looks like when empty:

Array
(
    [0] => Array
        (
        )

)

This is what the array looks like when it has a few elements in it:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [1] => question1
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [2] => Array
        (
            [1] => question2
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [3] => Array
        (
            [1] => question3
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

)

My array elements always start at 1, and not 0. Long story why, and no point explaining since it is off-topic to this question.

If needed, this is the code that is creating the array. It is being pulled from an uploaded CSV file.

$csv_array = array(array());
if (!empty($_FILES['upload_csv']['tmp_name']))
{
    $file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
}

if($file)
{
    while (($line = fgetcsv($file)) !== FALSE)
    {
        $csv_array[] = array_combine(range(1, count($line)), array_values($line));
    }

    fclose($file);
}

So in conclusion, I need to modify my if statement to check whether the array is empty or not.

Thanks in advance!

Body:
If you don't know the structure of the multidimensional array

public function isEmpty(array $array): bool
{
    $empty = true;

    array_walk_recursive($array, function ($leaf) use (&$empty) {
        if ($leaf === [] || $leaf === '') {
            return;
        }

        $empty = false;
    });

    return $empty;
}

Just keep in mind all leaf nodes will be parsed.


问:
How to create a thumbnail image of html content stored in a database
If you were to convert this html content into a small thumbnail image , how would you do it?

P.S. I'm trying to do this to allow users on my site to browse through their posts(containing html elements (e.g. strong, i, img tag's).

Body: try http://www.zubrag.com/scripts/website-thumbnail-generator.php


问:
PHP Secure Session's not working
I am trying to figure out how to make a session secure. I have done a lot of research and found what I want, but the secure session is not working correct, and the site does not say how to fix it.

As you look through the code,

Test 1 will fail

but when running it, it needs to pass.

also when you pull $_SESSION variable, there is nothing there in Test1.

What I have noticed is if I put the $_SESSION after encryption it accepts it.

The Function is from the following site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

```<code> $_SESSION['user_id'] = 'test';
 $_SESSION['username'] = 'john';
 $_SESSION['login_string'] = '1234';

 echo 'Session Set<br>';

 sec_session_start();

 // Testing $session pass or fail.

 echo 'test1<br>';

 if (isset($_SESSION['user_id'],
 $_SESSION['username'],
 $_SESSION['login_string'])){
 echo 'test: Pass';
 } else {
 echo 'test: failed';
 }

 echo '<br>';
 echo 'test2<br>';

 $_SESSION['user_id'] = 'test';
 $_SESSION['username'] = 'john';
 $_SESSION['login_string'] = '1234';

 echo 'Session Set<br>';

 if (isset($_SESSION['user_id'],
 $_SESSION['username'],
 $_SESSION['login_string'])){
 echo 'test: Pass';
 } else {
 echo 'test: failed';
 }

// Function from following site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
 function sec_session_start() {
     $session_name = 'sec_session_id';   // Set a custom session name
     /*Sets the session name.
      *This must come before session_set_cookie_params due to an undocumented bug/feature in PHP.
      */
     session_name($session_name);

     $secure = true;
     // This stops JavaScript being able to access the session id.
     $httponly = true;
     // Forces sessions to only use cookies.
     if (ini_set('session.use_only_cookies', 1) === FALSE) {
         header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
         exit();
     }
     // Gets current cookies params.
     $cookieParams = session_get_cookie_params();
     session_set_cookie_params($cookieParams["lifetime"],
         $cookieParams["path"],
         $cookieParams["domain"],
         $secure,
         $httponly);

     session_start();            // Start the PHP session
     session_regenerate_id(true);    // regenerated the session, delete the old one.
 }

 // remove all session variables
 session_unset();

 // destroy the session
 session_destroy();

 ?>
</code>```

答:
Site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

If you look at this order, I have broken down what is happening on webpage where I am getting my code.

When it gets to protected_page.php, its does not have any $_SESSION info to test.

The last IF statement does not detect $_SESSION variable.

```<code> index.php
    db_connect.php > Include_Once
        psl-config.php
    functions.php - sec_session_start()
        session_start();
    process_login.php

    process_login.php > POST from INDEX.PHP
        db_connect.php > Include_Once
            psl-config.php
        functions.php - sec_session_start()
            session_start();
        functions.php - login()
            functions.php - checkbrute()
            $_SESSION['user_id'] = $user_id;
            $_SESSION['username'] = $username;
            $_SESSION['login_string'] = hash('sha512', $db_password . $user_browser);
    protected_page.php

    protected_page.php > Sending $_SESSION, but $_SESSION does not come through.
            db_connect.php > Include_Once
                psl-config.php
            functions.php - sec_session_start()
                session_start();
            functions.php - login_check()
                 if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
                    } else {
                    Failed
                    }
</code>```

Title: PHP Secure Session's not working

Body:
I am trying to figure out how to make a session secure. I have done a lot of research and found what I want, but the secure session is not working correct, and the site does not say how to fix it.

As you look through the code,

Test 1 will fail

but when running it, it needs to pass.

also when you pull $_SESSION variable, there is nothing there in Test1.

What I have noticed is if I put the $_SESSION after encryption it accepts it.

The Function is from the following site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

 $_SESSION['user_id'] = 'test';
 $_SESSION['username'] = 'john';
 $_SESSION['login_string'] = '1234';

 echo 'Session Set
';

 sec_session_start();

 // Testing $session pass or fail.

 echo 'test1
';

 if (isset($_SESSION['user_id'],
 $_SESSION['username'],
 $_SESSION['login_string'])){
 echo 'test: Pass';
 } else {
 echo 'test: failed';
 }

 echo '
';
 echo 'test2
';

 $_SESSION['user_id'] = 'test';
 $_SESSION['username'] = 'john';
 $_SESSION['login_string'] = '1234';

 echo 'Session Set
';

 if (isset($_SESSION['user_id'],
 $_SESSION['username'],
 $_SESSION['login_string'])){
 echo 'test: Pass';
 } else {
 echo 'test: failed';
 }

// Function from following site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
 function sec_session_start() {
     $session_name = 'sec_session_id';   // Set a custom session name
     /*Sets the session name.
      *This must come before session_set_cookie_params due to an undocumented bug/feature in PHP.
      */
     session_name($session_name);

     $secure = true;
     // This stops JavaScript being able to access the session id.
     $httponly = true;
     // Forces sessions to only use cookies.
     if (ini_set('session.use_only_cookies', 1) === FALSE) {
         header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
         exit();
     }
     // Gets current cookies params.
     $cookieParams = session_get_cookie_params();
     session_set_cookie_params($cookieParams["lifetime"],
         $cookieParams["path"],
         $cookieParams["domain"],
         $secure,
         $httponly);

     session_start();            // Start the PHP session
     session_regenerate_id(true);    // regenerated the session, delete the old one.
 }

 // remove all session variables
 session_unset();

 // destroy the session
 session_destroy();

 ?>

Body:
Site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

If you look at this order, I have broken down what is happening on webpage where I am getting my code.

When it gets to protected_page.php, its does not have any $_SESSION info to test.

The last IF statement does not detect $_SESSION variable.

 index.php
    db_connect.php > Include_Once
        psl-config.php
    functions.php - sec_session_start()
        session_start();
    process_login.php

    process_login.php > POST from INDEX.PHP
        db_connect.php > Include_Once
            psl-config.php
        functions.php - sec_session_start()
            session_start();
        functions.php - login()
            functions.php - checkbrute()
            $_SESSION['user_id'] = $user_id;
            $_SESSION['username'] = $username;
            $_SESSION['login_string'] = hash('sha512', $db_password . $user_browser);
    protected_page.php

    protected_page.php > Sending $_SESSION, but $_SESSION does not come through.
            db_connect.php > Include_Once
                psl-config.php
            functions.php - sec_session_start()
                session_start();
            functions.php - login_check()
                 if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
                    } else {
                    Failed
                    }


问:
ruby: curses: Do not clear screen at end of program?
I'm using the ruby curses package (ruby 2.1.5).

In certain cases, I'd like the screen not to be cleared at the end of my program, so that the final contents of Curses.stdscr are still showing on my terminal when the program exits.

I've tried leaving out the call to Curses.close_screen, but the terminal screen still gets cleared upon exit.

Is there any way to tell curses in ruby to not clear the screen when the program is terminating?

Thank you in advance.

答:
The bundled Ruby curses module lacks (many) curses functions such as reset_shell_mode, which would be the usual way to do this:

The reset_prog_mode and reset_shell_mode routines  restore
  the  terminal  to "program" (in curses) or "shell" (out of
  curses) state.  These are done automatically by endwin(3x)
  and,  after  an  endwin, by doupdate, so they normally are
  not called.

Alternatively, you could use MRuby (which provides the function).

In either case, exiting like this can leave your terminal's special keys set to application mode.  The workaround for that would be to send an escape sequence (found in the terminal database as rmkx).


问:
query to select only the timestamp each 5 minutes
I would like to know if it's possible to have a query that will retrieve all the data with the Timestamp is a multiple of 5 minutes for example. (00h00, 00h05, 00h10, etc...)

Here's my query :

```<code>SELECT io_data.Timestamp, io.Name AS ioName, io_data.ReadingValue
FROM io_data io
WHERE io_data.Actif = 1
  AND io.ID_IO_Type = 3
ORDER BY io.Name, io.ID_IO_Type, io_data.Timestamp ASC
</code>```

This is because the system retrieve the value each 3 sec (in some cases) or at each 7.5 sec, 15 sec, 30 sec or 1 minute (in other cases). It depends of the customer settings. But, we I do a chart, that contains too many data and I would like to have only the data for each X minutes (1, 5, 10, etc... minutes)

I can't figure out how can I do that if it's possible.

答:
No need to convert to minutes, just take the minute part of the timestamp column:

```<code>SELECT io.Timestamp, io.Name AS ioName, io.ReadingValue
FROM io_data io
WHERE io.Actif = 1
  AND io.ID_IO_Type = 3
AND minute(io.TimeStamp) % 5 = 0
ORDER BY io.Name, io.ID_IO_Type, io.Timestamp ASC
</code>```

Body:
I would like to know if it's possible to have a query that will retrieve all the data with the Timestamp is a multiple of 5 minutes for example. (00h00, 00h05, 00h10, etc...)

Here's my query :

SELECT io_data.Timestamp, io.Name AS ioName, io_data.ReadingValue
FROM io_data io
WHERE io_data.Actif = 1
  AND io.ID_IO_Type = 3
ORDER BY io.Name, io.ID_IO_Type, io_data.Timestamp ASC

This is because the system retrieve the value each 3 sec (in some cases) or at each 7.5 sec, 15 sec, 30 sec or 1 minute (in other cases). It depends of the customer settings. But, we I do a chart, that contains too many data and I would like to have only the data for each X minutes (1, 5, 10, etc... minutes)

I can't figure out how can I do that if it's possible.

Body:
No need to convert to minutes, just take the minute part of the timestamp column:

SELECT io.Timestamp, io.Name AS ioName, io.ReadingValue
FROM io_data io
WHERE io.Actif = 1
  AND io.ID_IO_Type = 3
AND minute(io.TimeStamp) % 5 = 0
ORDER BY io.Name, io.ID_IO_Type, io.Timestamp ASC


问:
Windows software install automation
I am trying to automate the task of installing a software on Windows 7 and its an .exe file which requires user input in the form of Next or Ok. I have to first push that .exe (WinampInstall.exe) file on to the machines (over 100 of them). Additionally it should run silently without requiring any input from the user.

Until now I have come across AutoIt which can create macros which can replay the actions of the mouse and keyboard. I'm having trouble with the .au3 script, as it doesn't fully automate the installation.

Can I use batch file to run the script as well?

```<code>Run('C:\Users\Desktop\WinampInstall.exe')
_WinWaitActivate("SciTE","Address: C:\Program ")
MouseMove(630,19)
MouseDown("left")
MouseMove(609,-150)
MouseUp("left")
MouseMove(301,9)
MouseDown("left")
MouseMove(578,-18)
MouseUp("left")
</code>```

答:
According to the WinAmp forums, you can use command line switches with the installer.

winamp50*.exe /S /install=SFQDRA

  /S = Silent install

  S  = start menu icons

  F  = file association

  Q  = quicklaunch icon

  D  = desktop icon

  R  = fake registration

  A  = run winamp agent/set default

An example batch-file using command-line switches that would

Copy the WinAmp installer from a network share

Install WinAmp silently (using the /s switch)

```<code>@echo off
set "localPath=%temp%\WinampInstall.exe"
copy "\\network-share\WinampInstall.exe" "%localPath%"
"%localPath%" /S
pause
</code>```

Title: Windows software install automation

Body:
I am trying to automate the task of installing a software on Windows 7 and its an .exe file which requires user input in the form of Next or Ok. I have to first push that .exe (WinampInstall.exe) file on to the machines (over 100 of them). Additionally it should run silently without requiring any input from the user.

Until now I have come across AutoIt which can create macros which can replay the actions of the mouse and keyboard. I'm having trouble with the .au3 script, as it doesn't fully automate the installation.

Can I use batch file to run the script as well?

Run('C:\Users\Desktop\WinampInstall.exe')
_WinWaitActivate("SciTE","Address: C:\Program ")
MouseMove(630,19)
MouseDown("left")
MouseMove(609,-150)
MouseUp("left")
MouseMove(301,9)
MouseDown("left")
MouseMove(578,-18)
MouseUp("left")

Body:
According to the WinAmp forums, you can use command line switches with the installer.

winamp50*.exe /S /install=SFQDRA

  /S = Silent install

  S  = start menu icons

  F  = file association

  Q  = quicklaunch icon

  D  = desktop icon

  R  = fake registration

  A  = run winamp agent/set default

An example batch-file using command-line switches that would

Copy the WinAmp installer from a network share

Install WinAmp silently (using the /s switch)

@echo off
set "localPath=%temp%\WinampInstall.exe"
copy "\\network-share\WinampInstall.exe" "%localPath%"
"%localPath%" /S
pause


问:
Postgres service started, but can't connect. Nothing listening on port 5432
I don't know how this happened, but my postgres server (9.6.2) has stopped working locally.  I seem to be able to start it up, and stop it using:
brew services start postgresql and brew services start postgresql but when I try to connect using psql I get this error:

```<code>psql: could not connect to server: No such file or directory    Is the
server running locally and accepting    connections on Unix domain
socket "/tmp/.s.PGSQL.5432"?
</code>```

When I try to see if anything is listening on port 5432 using lsof -i :5432 I get nothing.

Looked at other posts that say check the pg_hba.conf file, which I did, but doesn't seem to be the problem.

答:
I ended up reinstalling postgres via homebrew.  That by itself didn't do enough.  I had to kill my data directory to get this to work (i.e. rm -rf /path/to/my/data/directory) and then rebuild it using initdb.

This solution obviously only works if you don't care about keeping your data (in my case, it was just data for my dev environment, so I didn't).  If you do want to save a copy of your data, I you'd have to come up with something else.

Body:
I don't know how this happened, but my postgres server (9.6.2) has stopped working locally.  I seem to be able to start it up, and stop it using:
brew services start postgresql and brew services start postgresql but when I try to connect using psql I get this error:

psql: could not connect to server: No such file or directory    Is the
server running locally and accepting    connections on Unix domain
socket "/tmp/.s.PGSQL.5432"?

When I try to see if anything is listening on port 5432 using lsof -i :5432 I get nothing.

Looked at other posts that say check the pg_hba.conf file, which I did, but doesn't seem to be the problem.


问:
Wrong output in mySQL query
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

```<code>SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
</code>```

And here is a picture to go along with what the output looks like:

答:
You are very close:</p>

```<code>SELECT
   brand_name, brand_type,
   round(avgprice,2) AS "Average Price", sub2.Units_Sold AS "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
        FROM lgproduct
        GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
JOIN (SELECT brand_id, Sum(line_qty) AS Units_Sold
     FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
</code>```

Title: Wrong output in mySQL query

Body:
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;

And here is a picture to go along with what the output looks like:

Body:
You are very close:

SELECT
   brand_name, brand_type,
   round(avgprice,2) AS "Average Price", sub2.Units_Sold AS "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
        FROM lgproduct
        GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
JOIN (SELECT brand_id, Sum(line_qty) AS Units_Sold
     FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
ON b.brand_id = sub2.brand_id
ORDER BY brand_name;


问:
Angular 2: Form submission canceled because the form is not connected
I have a modal that contains a form, when the modal is destroyed I get the following error in the console:

Form submission canceled because the form is not connected

The modal is added to a <modal-placeholder> element which is a direct child to <app-root>, my top level element.

What's the correct way to removing a form from the DOM and getting rid of this error in Angular 2? I currently use componentRef.destroy();

答:
There might be other reasons this occurs but in my case I had a button that was interpreted by the browser as a submit button and hence the form was submitted when the button was clicked causing the error. Adding type="button" fixed the issue. Full element:</p>

```<code>    <button type="button" (click)="submitForm()">
</code>```

Body:
There might be other reasons this occurs but in my case I had a button that was interpreted by the browser as a submit button and hence the form was submitted when the button was clicked causing the error. Adding type="button" fixed the issue. Full element:

    <button type="button" (click)="submitForm()">


问:
Wordpress Plugin Development Question!
I am currently writing a plugin for my client in wordpress. The issue I am having is when a user clicks on edit to change a record I am not sure how to create the admin link to do this.

i.e.

```<code><a href="<?php echo get_bloginfo('url'); ?>/wp-admin/admin.php?page=wpsc_product_seo_details">Edit</a>

function wpsc_product_seo_details()
{
    echo "<h2>Hello</h2>";
}
</code>```

I know my markup for the  tag is probably wrong but I was just testing. Do I need to register a hook to do this.

答:
The hook you are looking for is to add actions to the sidebar; there are various ways - add_options_page will add to the options menu, for example. add_menu_page will create a new group for you to add your links.

Check the documentation on adding admin menus for more information.

Title: Wordpress Plugin Development Question!

Body:
I am currently writing a plugin for my client in wordpress. The issue I am having is when a user clicks on edit to change a record I am not sure how to create the admin link to do this.

i.e.

<a href="<?php echo get_bloginfo('url'); ?>/wp-admin/admin.php?page=wpsc_product_seo_details">Edit

function wpsc_product_seo_details()
{
    echo "
Hello
";
}

I know my markup for the  tag is probably wrong but I was just testing. Do I need to register a hook to do this.


问:
connecting to a database in OrientDB console
I'm trying to connect to the GratefulDeadConcerts without any sucess.
I'm using docker.

```<code>orientdb> connect remote:localhost root root

Disconnecting from the database [null]...OK
Connecting to remote Server instance [remote:localhost] with user 'root'...OK
orientdb {server=remote:localhost/}> list databases

Found 5 databases:

* VehicleHistoryGraph (plocal)
* GratefulDeadConcerts (plocal)
* OpenBeer (plocal)
* BetterDemo (plocal)
* Tolkien-Arda (plocal)

orientdb {server=remote:localhost/}> connect plocal:../databases/GratefulDeadConcerts root root

Disconnecting from remote server [remote:localhost/]...
OK
Connecting to database [plocal:../databases/GratefulDeadConcerts] with user 'root'...
Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open local storage '../databases/GratefulDeadConcerts' with mode=rw
        DB name="GratefulDeadConcerts"

Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open the storage 'GratefulDeadConcerts' because it does not exist in path: ../databases/GratefulDeadConcerts
        DB name="GratefulDeadConcerts"
</code>```

what I am doing wrong?

答:
Can you try this?

connect remote:localhost/GratefulDeadConcerts root root

Body:
I'm trying to connect to the GratefulDeadConcerts without any sucess.
I'm using docker.

orientdb> connect remote:localhost root root

Disconnecting from the database [null]...OK
Connecting to remote Server instance [remote:localhost] with user 'root'...OK
orientdb {server=remote:localhost/}> list databases

Found 5 databases:

* VehicleHistoryGraph (plocal)
* GratefulDeadConcerts (plocal)
* OpenBeer (plocal)
* BetterDemo (plocal)
* Tolkien-Arda (plocal)

orientdb {server=remote:localhost/}> connect plocal:../databases/GratefulDeadConcerts root root

Disconnecting from remote server [remote:localhost/]...
OK
Connecting to database [plocal:../databases/GratefulDeadConcerts] with user 'root'...
Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open local storage '../databases/GratefulDeadConcerts' with mode=rw
        DB name="GratefulDeadConcerts"

Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open the storage 'GratefulDeadConcerts' because it does not exist in path: ../databases/GratefulDeadConcerts
        DB name="GratefulDeadConcerts"

what I am doing wrong?


问:
R leaflet - cannot export map
I plot a route on a map using R and leaflet :

```<code>ct <- read.csv("fl1.csv", stringsAsFactors=FALSE)

m <- leaflet(ct, incl.data=TRUE) %>% addTiles()
m %>% addPolylines(~longitude, ~latitude, color = "red", weight = 4
</code>```

RStudio plots exactly what I want:

However, I cannot export it as an HTML.

I tried:

use Export-> Save as web Page

the saveWidget function:

saveWidget(m, file="m.html")

saveWidget(m, '1F.html', selfcontained = FALSE)

saveWidget(m, '1T.html', selfcontained = TRUE)

In all above cases I get an html file, but when I try to open them using Chrome, Firefox and IE, the best I can get is only the route and not the map:

答: It seems to be a problem with the addTiles() function, which you can bypass by recreating your own function. See kgavhane702's workaround here: https://github.com/rstudio/leaflet/issues/192</p>

Title: R leaflet - cannot export map

Body:
I plot a route on a map using R and leaflet :

ct <- read.csv("fl1.csv", stringsAsFactors=FALSE)

m <- leaflet(ct, incl.data=TRUE) %>% addTiles()
m %>% addPolylines(~longitude, ~latitude, color = "red", weight = 4

RStudio plots exactly what I want:

However, I cannot export it as an HTML.

I tried:

use Export-> Save as web Page

the saveWidget function:

saveWidget(m, file="m.html")

saveWidget(m, '1F.html', selfcontained = FALSE)

saveWidget(m, '1T.html', selfcontained = TRUE)

In all above cases I get an html file, but when I try to open them using Chrome, Firefox and IE, the best I can get is only the route and not the map:


问:
Select first value and its related rows out of two values based on column condition otherwise select second value and its related rows
I have the Oracle SQL shown below

```<code>select *
from a
where a.description in ('Rebook All (1)', 'Created stock identifier')
    and a.date between '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    and a.unit = '38240007294677'
</code>```

Now result can have both description multiple times like below for a Unit number or can have 1 of the description.  When it has both description for a Unit number, I need to select only 'Rebook all (1)' (this description can be there many times/many rows as shows below in results) description not 'Created stock identifier' and its related details from table a. When it has only 1 description out of these 2 then if 'Rebook All (1)' is not there, select 'Created stock identifier' and vice versa.

How do I select it?

```<code>  Date                                         Description

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
</code>```

I need results like below when there are both description ('Rebook All (1)', 'Created stock identifier') for a Unit number then should get only ('Rebook All (1)') and all its rows, BUT when have only 1 description out of ('Rebook All (1)', 'Created stock identifier') for a Unit number then get that description -

When have both description ('Rebook All (1)', 'Created stock identifier') for a unit number then get only ('Rebook All (1)') like below -

```<code>3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
</code>```

If have only 1 description 'Created stock identifier' for a unit number then get that 'Created stock identifier' only -

```<code>3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
</code>```

答:
As of Oracle 12c:</p>

```<code>select a.*
from a
where a.unit = '38240007294677'
and a.description in ('Rebook All (1)', 'Created stock identifier')
and a.date >= date '2017-01-18'
and a.date <  date '2017-03-25'
order by case when a.description = 'Rebook All (1)' then 1 else 2 end
fetch first row with ties;
</code>```

Body:
I have the Oracle SQL shown below

select *
from a
where a.description in ('Rebook All (1)', 'Created stock identifier')
    and a.date between '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    and a.unit = '38240007294677'

Now result can have both description multiple times like below for a Unit number or can have 1 of the description.  When it has both description for a Unit number, I need to select only 'Rebook all (1)' (this description can be there many times/many rows as shows below in results) description not 'Created stock identifier' and its related details from table a. When it has only 1 description out of these 2 then if 'Rebook All (1)' is not there, select 'Created stock identifier' and vice versa.

How do I select it?

  Date                                         Description

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)

I need results like below when there are both description ('Rebook All (1)', 'Created stock identifier') for a Unit number then should get only ('Rebook All (1)') and all its rows, BUT when have only 1 description out of ('Rebook All (1)', 'Created stock identifier') for a Unit number then get that description -

When have both description ('Rebook All (1)', 'Created stock identifier') for a unit number then get only ('Rebook All (1)') like below -

3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)

If have only 1 description 'Created stock identifier' for a unit number then get that 'Created stock identifier' only -

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier

Body:
As of Oracle 12c:

select a.*
from a
where a.unit = '38240007294677'
and a.description in ('Rebook All (1)', 'Created stock identifier')
and a.date >= date '2017-01-18'
and a.date <  date '2017-03-25'
order by case when a.description = 'Rebook All (1)' then 1 else 2 end
fetch first row with ties;