问:
ACID update of ElasticSearch Document
I'm trying to build a Tinder-like system right now. Here I need to know which cards have already been seen.

If I save the cards in ElasticSearch, and then have such a document:

{ nama: David, location: {lat, lon}, seenFromUsers: [] }

I'm just wondering if it makes sense to create a list in the object itself. Probably there are 2000 entries in it.
But if I do an update in ElasticSearch, then I always have to pass all 2000 entries. If two users do this at the same time, does one get lost? How can I simply add another ID to the array? Is that even possible?

What other solutions are there?

答:
One other solution would be a complete different approach. Instead if creating documents like this

```<code>{
  "name": "David",
  "location": { "lat": ..., "lon": ...},
  "seenFromUsers": ["Laura", "Simone"]
}
</code>```

think in Relations like this:

```<code>{
  "name": "David",
  "seenBy": "Laura"
}

{
  "name": "David",
  "seenBy": "Simone"
}
</code>```

this approach will give you simpler queries, and the ACID problem is solved. New profile views are simply new documents...

As a benefit, you´ll get rid of inner objects and it will be more easy to add additional data to this relation:

```<code>{
  "name": "David",
  "seenBy": "Laura",
  "timestamp": ...,
  "liked": true
}

{
  "name": "David",
  "seenBy": "Simone",
  "timestamp": ...,
  "liked": false
}
</code>```

And now you´ll be able to do a simple query for all positive likes of a profile, or bi-directional likes/matches...

Title: ACID update of ElasticSearch Document

Body:
One other solution would be a complete different approach. Instead if creating documents like this

{
  "name": "David",
  "location": { "lat": ..., "lon": ...},
  "seenFromUsers": ["Laura", "Simone"]
}

think in Relations like this:

{
  "name": "David",
  "seenBy": "Laura"
}

{
  "name": "David",
  "seenBy": "Simone"
}

this approach will give you simpler queries, and the ACID problem is solved. New profile views are simply new documents...

As a benefit, you´ll get rid of inner objects and it will be more easy to add additional data to this relation:

{
  "name": "David",
  "seenBy": "Laura",
  "timestamp": ...,
  "liked": true
}

{
  "name": "David",
  "seenBy": "Simone",
  "timestamp": ...,
  "liked": false
}

And now you´ll be able to do a simple query for all positive likes of a profile, or bi-directional likes/matches...


来源: stackexchange

问:
How to set the attributes of the main  tag(at the top of the source code) for the Shiny application
I have a working R Shiny app, but in order to be meet the accessibility requirements (e.g. so that the web page readers for the blind could operate with the landing page) the language attribute (lang ="en") should be set in the main html tag i.e.: <!doctype html>  .....

I have my ui.R code starting with the dashboardPage() function, but if I put e.g. HTML("") into any of its arguments - the resulting app's source code will show this line in the body (created by dashboardBody() ), while I need it in the very top  tag (supposedly created by the shiny package itself when rendering the app's UI).

This is what I'm getting (when viewing the source html code of the working shiny app:

```<code><!DOCTYPE html>
<html>
<head>
</code>```

While what I need looks like the following:

```<code><!DOCTYPE html>
<html class="no-js" lang="en">
<head>
</code>```

答:
You can do

```<code>tags$html(class = "no-js", lang="en")
</code>```

I don't use shinydashboard, but I think you have to place this code in the dashboardBody.

ContentLicense: CC BY-SA 4.0

Title: How to set the attributes of the main <html> tag(at the top of the source code) for the Shiny application

Body:
I have a working R Shiny app, but in order to be meet the accessibility requirements (e.g. so that the web page readers for the blind could operate with the landing page) the language attribute (lang ="en") should be set in the main html tag i.e.: <!doctype html>  .....

I have my ui.R code starting with the dashboardPage() function, but if I put e.g. HTML("") into any of its arguments - the resulting app's source code will show this line in the body (created by dashboardBody() ), while I need it in the very top  tag (supposedly created by the shiny package itself when rendering the app's UI).

This is what I'm getting (when viewing the source html code of the working shiny app:

<!DOCTYPE html>

While what I need looks like the following:

<!DOCTYPE html>

Body:
You can do

tags$html(class = "no-js", lang="en")

I don't use shinydashboard, but I think you have to place this code in the dashboardBody.


问:
Edit headers of fancybox ajax request
Hello I am trying to alter ajax request headers while opening fancybox.
So far I can not seem to make it work even according to documentation. After stating type to be ajax i should be able to edit ajax according to jquery documentation.

So far it does work without headers like this (everything is inside jQ on click event):

```<code>$.fancybox.open( $(this), {
        type: 'ajax',
        helpers: {
            overlay: {
                locked: false
            }
        }
    });
</code>```

The problem comes when i try to alter ajax request. This is what i tried and does not work:

```<code>$.fancybox.open({
            type: 'ajax',
            ajax: {
                url: siteUrl + href,
                type: 'GET',
                headers: {
                    'fooheader' : 'bar'
                }
            },
            helpers: {
                overlay: {
                    locked: false
                }
            }
        });
</code>```

What happens when I execute previous code is that it redirects me back to the same page i clicked from.

Does anyone have experience with adding headers inside fancybox ajax request?

答:
Adding headers inside the fancybox ajax request:</p>

```<code><a href="javascript:void(0);" id="linkName" class="fancybox" >Fancybox Link Name</a>

 <script type="text/javascript">
      $(document).ready(function() {
        var name = "This is text that will be send into ajax request";
        $("#linkName").click(function() {
          $.fancybox.showLoading(); //Loader before the ajax request
          $.ajax({
              type : "POST",
            headers: {
                  'Authorization':'Basic xxxxxxxxxxxxx',
                  'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
                  'Content-Type':'application/json' },
            cache : false,
            url : "testfile.php",   //File url
            data  : 'myText=' + name, //Ajax requested data
            success : function(data) {
              $.fancybox(data);  //Get response into data variable
            }
          });
          return false;
        });
      });
    </script>
</code>```

Title: Edit headers of fancybox ajax request

Body:
Hello I am trying to alter ajax request headers while opening fancybox.
So far I can not seem to make it work even according to documentation. After stating type to be ajax i should be able to edit ajax according to jquery documentation.

So far it does work without headers like this (everything is inside jQ on click event):

$.fancybox.open( $(this), {
        type: 'ajax',
        helpers: {
            overlay: {
                locked: false
            }
        }
    });

The problem comes when i try to alter ajax request. This is what i tried and does not work:

$.fancybox.open({
            type: 'ajax',
            ajax: {
                url: siteUrl + href,
                type: 'GET',
                headers: {
                    'fooheader' : 'bar'
                }
            },
            helpers: {
                overlay: {
                    locked: false
                }
            }
        });

What happens when I execute previous code is that it redirects me back to the same page i clicked from.

Does anyone have experience with adding headers inside fancybox ajax request?

Body:
Adding headers inside the fancybox ajax request:

<a href="javascript:void(0);" id="linkName" class="fancybox" >Fancybox Link Name</a>

 <script type="text/javascript">
      $(document).ready(function() {
        var name = "This is text that will be send into ajax request";
        $("#linkName").click(function() {
          $.fancybox.showLoading(); //Loader before the ajax request
          $.ajax({
              type : "POST",
            headers: {
                  'Authorization':'Basic xxxxxxxxxxxxx',
                  'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
                  'Content-Type':'application/json' },
            cache : false,
            url : "testfile.php",   //File url
            data  : 'myText=' + name, //Ajax requested data
            success : function(data) {
              $.fancybox(data);  //Get response into data variable
            }
          });
          return false;
        });
      });
    </script>


问:
Converting a constant array to a constant string
I've this code:

```<code>const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];
</code>```

I use the TYPE_ARRAY to check if a type is valid by using in_array(). But I also need to do a regex check, but I can't use this array directly for that. I need a string in the form: "a|b|c", which is equivalent to:

```<code>implode('|', TYPE_ARRAY);
</code>```

But in stead of doing this:

```<code>const TYPE_REGEX_STR = "a|b|c";
</code>```

I wonder if it wouldn't be possible to convert the const TYPE_ARRAY automatically to a constant with the regex. So something like this:

```<code>const TYPE_REGEX_STR = implode('|', TYPE_ARRAY);
</code>```

I know that this last example is not possible, but is there a another way do this?

This might seem silly, but when you have an array with many possible types, it would be better to create the const TYPE_REGEX_STR based on the const TYPE_ARRAY instead of defining it separately. In that way it would be easier to add a new type: just add it to the array and the regex string is made automatically.

Btw I need TYPE_REGEX_STR as a constant because Symfony can use a constant in the route requirements, but not a static function.

答:
You could use define</p>

```<code><?php

const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];

define ( 'TYPE_REGEX_STR' , implode('|', TYPE_ARRAY) );

echo TYPE_REGEX_STR;
</code>```

Body:
I've this code:

const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];

I use the TYPE_ARRAY to check if a type is valid by using in_array(). But I also need to do a regex check, but I can't use this array directly for that. I need a string in the form: "a|b|c", which is equivalent to:

implode('|', TYPE_ARRAY);

But in stead of doing this:

const TYPE_REGEX_STR = "a|b|c";

I wonder if it wouldn't be possible to convert the const TYPE_ARRAY automatically to a constant with the regex. So something like this:

const TYPE_REGEX_STR = implode('|', TYPE_ARRAY);

I know that this last example is not possible, but is there a another way do this?

This might seem silly, but when you have an array with many possible types, it would be better to create the const TYPE_REGEX_STR based on the const TYPE_ARRAY instead of defining it separately. In that way it would be easier to add a new type: just add it to the array and the regex string is made automatically.

Btw I need TYPE_REGEX_STR as a constant because Symfony can use a constant in the route requirements, but not a static function.

Body:
You could use define

<?php

const TYPE_A = 'a';
const TYPE_B = 'b';
const TYPE_C = 'c';

const TYPE_ARRAY = [
TYPE_A,
TYPE_B,
TYPE_C,
];

define ( 'TYPE_REGEX_STR' , implode('|', TYPE_ARRAY) );

echo TYPE_REGEX_STR;


问:
Documents directory in objective C
In Xcode, the Resources folder links to the NSDocumentsFolder of the app? Or what else?

Is there a way to see the files in NSDocumentFolder without write code?

答:
The folders you use in XCode will not be copied to your application bundle even though all their content (as well as anything else you have in your XCode project...excluding compiled resources) will be flatly copied into your Bundle Folder. If what you need is accessing the Documents folder on an iOS app or in a the User's library you can access it (by code, I'm sorry) with:

```<code>NSString *documentFolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
</code>```

And anything you need to be in there you will have to copy by code.

ContentLicense: CC BY-SA 3.0

Title: Documents directory in objective C

Body:
The folders you use in XCode will not be copied to your application bundle even though all their content (as well as anything else you have in your XCode project...excluding compiled resources) will be flatly copied into your Bundle Folder. If what you need is accessing the Documents folder on an iOS app or in a the User's library you can access it (by code, I'm sorry) with:

NSString *documentFolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

And anything you need to be in there you will have to copy by code.


问:
Exclude elements from group in SCSS
Imagine a set of rules like the ones shown below:

```<code>span, div { color: red; }
span { background: white; }
div { background: black; }
</code>```

Is it possible to wrap them under 1 SCSS rule? Something in the form of:

```<code>span, div {
    & { color: red; }
    &:not(div) { background: white;}
    &:not(span) { background: black; }
}
</code>```

Unfortunately an approach like this could very easily get quite large. So I'm hoping for an SCSS implementation of the code shown at the top but without the use of :not(<every other selector>).

Preferably something looking like (invalid code):

```<code>span, div {
    & { color: red; }
    &(span) { background: white;}
    &(span) { background: black; }
}
</code>```

答:
I don't think that it is possible to do what you want this way (but I may be wrong).

The code below achieve the result you are looking for but uses a map, a @mixin and @extend instead of a single selector. Maybe it's a bit too complex for want you want to achieve but I hope it can help:

```<code>@mixin setSelectors($elements) {
  %commonProperties {
    @content;
  }

  @each $selector, $properties in $elements {
    #{$selector} {
      @extend %commonProperties;
      @each $property, $value in $properties {
        #{$property}: #{$value};
      }
    }
  }
}

@include setSelectors((
  span: (background: white),
  div: (background: black)
)) {
  color: red; // Common properties
}
</code>```

Will return:

```<code>div, span { color: red; }
span { background: white; }
div { background: black; }
</code>```

The first argument is a map containing all your selectors and their specific properties. The @content of the @mixin contains shared properties.
If you need to add a selector that doesn't have any specific property, you can add it to the map with null as key. Such as:

```<code>@include setSelectors((
  span: (background: white),
  div: (background: black),
  i: null
)) {
  color: red;
}
</code>```

However, this solution doesn't allow nested selectors so I believe that separating the selectors is the best way to go.

Title: Exclude elements from group in SCSS

Body:
Imagine a set of rules like the ones shown below:

span, div { color: red; }
span { background: white; }
div { background: black; }

Is it possible to wrap them under 1 SCSS rule? Something in the form of:

span, div {
    & { color: red; }
    &:not(div) { background: white;}
    &:not(span) { background: black; }
}

Unfortunately an approach like this could very easily get quite large. So I'm hoping for an SCSS implementation of the code shown at the top but without the use of :not(<every other selector>).

Preferably something looking like (invalid code):

span, div {
    & { color: red; }
    &(span) { background: white;}
    &(span) { background: black; }
}

Body:
I don't think that it is possible to do what you want this way (but I may be wrong).

The code below achieve the result you are looking for but uses a map, a @mixin and @extend instead of a single selector. Maybe it's a bit too complex for want you want to achieve but I hope it can help:

@mixin setSelectors($elements) {
  %commonProperties {
    @content;
  }

  @each $selector, $properties in $elements {
    #{$selector} {
      @extend %commonProperties;
      @each $property, $value in $properties {
        #{$property}: #{$value};
      }
    }
  }
}

@include setSelectors((
  span: (background: white),
  div: (background: black)
)) {
  color: red; // Common properties
}

Will return:

div, span { color: red; }
span { background: white; }
div { background: black; }

The first argument is a map containing all your selectors and their specific properties. The @content of the @mixin contains shared properties.
If you need to add a selector that doesn't have any specific property, you can add it to the map with null as key. Such as:

@include setSelectors((
  span: (background: white),
  div: (background: black),
  i: null
)) {
  color: red;
}

However, this solution doesn't allow nested selectors so I believe that separating the selectors is the best way to go.


答:
You will want to use define</p>

```<code>define( 'TYPE_REGEX_STR', implode('|', TYPE_ARRAY) );
</code>```

Title: Converting a constant array to a constant string

Body:
You will want to use define

define( 'TYPE_REGEX_STR', implode('|', TYPE_ARRAY) );


问:
how to hide a scoll area in qt?
I am trying to hide a scroll area but running these commands just make it smaller and more towards the bottom. I am trying to close a scroll area which has a live webcam feed in it. I have tried the hide and the close command and neither of those are working.</p>

```<code>    connect(mCameraAction, &QAction::triggered, [&](){
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();

        ui->ScrollArea->show();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        mCamera->start();

    });

    connect(mGantryAction,&QAction::triggered, [&](){
        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();

        ui->xAxis->setLayout(mLayout);
        ui->yAxis->setLayout(mLayout);
        ui->zAxis->setLayout(mLayout);
        ui->xRotate->setLayout(mLayout);
        ui->yRotate->setLayout(mLayout);
        ui->zRotate->setLayout(mLayout);
        ui->x1Label->setLayout(mLayout);
        ui->y1Label->setLayout(mLayout);
        ui->z1Label->setLayout(mLayout);
        ui->x2Label->setLayout(mLayout);
        ui->y2Label->setLayout(mLayout);
        ui->z2Label->setLayout(mLayout);
        ui->x1Label->show();
        ui->y1Label->show();
        ui->z1Label->show();
        ui->x2Label->show();
        ui->y2Label->show();
        ui->z2Label->show();
        ui->xAxis->show();
        ui->yAxis->show();
        ui->zAxis->show();
        ui->xRotate->show();
        ui->yRotate->show();
        ui->zRotate->show();

    });
</code>```

答:
QScrollArea is a QFrame descendant. If you set the frame shape to QFrame::NoFrame
Try :</p>

```<code>setFrameShape(QFrame::NoFrame);
</code>```

Title: how to hide a scoll area in qt?

Body:
I am trying to hide a scroll area but running these commands just make it smaller and more towards the bottom. I am trying to close a scroll area which has a live webcam feed in it. I have tried the hide and the close command and neither of those are working.

    connect(mCameraAction, &QAction::triggered, [&](){
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();

        ui->ScrollArea->show();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        mCamera->start();

    });

    connect(mGantryAction,&QAction::triggered, [&](){
        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();

        ui->xAxis->setLayout(mLayout);
        ui->yAxis->setLayout(mLayout);
        ui->zAxis->setLayout(mLayout);
        ui->xRotate->setLayout(mLayout);
        ui->yRotate->setLayout(mLayout);
        ui->zRotate->setLayout(mLayout);
        ui->x1Label->setLayout(mLayout);
        ui->y1Label->setLayout(mLayout);
        ui->z1Label->setLayout(mLayout);
        ui->x2Label->setLayout(mLayout);
        ui->y2Label->setLayout(mLayout);
        ui->z2Label->setLayout(mLayout);
        ui->x1Label->show();
        ui->y1Label->show();
        ui->z1Label->show();
        ui->x2Label->show();
        ui->y2Label->show();
        ui->z2Label->show();
        ui->xAxis->show();
        ui->yAxis->show();
        ui->zAxis->show();
        ui->xRotate->show();
        ui->yRotate->show();
        ui->zRotate->show();

    });

Body:
QScrollArea is a QFrame descendant. If you set the frame shape to QFrame::NoFrame
Try :

setFrameShape(QFrame::NoFrame);


问:
How to convert byte array into image without saving it into file in python?
How to convert byte array into image without using file in python?</p>

```<code>#image to bytearray
with open("C:/Downloads/myimage.jpeg", "rb") as image:
    f = image.read()
    b = bytearray(f)
#bytearray to image
f = open('xyz.jpeg', 'wb')
f.write(bytearray(b))
f.close()
</code>```

答:
You can use Pillow. First install it: pip install Pillow

```<code>import io
from PIL import Image

#image to bytearray
with open("C:/Downloads/myimage.jpeg", "rb") as image:
    f = image.read()
    b = bytearray(f)

image = Image.open(io.BytesIO(b))
image.show()
# image.save("C:/Downloads/myimage_new.jpeg", "JPEG")  # to save the image
</code>```

Body:
How to convert byte array into image without using file in python?

#image to bytearray
with open("C:/Downloads/myimage.jpeg", "rb") as image:
    f = image.read()
    b = bytearray(f)
#bytearray to image
f = open('xyz.jpeg', 'wb')
f.write(bytearray(b))
f.close()

Body:
You can use Pillow. First install it: pip install Pillow

import io
from PIL import Image

#image to bytearray
with open("C:/Downloads/myimage.jpeg", "rb") as image:
    f = image.read()
    b = bytearray(f)

image = Image.open(io.BytesIO(b))
image.show()
# image.save("C:/Downloads/myimage_new.jpeg", "JPEG")  # to save the image


问:
WWW Unity: not showing text
I am trying to assign a text taken from a page linked to a Database through the WWW class to a Text (in the code linguaitaliana) that I inserted inside Unity.

Through the script I propose below, I take the name in the Update function and insert it into the IEnumerator function.

Here is my code

```<code>public class Prova2 : MonoBehaviour
{
    Prova script1;
    public string name;
    public Text linguaitaliana=null;
    IEnumerator Start()
    {
        Thread.Sleep(1000);
        WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
        Debug.Log("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
        string DataString = DataIta.text;
        Debug.Log(DataString);
        linguaitaliana.text = DataString;
    }

    void Update()
    {
        script1=gameObject.GetComponent<Prova>();
        name=script1.due;
    }
}
</code>```

DataIta is correct, since the link is the working one. But when I do DataIta.text, I don't get the text I want (it's empty!)

If I try to put the link directly (without concatenation) inside the script like

```<code>new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=CasaLuigi");
//Debug.Log("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
</code>```

the result is correct

Just for completion this is the setup in the Inspector

The problem is, therefore, of printing. Solutions?

答:
Multiple issues here:

First of all

I take the name in the Update function and insert it into the IEnumerator function.

Nope! Start is executed before Update so you don't pass the name in there. Anyway it wouldn't make sense in an Update method which is called every frame so move it to the top of the Start instead.

Second

this Thread.Sleep(1000); makes no sense! I guess you ment to use WaitForSeconds

```<code>yield return new WaitForSeconds(1);
</code>```

in order to wait a second.

Finally

You created an http request using

```<code>WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
</code>```

but you don't wait until it is finished with downloading. You should do

```<code>using(WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" + name))
{
    yield return www;

    // use result
}
</code>```

In general I would recommend to rather use UnityWebRequest.Get instead of WWW which is obsolete and might get removed in the future. And also check for download or connection errors

```<code>public class Prova2 : MonoBehaviour
{
    Prova script1;
    public string name;
    public Text linguaitaliana=null;
    IEnumerator Start()
    {
        script1=gameObject.GetComponent<Prova>();
        name=script1.due;

        yield return new WaitForSeconds(1);

        using (var webRequest = UnityWebRequest.Get("http://arnaples.altavista.org/QueryTestoITA.phpnum=" + name))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogFormat(this, "Download error due to {0} - {1}", webRequest.responseCode, webRequest.error);
            }
            else
            {
                Debug.Log("Download complete: " + webRequest.downloadHandler.text, this);
                linguaitaliana.text = webRequest.downloadHandler.text;
            }
        }
    }
}
</code>```

Note: Typed on smartphone so no warranty but I hope the idea gets clear

Title: WWW Unity: not showing text

Body:
I am trying to assign a text taken from a page linked to a Database through the WWW class to a Text (in the code linguaitaliana) that I inserted inside Unity.

Through the script I propose below, I take the name in the Update function and insert it into the IEnumerator function.

Here is my code

public class Prova2 : MonoBehaviour
{
    Prova script1;
    public string name;
    public Text linguaitaliana=null;
    IEnumerator Start()
    {
        Thread.Sleep(1000);
        WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
        Debug.Log("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);
        string DataString = DataIta.text;
        Debug.Log(DataString);
        linguaitaliana.text = DataString;
    }

    void Update()
    {
        script1=gameObject.GetComponent<Prova>();
        name=script1.due;
    }
}

DataIta is correct, since the link is the working one. But when I do DataIta.text, I don't get the text I want (it's empty!)

If I try to put the link directly (without concatenation) inside the script like

new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=CasaLuigi");
//Debug.Log("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);

the result is correct

Just for completion this is the setup in the Inspector

The problem is, therefore, of printing. Solutions?

Body:
Multiple issues here:

First of all

I take the name in the Update function and insert it into the IEnumerator function.

Nope! Start is executed before Update so you don't pass the name in there. Anyway it wouldn't make sense in an Update method which is called every frame so move it to the top of the Start instead.

Second

this Thread.Sleep(1000); makes no sense! I guess you ment to use WaitForSeconds

yield return new WaitForSeconds(1);

in order to wait a second.

Finally

You created an http request using

WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" +name);

but you don't wait until it is finished with downloading. You should do

using(WWW DataIta = new WWW("http://arnaples.altavista.org/QueryTestoITA.phpnum=" + name))
{
    yield return www;

    // use result
}

In general I would recommend to rather use UnityWebRequest.Get instead of WWW which is obsolete and might get removed in the future. And also check for download or connection errors

public class Prova2 : MonoBehaviour
{
    Prova script1;
    public string name;
    public Text linguaitaliana=null;
    IEnumerator Start()
    {
        script1=gameObject.GetComponent<Prova>();
        name=script1.due;

        yield return new WaitForSeconds(1);

        using (var webRequest = UnityWebRequest.Get("http://arnaples.altavista.org/QueryTestoITA.phpnum=" + name))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogFormat(this, "Download error due to {0} - {1}", webRequest.responseCode, webRequest.error);
            }
            else
            {
                Debug.Log("Download complete: " + webRequest.downloadHandler.text, this);
                linguaitaliana.text = webRequest.downloadHandler.text;
            }
        }
    }
}

Note: Typed on smartphone so no warranty but I hope the idea gets clear


问:
Tab loading screen - Android
I have 5 Tabs and on 2 of theme there is a content provided from our server. There is about 170 items in ListVie in each of tabs. To download and process data it can take about 1 second (or more - depend on signal strength)...

Let me be more exact... I have 5 tabs (tab1, tab2, tab3, tab4, tab5). First two (tab1 and tab2) receives content from servers. When I click from whatever tab to tab1 or tab2 it takes time to switch and looks like app freezes. Therefore I would like to create a loader... How to do that in tabs?

答: This may well help Android: Showing indeterminate progress bar in TabHost activity</p>

Title: Tab loading screen - Android


问:
Why does bottom table cell that has centered-text get cut off when displayed as PDF in iOS?
Question

I have an iOS app that takes an html file, turns it into a PDF, and displays it to a WebKit web view. I have a weird problem where the bottom table cell gets cut off when I display to PDF. The weird thing is that the bottom table is only cut off when the text is centered. If it is left-aligned, everything works fine. Why does this happen?

Please note that I am not looking for a work around solution. Rather, I am seeking to understand why this happens. Is this a bug in iOS? Or did I miss something?

Overview

In the image below, there are two tables
. One table is large, has a reddish (coral) background, and has a height of 505px. The other table is below the first with a white background (height is not set). Both have some text. The text is centered for both tables.

The navbar title shows the details of the current view. For example, as shown in the image below, a title of PDF Landscape 505 means that the view shows a PDF in landscape dimensions with a main table height of 505px.

The Problem

The problem arises when I increase the height by 10px. In the image below, the main table height is 515px and the lower table is now cut off.

Take the exact same html and css code and change only the text-alignment to be left-aligned. Now the lower table is not cut off anymore. I also changed the background color to green for distinction. Green means that text is left-aligned. Red means that text is centered.

The following image shows a main-table height of 745px and still the lower table is not cut off because it is left-aligned.

Code

Below is the html code used for this test.

```<code><!DOCTYPE html>
<html>
<head>
  <title>#COLOR#</title>
  <meta charset="utf-8">
  <style>
  table, th, td {
    border-collapse: collapse;
    border: 3px solid black;
    text-align: #ALIGN#;
  }
  table.main-table {
    width: 1012px;
    height: #HEIGHT#px;
    background-color: #COLOR#;
  }
  table.bottom-table {
    width: 1012px;
  }
  </style>
</head>

<body>

  <table class="main-table">
    <tr><td>Hello World.</td></tr>
  </table>
  <table class="bottom-table">
    <tr><td>This text gets cut off when centered. It does *not* get cut when left-aligned.</td></tr>
  </table>

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

In MyViewController, the getHTML() function pulls the html source from sample.html. The function then replaces #ALIGN#, #COLOR#, and #HEIGHT# with their respective values.

```<code>func getHTML() -> String? {
    let htmlPath: String? = Bundle.main.path(forResource: htmlResource, ofType: "html")
    guard let path = htmlPath else { return nil }
    do {
        // Load the HTML template code into a String variable.
        var html = try String(contentsOfFile: path)
        html = html.replacingOccurrences(of: "#HEIGHT#", with: tableHeight.description)
        html = html.replacingOccurrences(of: "#COLOR#", with: colorState.rawValue)
        html = html.replacingOccurrences(of: "#ALIGN#", with: alignState.rawValue)
        return html
    } catch {
        print("Error: " + error.localizedDescription)
    }
    return nil
}
</code>```

The PDFBuilder class handles the PDF creation with one function:

```<code>static func exportHTMLToPDF(html: String, frame: CGRect) -> Data {
    // Set a printable frame and inset
    let pageFrame = frame
    let insetRect = pageFrame.insetBy(dx: 10.0, dy: 10.0)

    // Create a UIPrintPageRenderer and set the paperRect and printableRect using above values.
    let pageRenderer = UIPrintPageRenderer()
    pageRenderer.setValue(pageFrame, forKey: "paperRect")
    pageRenderer.setValue(insetRect, forKey: "printableRect")

    // Create a printFormatter and pass the HTML code as a string.
    let printFormatter = UIMarkupTextPrintFormatter(markupText: html)

    // Add the printFormatter to the pageRenderer
    pageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

    // This data var is where the PDF will be stored once created.
    let data = NSMutableData()

    // This is where the PDF gets drawn.
    UIGraphicsBeginPDFContextToData(data, pageFrame, nil)
    UIGraphicsBeginPDFPage()
    pageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())
    print("bounds: " + UIGraphicsGetPDFContextBounds().debugDescription)
    UIGraphicsEndPDFContext()

    return data as Data
}
</code>```

This project is also on Github:
 https://github.com/starkindustries/PrintPDFTest

Troubleshooting Steps Taken

Dimensions: I tried playing around with the size of the PDF dimensions. This did not make a difference in the result.

Columns: I tried using multiple columns instead of just one. Same problem; no difference.

Tables: I tried using just one table instead of two. With one table and two cells, the bottom cell still gets cut off when text is centered; bottom cell does not get cut when text is left-aligned.

iPhones: I tried simulating on different iPhone devices (iPhone 6s, iPhone 8, iPad Pro). Same issue.

Div: If you use a div instead of a second table, the problem is magically fixed. But why does a div work and not a table?

App Notes

The top toolbar has two buttons: green and red. Green makes the text left-aligned. Red makes the text centered.

The bottom toolbar has five buttons: rewind, html, portrait, landscape, and fast forward. The rewind button reduces the main table's height by 10px. Fast forward increases the height by 10px. The html button shows the html view. Portrait and landscape show PDF's in their respective orientations.

答:
I had many troubles with PDF rendering in order to keep the exact same aspect and size then my HTML file once transformed (mostly because of resolution translation problems).

The best and simpliest workaround that I found is to encapsulate the content in a container that exactly fit the height of the document.
You can use the media query to apply your css code only on the print result if you want to display your source html file.

table, th, td {
  border-collapse: collapse;
  border: 3px solid black;
  text-align: center;
}

table.main-table {
  width: 1012px;
  height: 515px;
  background-color: #f4f4f4;
}

table.bottom-table {
  width: 1012px;
}

@media print {
  .main-container{
    height:1100px;/* adjust the height to fit your PDF document*/
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container">
  <table class="main-table">
    <tr><td>Hello World.</td></tr>
  </table>
  <table class="bottom-table">
    <tr><td>This text gets cut off when centered. It does *not* get cut when left-aligned.</td></tr>
  </table>
 </div></code>```

Body:
Question

I have an iOS app that takes an html file, turns it into a PDF, and displays it to a WebKit web view. I have a weird problem where the bottom table cell gets cut off when I display to PDF. The weird thing is that the bottom table is only cut off when the text is centered. If it is left-aligned, everything works fine. Why does this happen?

Please note that I am not looking for a work around solution. Rather, I am seeking to understand why this happens. Is this a bug in iOS? Or did I miss something?

Overview

In the image below, there are two tables
. One table is large, has a reddish (coral) background, and has a height of 505px. The other table is below the first with a white background (height is not set). Both have some text. The text is centered for both tables.

The navbar title shows the details of the current view. For example, as shown in the image below, a title of PDF Landscape 505 means that the view shows a PDF in landscape dimensions with a main table height of 505px.

The Problem

The problem arises when I increase the height by 10px. In the image below, the main table height is 515px and the lower table is now cut off.

Take the exact same html and css code and change only the text-alignment to be left-aligned. Now the lower table is not cut off anymore. I also changed the background color to green for distinction. Green means that text is left-aligned. Red means that text is centered.

The following image shows a main-table height of 745px and still the lower table is not cut off because it is left-aligned.

Code

Below is the html code used for this test.

<!DOCTYPE html>

  <title>#COLOR#</title>
  <meta charset="utf-8">

Hello World.

This text gets cut off when centered. It does *not* get cut when left-aligned.

In MyViewController, the getHTML() function pulls the html source from sample.html. The function then replaces #ALIGN#, #COLOR#, and #HEIGHT# with their respective values.

func getHTML() -> String? {
    let htmlPath: String? = Bundle.main.path(forResource: htmlResource, ofType: "html")
    guard let path = htmlPath else { return nil }
    do {
        // Load the HTML template code into a String variable.
        var html = try String(contentsOfFile: path)
        html = html.replacingOccurrences(of: "#HEIGHT#", with: tableHeight.description)
        html = html.replacingOccurrences(of: "#COLOR#", with: colorState.rawValue)
        html = html.replacingOccurrences(of: "#ALIGN#", with: alignState.rawValue)
        return html
    } catch {
        print("Error: " + error.localizedDescription)
    }
    return nil
}

The PDFBuilder class handles the PDF creation with one function:

static func exportHTMLToPDF(html: String, frame: CGRect) -> Data {
    // Set a printable frame and inset
    let pageFrame = frame
    let insetRect = pageFrame.insetBy(dx: 10.0, dy: 10.0)

    // Create a UIPrintPageRenderer and set the paperRect and printableRect using above values.
    let pageRenderer = UIPrintPageRenderer()
    pageRenderer.setValue(pageFrame, forKey: "paperRect")
    pageRenderer.setValue(insetRect, forKey: "printableRect")

    // Create a printFormatter and pass the HTML code as a string.
    let printFormatter = UIMarkupTextPrintFormatter(markupText: html)

    // Add the printFormatter to the pageRenderer
    pageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

    // This data var is where the PDF will be stored once created.
    let data = NSMutableData()

    // This is where the PDF gets drawn.
    UIGraphicsBeginPDFContextToData(data, pageFrame, nil)
    UIGraphicsBeginPDFPage()
    pageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())
    print("bounds: " + UIGraphicsGetPDFContextBounds().debugDescription)
    UIGraphicsEndPDFContext()

    return data as Data
}

This project is also on Github:
 https://github.com/starkindustries/PrintPDFTest

Troubleshooting Steps Taken

Dimensions: I tried playing around with the size of the PDF dimensions. This did not make a difference in the result.

Columns: I tried using multiple columns instead of just one. Same problem; no difference.

Tables: I tried using just one table instead of two. With one table and two cells, the bottom cell still gets cut off when text is centered; bottom cell does not get cut when text is left-aligned.

iPhones: I tried simulating on different iPhone devices (iPhone 6s, iPhone 8, iPad Pro). Same issue.

Div: If you use a div instead of a second table, the problem is magically fixed. But why does a div work and not a table?

App Notes

The top toolbar has two buttons: green and red. Green makes the text left-aligned. Red makes the text centered.

The bottom toolbar has five buttons: rewind, html, portrait, landscape, and fast forward. The rewind button reduces the main table's height by 10px. Fast forward increases the height by 10px. The html button shows the html view. Portrait and landscape show PDF's in their respective orientations.

Body:
I had many troubles with PDF rendering in order to keep the exact same aspect and size then my HTML file once transformed (mostly because of resolution translation problems).

The best and simpliest workaround that I found is to encapsulate the content in a container that exactly fit the height of the document.
You can use the media query to apply your css code only on the print result if you want to display your source html file.

table, th, td {
  border-collapse: collapse;
  border: 3px solid black;
  text-align: center;
}

table.main-table {
  width: 1012px;
  height: 515px;
  background-color: #f4f4f4;
}

table.bottom-table {
  width: 1012px;
}

@media print {
  .main-container{
    height:1100px;/* adjust the height to fit your PDF document*/
  }
}

<div class="main-container">
  <table class="main-table">
    <tr><td>Hello World.</td></tr>
  </table>
  <table class="bottom-table">
    <tr><td>This text gets cut off when centered. It does *not* get cut when left-aligned.</td></tr>
  </table>
 </div>


问:
Sum column based on another column in Pandas DataFrame
I have a pandas DataFrame like this:

```<code>>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333
</code>```

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

```<code>   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333
</code>```

Thanks for your help in advance!

答:
The code below works for your example:

```<code>df1 = df.groupby(["SINID"]).sum()
df1['EXTRA'] = df.groupby(["SINID"]).mean()['EXTRA']
</code>```

Result :

```<code>       MONTREGL  EXTRA
SINID
aaa        2242  400.0
bbb         235  500.0
ccc        5611  333.0
</code>```

Body:
I have a pandas DataFrame like this:

>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333

Thanks for your help in advance!

Body:
The code below works for your example:

df1 = df.groupby(["SINID"]).sum()
df1['EXTRA'] = df.groupby(["SINID"]).mean()['EXTRA']

Result :

       MONTREGL  EXTRA
SINID
aaa        2242  400.0
bbb         235  500.0
ccc        5611  333.0


问:
In what module is shapefile defined
I want to run this example. It fails on the first line:

```<code>$ python3
>>> import shapefile
ModuleNotFoundError: No module named 'shapefile'
</code>```

Apparently shapefile is not in the standard library. When I search in PyPi I get results, but in the first result no import shapefile is provided, so it's unclear if this will work for me.

Am I missing something here, and should I just try all matches from the PyPi search without any reasoning? I'm a bit lost here...

答:
To run import shapefile you need to install the pyshp library.

Need to do pip install pyshp and then run import shapefile

Title: In what module is shapefile defined

Body:
I want to run this example. It fails on the first line:

$ python3
>>> import shapefile
ModuleNotFoundError: No module named 'shapefile'

Apparently shapefile is not in the standard library. When I search in PyPi I get results, but in the first result no import shapefile is provided, so it's unclear if this will work for me.

Am I missing something here, and should I just try all matches from the PyPi search without any reasoning? I'm a bit lost here...


问:
java out of memory error-heap space
I'm developing web application in jsp/servlet,i had an issue with netbeans and Java. My program needs large data process. So I used -Xmx512m to increase the maximum heap size via

Tools -> Servers -> on the Platform tab there is a VM option below
  Java Platform.
  Then it works fine..

Now my issue is i'm building the WAR file, directly deployed and run in my another machine Tomcat for demo,
here i'm facing the same issue java out of memory error-heap space
 i also tried with

environment variable set   CATALINA_OPTS=-Xms512m -Xmx512m

this also didn't help me

how to resolve this issue?, Please point me to the right direction

答: Out of memory error can be result of big session-timeout number in Tomcat's web.xml. In that case many web sessions can take many system memory.</p>

Title: java out of memory error-heap space


问:
geom_bar changes behavior when variable is factor
Plotting a bar chart for a two-column data frame works just fine:

library(tidyverse)
tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
       .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L)) %>%
ggplot() +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")
```

<p><img src="https://i.stack.imgur.com/c88Mp.png" alt="Click me. I cannot embed images :("></p>

<p>However, when the variable is declared as a factor geom_bar produces non-sense results. What is going on in this particular case?</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)
tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
       .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L) %>% factor) %>%
ggplot() +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")
</code>```

答:
When the x variable is numeric, geom_bar calculates the proportion relative to all values of the x variable. When the x variable is categorical (either character or factor class), geom_bar calculates the proportion within each value of the x variable. You can override this behavior by adding a group aesthetic to force geom_bar to calculate the proportion relative to all x values. For example:

```<code>dat = tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
             .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L))

# .value is integer
ggplot(dat) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

# .value is factor
ggplot(dat %>% mutate(.value=factor(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

ggplot(dat %>% mutate(.value=factor(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group, group=.group), position="dodge")

# .value is character
ggplot(dat %>% mutate(.value=as.character(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

ggplot(dat %>% mutate(.value=as.character(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group, group=.group), position="dodge")
</code>```

geom_line behaves in a similar fashion when the x variable is categorical. For example:

```<code>set.seed(3)
dat = data.frame(x=rep(paste0(2010:2015, "-", substr(2011:2016,3,4)), 2),
                 y=cumsum(rnorm(12)),
                 group=rep(LETTERS[1:2], each=6))

ggplot(dat, aes(x=x, y=y, colour=group)) +
  geom_point() +
  geom_line()

ggplot(dat, aes(x=x, y=y, colour=group, group=group)) +
  geom_point() +
  geom_line()
</code>```

Body:
Plotting a bar chart for a two-column data frame works just fine:

library(tidyverse)
tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
       .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L)) %>%
ggplot() +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

However, when the variable is declared as a factor geom_bar produces non-sense results. What is going on in this particular case?

library(tidyverse)
tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
       .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L) %>% factor) %>%
ggplot() +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

Body:
When the x variable is numeric, geom_bar calculates the proportion relative to all values of the x variable. When the x variable is categorical (either character or factor class), geom_bar calculates the proportion within each value of the x variable. You can override this behavior by adding a group aesthetic to force geom_bar to calculate the proportion relative to all x values. For example:

dat = tibble(.group = c("A","B","A","B","B","A","A","A","A") %>% factor,
             .value = c( 1L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 1L))

# .value is integer
ggplot(dat) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

# .value is factor
ggplot(dat %>% mutate(.value=factor(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

ggplot(dat %>% mutate(.value=factor(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group, group=.group), position="dodge")

# .value is character
ggplot(dat %>% mutate(.value=as.character(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group), position="dodge")

ggplot(dat %>% mutate(.value=as.character(.value))) +
  geom_bar(aes(x=.value, y=..prop.., fill=.group, group=.group), position="dodge")

geom_line behaves in a similar fashion when the x variable is categorical. For example:

set.seed(3)
dat = data.frame(x=rep(paste0(2010:2015, "-", substr(2011:2016,3,4)), 2),
                 y=cumsum(rnorm(12)),
                 group=rep(LETTERS[1:2], each=6))

ggplot(dat, aes(x=x, y=y, colour=group)) +
  geom_point() +
  geom_line()

ggplot(dat, aes(x=x, y=y, colour=group, group=group)) +
  geom_point() +
  geom_line()


问:
jQuery and AJAX Loading
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

```<code>$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});
</code>```

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

答:
I would use something like this:</p>

```<code>var requestHandle;
function loadPage(url, vars) {
  //cancel pending
  if (requestHandle!=null)
      requestHandle.abort();

  //load page..
  requestHandle = $.get(url, vars, function(data) {
        $('#storycontainer').hide();
        $('#loading').remove();
        $('#storycontainer').hide(0).html(data).fadeIn(1000);
  });
}
</code>```

Title: jQuery and AJAX Loading

Body:
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

Body:
I would use something like this:

var requestHandle;
function loadPage(url, vars) {
  //cancel pending
  if (requestHandle!=null)
      requestHandle.abort();

  //load page..
  requestHandle = $.get(url, vars, function(data) {
        $('#storycontainer').hide();
        $('#loading').remove();
        $('#storycontainer').hide(0).html(data).fadeIn(1000);
  });
}


答:
I think the page you're looking at is maybe out of date.

First run pip install pyshp on the command line. Then import shapefile in the Python prompt.

This works for me on Python 3.5.6.

https://pypi.org/project/pyshp/

Title: In what module is shapefile defined


问:
Write to specific objects in json. Python
I want to create a program that loads a json file, reads it and then adds a
object to a list.

```<code>import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

with open("json.json", "w") as f:
    json.dump(newo, f)
</code>```

This is the python file I have been using.

```<code>{
    "cointiply": [
        {
            "balance" : "242537",
            "time": "28.05.2019"
        },
        {
            "balance": "246362",
            "time": "29.05.2019"
        }
    ]
}
</code>```

And that's the json file.

I now want the newo list to be inserted into the json list "cointiply".

Any idea how that could be done?
Because right now the "newo" list is deleting every think in the json file and then just inserted like the file would have been empty.

答:
You could use a temporary file, write your new data to it and then replace the two files, instead of opening the same file twice. Regarding the list - you need to use append in order to add your new data to the cointiply element:

from os import remove
from shutil import move
from tempfile import mkstemp

newo = {
    "balance": "1234",
    "time": "forever"
}

fh, abs_path = mkstemp()
file_path = "json.json"
with open(fh, "w") as newf, open(file_path, "r") as oldf:
    data = json.load(oldf)
    data["cointiply"].append(newo)
    json.dump(data, newf)
    # Remove original file
    remove(file_path)
    # Move new file
    move(abs_path, file_path)
```

Body:
I want to create a program that loads a json file, reads it and then adds a
object to a list.

import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

with open("json.json", "w") as f:
    json.dump(newo, f)

This is the python file I have been using.

{
    "cointiply": [
        {
            "balance" : "242537",
            "time": "28.05.2019"
        },
        {
            "balance": "246362",
            "time": "29.05.2019"
        }
    ]
}

And that's the json file.

I now want the newo list to be inserted into the json list "cointiply".

Any idea how that could be done?
Because right now the "newo" list is deleting every think in the json file and then just inserted like the file would have been empty.


问:
Map array values to collection of items
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

```<code>$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];
</code>```

The collection :

```<code> $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);
</code>```

The end result :

```<code>$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];
</code>```

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

答:
Thanks to @vivek_23 and @IndianCoding for giving me idea's I ended up with the following :
 I made a small edit to make sure the mapping and the items keys lined up.
 so you don't have to worry of misalignment and all in laravel collection !</p>

```<code>
$baseMap = collect($baseMap)->sortKeys();

$result = $items->map(function ($item) use ($baseMap) {

            return $baseMap->values()
                ->combine(
                    collect($item)->sortKeys()->intersectByKeys($baseMap)
                )
                ->all();
        });
</code>```

Title: Map array values to collection of items

Body:
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];

The collection :

 $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);

The end result :

$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

Body:
Thanks to @vivek_23 and @IndianCoding for giving me idea's I ended up with the following :
 I made a small edit to make sure the mapping and the items keys lined up.
 so you don't have to worry of misalignment and all in laravel collection !

$baseMap = collect($baseMap)->sortKeys();

$result = $items->map(function ($item) use ($baseMap) {

            return $baseMap->values()
                ->combine(
                    collect($item)->sortKeys()->intersectByKeys($baseMap)
                )
                ->all();
        });


问:
Groovy (SoapUI) choose which request are compatible with deployed API and use them
I want to write SoapUI test cases, which can be run on different versions of API. Before running test case, it needs to find which API versions are deployed. And then choose which request can run on those API versions. API versions are changed every day, so we need that SoapUI test cases can handle different versions.

I wrote simple script in Groovy, which checks deployed API version (major version) on servers and save them in the test suite properties. Also this script checks If we have requests for those versions. It fails when we don't have request for deployed version.

Test Suite Properties looks something like this:

I also have prepared requests for different versions. But now I need to make a Groovy script which will choose appropriate requests. Any idea which is easiest way to do that?

My idea was to make map (apiRequests) with API names as 'keys' and requests names as 'values'. Than use .each and every loop it will get version of that API from Test Suite Properties. I have made this:

API: onboarding, communication, customer-bill, etc.

Requests: Login, Logout, List of inbox messages, See bill history, Retrieve unpaid bills, etc.

```<code>def apiRequests=[
  'onboarding' : ['Login', 'Logout'],
  'customer-bill' : ['See bill history', 'Retrieve unpaid bills'],
  'communication' : ['List of inbox messages'],
]
apiRequests.each{k,v->
def apiVersion =  testRunner.testCase.testSuite.project.getTestSuiteByName("Independent functions").getTestCaseByName("Get API Version").getPropertyValue("$k")
log.info apiVersion     //returns version for api in that loop (e.g. '2' for onboarding api)

}
</code>```

And now I need to build complete request name (e.g. 'Login - v2'). I think that I can use something like this:

```<code>def finalRequest = (v + " -v " + apiVersion)
</code>```

But this doesn't work because I have more 'values' for one 'key'.

And then I need to disable other requests (different than all finalRequests) ->

Loop - disable: 'Login - v1', 'Login - v3', 'Logout - v1', Logout - v3'; enable: 'Login - v2', 'Logout - v2'

Loop - disable: 'See bill history - v2; enable: 'See bill history - v1'

Loop - etc.

I would like to make this groovy script universal for every test case. So it will run loop for every request stored in 'apiRequests' and If they exist in actual test case, then it choose them and disable others.

答:
This would work what are your looking for -

PS: I assume the properties are added on Project label scope. If you add the properties TestSuite/TestCase lable, change the context.expand('${#TestSuite/TestCase#....}')  accordingly.

```<code>testRunner.testCase.testSteps.each { k, v ->
  if(k.inspect().contains(context.expand('${#Project#onboarding}'))) {
     log.info k
     v.setDisabled(true)
   }
  if(k.inspect().contains(context.expand('${#Project#communication}'))) {
    log.info k
    v.setDisabled(true)
  }
  if(k.inspect().contains(context.expand('${#Project#customer-bill}'))) {
    log.info k
    v.setDisabled(true)
 }
}
return
</code>```

PS:
I would suggest to change the value of your property with adding v as version before the version number like you named your testStep name - Login - v1 , Login - v2 etc.
So the property would look like -

```<code>|Name          | Value |
|----------------------|
|onboarding    |  v2   |
|communication |  v3   |
|customer-bill |  v1   |
</code>```

At any case the above code ll work.

Body:
I want to write SoapUI test cases, which can be run on different versions of API. Before running test case, it needs to find which API versions are deployed. And then choose which request can run on those API versions. API versions are changed every day, so we need that SoapUI test cases can handle different versions.

I wrote simple script in Groovy, which checks deployed API version (major version) on servers and save them in the test suite properties. Also this script checks If we have requests for those versions. It fails when we don't have request for deployed version.

Test Suite Properties looks something like this:

I also have prepared requests for different versions. But now I need to make a Groovy script which will choose appropriate requests. Any idea which is easiest way to do that?

My idea was to make map (apiRequests) with API names as 'keys' and requests names as 'values'. Than use .each and every loop it will get version of that API from Test Suite Properties. I have made this:

API: onboarding, communication, customer-bill, etc.

Requests: Login, Logout, List of inbox messages, See bill history, Retrieve unpaid bills, etc.

def apiRequests=[
  'onboarding' : ['Login', 'Logout'],
  'customer-bill' : ['See bill history', 'Retrieve unpaid bills'],
  'communication' : ['List of inbox messages'],
]
apiRequests.each{k,v->
def apiVersion =  testRunner.testCase.testSuite.project.getTestSuiteByName("Independent functions").getTestCaseByName("Get API Version").getPropertyValue("$k")
log.info apiVersion     //returns version for api in that loop (e.g. '2' for onboarding api)

}

And now I need to build complete request name (e.g. 'Login - v2'). I think that I can use something like this:

def finalRequest = (v + " -v " + apiVersion)

But this doesn't work because I have more 'values' for one 'key'.

And then I need to disable other requests (different than all finalRequests) ->

Loop - disable: 'Login - v1', 'Login - v3', 'Logout - v1', Logout - v3'; enable: 'Login - v2', 'Logout - v2'

Loop - disable: 'See bill history - v2; enable: 'See bill history - v1'

Loop - etc.

I would like to make this groovy script universal for every test case. So it will run loop for every request stored in 'apiRequests' and If they exist in actual test case, then it choose them and disable others.

Body:
This would work what are your looking for -

PS: I assume the properties are added on Project label scope. If you add the properties TestSuite/TestCase lable, change the context.expand('${#TestSuite/TestCase#....}')  accordingly.

testRunner.testCase.testSteps.each { k, v ->
  if(k.inspect().contains(context.expand('${#Project#onboarding}'))) {
     log.info k
     v.setDisabled(true)
   }
  if(k.inspect().contains(context.expand('${#Project#communication}'))) {
    log.info k
    v.setDisabled(true)
  }
  if(k.inspect().contains(context.expand('${#Project#customer-bill}'))) {
    log.info k
    v.setDisabled(true)
 }
}
return

PS:
I would suggest to change the value of your property with adding v as version before the version number like you named your testStep name - Login - v1 , Login - v2 etc.
So the property would look like -

|Name          | Value |
|----------------------|
|onboarding    |  v2   |
|communication |  v3   |
|customer-bill |  v1   |

At any case the above code ll work.


问:
Selenium Grid - How to shutdown the node after execution?
I am trying to implement a solution that'd shutdown the node running inside a docker (Swarm) container after a test run.

I looked at docker remove command but cannot use the docker container rm command as the containers are at the service-task level

I looked at the /lifecycle-manager api but cannot get to the node from client, the docker stack is running through a nginx server and only one port(4444) gets exposed

Finally I looked at extended the grid node (DefaultRemoteProxy). Excuse my bad java code, this is my first stab at writing java code. With this, it looks like I can stop the node but it gets registered to the hub

How can i stop this re-registration process or start the node without it

My goal is to have a new container for every test and let the docker orchestration bring up a new container when the node is shutdown and container gets removed (docker api https://docs.docker.com/engine/api/v1.24/)

```<code>public class ExtendedProxy extends DefaultRemoteProxy implements TestSessionListener {

    public ExtendedProxy(RegistrationRequest request, GridRegistry registry) {
        super(request, registry);
    }

    @Override
    public void afterCommand(TestSession session, HttpServletRequest request, HttpServletResponse response) {
        RequestType type = SeleniumBasedRequest.createFromRequest(request, getRegistry()).extractRequestType();

        if(type == STOP_SESSION) {
            System.out.println("Going to Shutdown the Node");

           GridRegistry registry = getRegistry();
           registry.stop();
           registry.removeIfPresent(this);

        }
    }
}
</code>```

Hub

```<code>[DefaultGridRegistry.assignRequestToProxy] - Shutting down registry.
[DefaultGridRegistry.removeIfPresent] - Cleaning up stale test sessions on the unregistered node
[DefaultGridRegistry.add] - Registered a node
</code>```

Node

```<code>[ActiveSessions$1.onStop] - Removing session de04928d-7056-4b39-8137-27e9a0413024 (org.openqa.selenium.firefox.GeckoDriverService)
[SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://localhost:4444/grid/register
[SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use
</code>```

答:
I figured out the solution. I am answering my own question, hoping it'd benefit the community.

Start the node with the command line flag. This stops the auto registration thread from ever getting created.

```<code>registerCycle - 0
</code>```

And in your class that extends DefaultRemoteProxy, override the afterSession

```<code>@Override
public void afterSession(TestSession session) {
    totalSessionsCompleted++;

    GridRegistry gridRegistry = getRegistry();
    for(TestSlot slot : getTestSlots()) {
        gridRegistry.forceRelease(slot, SessionTerminationReason.PROXY_REREGISTRATION);
    }
    teardown();
    gridRegistry.removeIfPresent(this);
}
</code>```

When the client executed the driver.quit() method, the node de-registers with the hub.

Body:
I am trying to implement a solution that'd shutdown the node running inside a docker (Swarm) container after a test run.

I looked at docker remove command but cannot use the docker container rm command as the containers are at the service-task level

I looked at the /lifecycle-manager api but cannot get to the node from client, the docker stack is running through a nginx server and only one port(4444) gets exposed

Finally I looked at extended the grid node (DefaultRemoteProxy). Excuse my bad java code, this is my first stab at writing java code. With this, it looks like I can stop the node but it gets registered to the hub

How can i stop this re-registration process or start the node without it

My goal is to have a new container for every test and let the docker orchestration bring up a new container when the node is shutdown and container gets removed (docker api https://docs.docker.com/engine/api/v1.24/)

public class ExtendedProxy extends DefaultRemoteProxy implements TestSessionListener {

    public ExtendedProxy(RegistrationRequest request, GridRegistry registry) {
        super(request, registry);
    }

    @Override
    public void afterCommand(TestSession session, HttpServletRequest request, HttpServletResponse response) {
        RequestType type = SeleniumBasedRequest.createFromRequest(request, getRegistry()).extractRequestType();

        if(type == STOP_SESSION) {
            System.out.println("Going to Shutdown the Node");

           GridRegistry registry = getRegistry();
           registry.stop();
           registry.removeIfPresent(this);

        }
    }
}

Hub

[DefaultGridRegistry.assignRequestToProxy] - Shutting down registry.
[DefaultGridRegistry.removeIfPresent] - Cleaning up stale test sessions on the unregistered node
[DefaultGridRegistry.add] - Registered a node

Node

[ActiveSessions$1.onStop] - Removing session de04928d-7056-4b39-8137-27e9a0413024 (org.openqa.selenium.firefox.GeckoDriverService)
[SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://localhost:4444/grid/register
[SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use

Body:
I figured out the solution. I am answering my own question, hoping it'd benefit the community.

Start the node with the command line flag. This stops the auto registration thread from ever getting created.

registerCycle - 0

And in your class that extends DefaultRemoteProxy, override the afterSession

@Override
public void afterSession(TestSession session) {
    totalSessionsCompleted++;

    GridRegistry gridRegistry = getRegistry();
    for(TestSlot slot : getTestSlots()) {
        gridRegistry.forceRelease(slot, SessionTerminationReason.PROXY_REREGISTRATION);
    }
    teardown();
    gridRegistry.removeIfPresent(this);
}

When the client executed the driver.quit() method, the node de-registers with the hub.


问:
How to convert factor to date in R without getting NA?
I'm sorry I know this question has been asked thousand times, but I'm trying to convert my dates column which is in factor to date , but it gets NA !!

Here's my Data:

```<code>     'data.frame':  397774 obs. of  6 variables:
     $ ï..date      : Factor w/ 744 levels "2017-03-15","2017-03-16",..: 113 311 118 109 70 102 9 310 8 172 ...
     $ store        : int  43 43 43 43 43 43 43 43 43 43 ...
     $ item         : int  43 295 296 295 43 43 43 296 296 43 ...
     $ qty          : int  61 73 145 255 267 242 200 121 48 182 ...
     $ unit_price   : num  10.1 13.3 11.9 13.3 10.1 ...
     $ item_category: int  13 13 13 13 13 13 13 13 13 13 …
</code>```

Here's my code:

```<code>     df$ï..date <- as.Date(
     paste0("-1",as.character(df$ï..date)),
     format = "%b-%y-%d")
</code>```

Here's what I get:

```<code>  'data.frame': 397774 obs. of  6 variables:
  $ ï..date      : Date, format: NA NA NA ...
  $ store        : int  43 43 43 43 43 43 43 43 43 43 ...
  $ item         : int  43 295 296 295 43 43 43 296 296 43 ...
  $ qty          : int  61 73 145 255 267 242 200 121 48 182 ...
  $ unit_price   : num  10.1 13.3 11.9 13.3 10.1 ...
  $ item_category: int  13 13 13 13 13 13 13 13 13 13 …
</code>```

Any suggestion would be much appreciated, thank you.

答:
There are several problems here:

the dates shown are not in the format of the format string shown.  They are in the format yyyy-mm-dd (or in terms of percent codes %Y-%m-%d), which is the default, so there is no need to specify any format at all

the dates already have year, month and day so there is no need to paste anything onto them

as.Date has a factor method. There is no need to convert them to character.

Try this:

```<code>x <- factor(c("2017-03-15","2017-03-16"))
as.Date(x)
## [1] "2017-03-15" "2017-03-16"
</code>```

Body:
I'm sorry I know this question has been asked thousand times, but I'm trying to convert my dates column which is in factor to date , but it gets NA !!

Here's my Data:

     'data.frame':  397774 obs. of  6 variables:
     $ ï..date      : Factor w/ 744 levels "2017-03-15","2017-03-16",..: 113 311 118 109 70 102 9 310 8 172 ...
     $ store        : int  43 43 43 43 43 43 43 43 43 43 ...
     $ item         : int  43 295 296 295 43 43 43 296 296 43 ...
     $ qty          : int  61 73 145 255 267 242 200 121 48 182 ...
     $ unit_price   : num  10.1 13.3 11.9 13.3 10.1 ...
     $ item_category: int  13 13 13 13 13 13 13 13 13 13 …

Here's my code:

     df$ï..date <- as.Date(
     paste0("-1",as.character(df$ï..date)),
     format = "%b-%y-%d")

Here's what I get:

  'data.frame': 397774 obs. of  6 variables:
  $ ï..date      : Date, format: NA NA NA ...
  $ store        : int  43 43 43 43 43 43 43 43 43 43 ...
  $ item         : int  43 295 296 295 43 43 43 296 296 43 ...
  $ qty          : int  61 73 145 255 267 242 200 121 48 182 ...
  $ unit_price   : num  10.1 13.3 11.9 13.3 10.1 ...
  $ item_category: int  13 13 13 13 13 13 13 13 13 13 …

Any suggestion would be much appreciated, thank you.

Body:
There are several problems here:

the dates shown are not in the format of the format string shown.  They are in the format yyyy-mm-dd (or in terms of percent codes %Y-%m-%d), which is the default, so there is no need to specify any format at all

the dates already have year, month and day so there is no need to paste anything onto them

as.Date has a factor method. There is no need to convert them to character.

Try this:

x <- factor(c("2017-03-15","2017-03-16"))
as.Date(x)
## [1] "2017-03-15" "2017-03-16"


问:
Spring Data MongoDB and allowDiskUse
I have a query like this:

```<code>db.tqaP.aggregate([
            {$match : { $and: [
                                {"eventUTCDate" : {
                                                    $gte : '01-10-2014'
                                                  }
                                },
                    {"eventUTCDate" : {
                                                    $lt : '31-10-2014'
                                                  }
                                },
                                {"mpTransactionId":{
                                                    $exists: true
                                                   }
                                },
                                {testMode : false},
                                {eventID : {
                                            $in : [
                                                    230, // ContentDiscoveredEvent
                                                    204, // ContentSLAStartEvent
                                                    211, // ContentProcessedEndEvent
                                                    255, // ContentValidationStatusEvent
                                                    256, // ContentErrorEvent
                                                    231, // ContentAnalyzedEvent
                                                    240, // ContentTranscodeStartEvent
                                                    241, // ContentTranscodeEndEvent
                                                    252  // AbortJobEvent
                                                    //205, 207
                                                  ]
                                            }
                                }
                        ]}},
          {$project :
                        {
                            _id:0,
                            event : {
                                eventID                 : "$eventID",
                                eventUTCDate            : "$eventUTCDate",
                                processState            : "$processState",
                                jobInstanceId           : "$jobInstanceId",
                                mpTransactionId         : "$mpTransactionId",
                                eventUID                : "$eventUID",
                                contextJobInstanceId    : "$context.jobInstanceId",
                                contextValidationStatus : "$context.validationStatus",
                                metaUpdateOnly          : "$metaUpdateOnly",
                                errorCode               : "$errorCode",
                                transcodingProfileName  : "$transcodingProfileName",
                                contextAssetId          : "$context.assetId"
                            }
                        }
          },
          // Creating the hash map <mpTransactionId, listOfAssociatedEvents>
          {$group   :     {
                            "_id"               : "$event.mpTransactionId",
                            "chainOfEvents"     : {$addToSet : "$event"}
                          },
          },
          // Sorting by chainOfEvents.eventUTCDate
          {$unwind      : "$chainOfEvents"},
          {$sort        : {
                            "chainOfEvents.eventUTCDate":1
                          }
          },
          {$group       : {
                            _id :"$_id",
                            chainOfEvents: {
                                                $push:"$chainOfEvents"
                                           }
                          }
          }
       ])
</code>```

that runs over 1.2 millions records and dies. The error message is

```<code>assert: command failed: {
        "errmsg" : "exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDi
skUse:true to opt in.",
        "code" : 16819,
        "ok" : 0
} : aggregate failed
</code>```

I fix this by adding between the last closing brackets (the square and the round one)

```<code>,{allowDiskUsage: true}
</code>```

Now I am trying to express the same thing using Spring Data for MongoDB and my Java code looks like:

```<code>MatchOperation match = Aggregation.match( new Criteria()
                            .andOperator(
                                        Criteria.where("eventUTCDate").gte(startDateAsString),
                                        Criteria.where("eventUTCDate").lt(endDateAsString))
                            .and("mpTransactionId").exists(true)
                            .and("testMode").is(false)
                            .and("eventID").in(230, 204, 211, 255, 256, 231, 240, 241, 252) );

    ProjectionOperation projection = Aggregation.project().and("event").
                                nested(bind("eventID", "eventID").
                                        and("eventUTCDate", "eventUTCDate").
                                        and("processState", "processState").
                                        and("jobInstanceId", "jobInstanceId").
                                        and("mpTransactionId", "mpTransactionId").
                                        and("eventUID", "eventUID").
                                        and("contextJobInstanceId", "context.jobInstanceId").
                                        and("contextValidationStatus", "context.validationStatus").
                                        and("metaUpdateOnly", "metaUpdateOnly").
                                        and("errorCode", "errorCode").
                                        and("transcodingProfileName", "transcodingProfileName").
                                        and("contextAssetId", "context.assetId"));

    GroupOperation group = Aggregation.group("event.mpTransactionId").addToSet("event").as("chainOfEvents");

    UnwindOperation unwind = Aggregation.unwind("chainOfEvents");

    SortOperation sort = Aggregation.sort(Sort.Direction.ASC, "chainOfEvents.eventUTCDate");

    GroupOperation groupAgain = Aggregation.group("_id").push("chainOfEvents").as("eventsList");

    Aggregation agg = newAggregation(Event.class, match,  projection, group, unwind, sort, groupAgain).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
    AggregationResults<EventsChain> results = mongoOps.aggregate(agg, "tqaP", EventsChain.class);
</code>```

but I receive a set of empty results. This query was working for a smaller set of data.
I just added

```<code>.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
</code>```

in order to adapt to the size of the data. Can anybody tell if I am using incorrectly?

I am using MongoDB 2.6.4 and Spring-Data-MongoDB version 1.6.1-RELEASE.

答:
Here is a working solution 2.1.8 using MongoTemplate class helper.

```<code>AggregationOptions options = AggregationOptions.builder().allowDiskUse(true).build();
List<AggregationOperation> aggs = Arrays.asList(m1, p1, g1);
        mongoTemplate.aggregate(Aggregation.newAggregation(aggs).withOptions(options), inputCollectionName, Document.class);
</code>```

Title: Spring Data MongoDB and allowDiskUse

Body:
I have a query like this:

db.tqaP.aggregate([
            {$match : { $and: [
                                {"eventUTCDate" : {
                                                    $gte : '01-10-2014'
                                                  }
                                },
                    {"eventUTCDate" : {
                                                    $lt : '31-10-2014'
                                                  }
                                },
                                {"mpTransactionId":{
                                                    $exists: true
                                                   }
                                },
                                {testMode : false},
                                {eventID : {
                                            $in : [
                                                    230, // ContentDiscoveredEvent
                                                    204, // ContentSLAStartEvent
                                                    211, // ContentProcessedEndEvent
                                                    255, // ContentValidationStatusEvent
                                                    256, // ContentErrorEvent
                                                    231, // ContentAnalyzedEvent
                                                    240, // ContentTranscodeStartEvent
                                                    241, // ContentTranscodeEndEvent
                                                    252  // AbortJobEvent
                                                    //205, 207
                                                  ]
                                            }
                                }
                        ]}},
          {$project :
                        {
                            _id:0,
                            event : {
                                eventID                 : "$eventID",
                                eventUTCDate            : "$eventUTCDate",
                                processState            : "$processState",
                                jobInstanceId           : "$jobInstanceId",
                                mpTransactionId         : "$mpTransactionId",
                                eventUID                : "$eventUID",
                                contextJobInstanceId    : "$context.jobInstanceId",
                                contextValidationStatus : "$context.validationStatus",
                                metaUpdateOnly          : "$metaUpdateOnly",
                                errorCode               : "$errorCode",
                                transcodingProfileName  : "$transcodingProfileName",
                                contextAssetId          : "$context.assetId"
                            }
                        }
          },
          // Creating the hash map <mpTransactionId, listOfAssociatedEvents>
          {$group   :     {
                            "_id"               : "$event.mpTransactionId",
                            "chainOfEvents"     : {$addToSet : "$event"}
                          },
          },
          // Sorting by chainOfEvents.eventUTCDate
          {$unwind      : "$chainOfEvents"},
          {$sort        : {
                            "chainOfEvents.eventUTCDate":1
                          }
          },
          {$group       : {
                            _id :"$_id",
                            chainOfEvents: {
                                                $push:"$chainOfEvents"
                                           }
                          }
          }
       ])

that runs over 1.2 millions records and dies. The error message is

assert: command failed: {
        "errmsg" : "exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDi
skUse:true to opt in.",
        "code" : 16819,
        "ok" : 0
} : aggregate failed

I fix this by adding between the last closing brackets (the square and the round one)

,{allowDiskUsage: true}

Now I am trying to express the same thing using Spring Data for MongoDB and my Java code looks like:

MatchOperation match = Aggregation.match( new Criteria()
                            .andOperator(
                                        Criteria.where("eventUTCDate").gte(startDateAsString),
                                        Criteria.where("eventUTCDate").lt(endDateAsString))
                            .and("mpTransactionId").exists(true)
                            .and("testMode").is(false)
                            .and("eventID").in(230, 204, 211, 255, 256, 231, 240, 241, 252) );

    ProjectionOperation projection = Aggregation.project().and("event").
                                nested(bind("eventID", "eventID").
                                        and("eventUTCDate", "eventUTCDate").
                                        and("processState", "processState").
                                        and("jobInstanceId", "jobInstanceId").
                                        and("mpTransactionId", "mpTransactionId").
                                        and("eventUID", "eventUID").
                                        and("contextJobInstanceId", "context.jobInstanceId").
                                        and("contextValidationStatus", "context.validationStatus").
                                        and("metaUpdateOnly", "metaUpdateOnly").
                                        and("errorCode", "errorCode").
                                        and("transcodingProfileName", "transcodingProfileName").
                                        and("contextAssetId", "context.assetId"));

    GroupOperation group = Aggregation.group("event.mpTransactionId").addToSet("event").as("chainOfEvents");

    UnwindOperation unwind = Aggregation.unwind("chainOfEvents");

    SortOperation sort = Aggregation.sort(Sort.Direction.ASC, "chainOfEvents.eventUTCDate");

    GroupOperation groupAgain = Aggregation.group("_id").push("chainOfEvents").as("eventsList");

    Aggregation agg = newAggregation(Event.class, match,  projection, group, unwind, sort, groupAgain).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
    AggregationResults<EventsChain> results = mongoOps.aggregate(agg, "tqaP", EventsChain.class);

but I receive a set of empty results. This query was working for a smaller set of data.
I just added

.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());

in order to adapt to the size of the data. Can anybody tell if I am using incorrectly?

I am using MongoDB 2.6.4 and Spring-Data-MongoDB version 1.6.1-RELEASE.

Body:
Here is a working solution 2.1.8 using MongoTemplate class helper.

AggregationOptions options = AggregationOptions.builder().allowDiskUse(true).build();
List<AggregationOperation> aggs = Arrays.asList(m1, p1, g1);
        mongoTemplate.aggregate(Aggregation.newAggregation(aggs).withOptions(options), inputCollectionName, Document.class);


答:
You are getting the NA because your format is wrong

```<code>> as.Date("2017-03-15", format = "%b-%y-%d")
[1] NA
</code>```

The %Y represents the year, %m the month and %d the day.

```<code>> as.Date("2017-03-15", format = "%Y-%m-%d")
[1] "2017-03-15"
</code>```

Title: How to convert factor to date in R without getting NA?

Body:
You are getting the NA because your format is wrong

> as.Date("2017-03-15", format = "%b-%y-%d")
[1] NA

The %Y represents the year, %m the month and %d the day.

> as.Date("2017-03-15", format = "%Y-%m-%d")
[1] "2017-03-15"


问:
Tortoise GIT - show changes created in branch after merge
Is it possible to show only commits and changes created in a specific branch? If I do this before merge it works. If I merge master branch to this branch (to make it actual) then I see commits and merges made in master branch. Is there some way how to filter it?</p>

答:
You can do this using git bash (packaged tool with git), it's an alternative.
This is a more effective solution for this question:

type the command:

```<code>git log --graph [branch]
</code>```

type this too:

```<code>git diff ..master path/to/file
</code>```

Credits to the author @lukman of this answer to a similar question here on SO.

Body:
You can do this using git bash (packaged tool with git), it's an alternative.
This is a more effective solution for this question:

type the command:

git log --graph [branch]

type this too:

git diff ..master path/to/file

Credits to the author @lukman of this answer to a similar question here on SO.