问:
How to convert an .eps file into a .png in Python 3.6
With Python turtle I'm trying to save the canvas as a png. I've researched it and found a way to save it as an eps file without any modules, but I'm finding it hard to convert the eps file into a png.

Is there a way to convert eps to png without downloading another module? If not can someone tell me more about ImageMagick, because I have looked at it, but I'm confused how to use it? I've also seen it being linked to linux and is it outdated?

If not converting eps to png, is there a even simpler way to save the canvas as a png?

Btw I have seen this, but I don't understand it :/
How to convert a .eps file to a high quality 1024x1024 .jpg?

答:
I've been having problems with ImageMagick having had its security policy changed so it can't interact with Ghostscript. (for good reason... but it's questionable that it doesn't allow you to locally override the default policy so web apps can be protected while whitelisted uses can still work.)

For anyone else slamming into convert: not authorized, here's how to invoke Ghostscript directly:

gs -dSAFER -dEPSCrop -r300 -sDEVICE=jpeg -o image.png image.eps
```

<ul>
<li><code>-dSAFER</code> puts Ghostscript into sandboxed mode so you can interpret untrusted Postscript. (It should be default, but backwards compatibility.)</li>
<li><code>-dEPSCrop</code> asks Ghostscript to not pad it out to the size of a printable page. (details)</li>
<li>ImageMagick's <code>-density 300</code> becomes <code>-r300</code> when it invokes Ghostscript. (details)</li>
<li><code>-sDEVICE</code> is how you set the output format (See the Devices section of the manual for other choices.)</li>
<li><code>-o</code> is a shorthand for <code>-dBATCH -dNOPAUSE -sOutputFile=</code> (details)</li>
</ul>

<p>You could then use ImageMagick's <code>mogrify</code> command to resize it to fit exact pixel dimensions:</p>

<pre class="lang-sh prettyprint-override"><code>mogrify -resize 1024x1024 image.png
</code>```

(mogrify is like convert but replaces the input file rather than writing to a new file.)

UPDATE: In hindsight, I should have checked whether Pillow supported EPS before posting that first answer.

The native Python solution would be to use Pillow's support for invoking Ghostscript (like ImageMagick in that respect, but with a native Python API).

However, Pillow's docs don't explain how they arrive at a size in pixels and only take an optional multiplier (scale) for the default size rather than an absolute DPI value.

If that doesn't bother you, and you've got both Pillow and Ghostscript installed, here's how to do it without ImageMagick:

#!/usr/bin/env python3

from PIL import Image

TARGET_BOUNDS = (1024, 1024)

# Load the EPS at 10 times whatever size Pillow thinks it should be
# (Experimentaton suggests that scale=1 means 72 DPI but that would
#  make 600 DPI scale=8⅓ and Pillow requires an integer)
pic = Image.open('image.eps')
pic.load(scale=10)

# Ensure scaling can anti-alias by converting 1-bit or paletted images
if pic.mode in ('P', '1'):
    pic = pic.convert("RGB")

# Calculate the new size, preserving the aspect ratio
ratio = min(TARGET_BOUNDS[0] / pic.size[0],
            TARGET_BOUNDS[1] / pic.size[1])
new_size = (int(pic.size[0] * ratio), int(pic.size[1] * ratio))

# Resize to fit the target size
pic = pic.resize(new_size, Image.ANTIALIAS)

# Save to PNG
pic.save("image.png")

```

Body:
I've been having problems with ImageMagick having had its security policy changed so it can't interact with Ghostscript. (for good reason... but it's questionable that it doesn't allow you to locally override the default policy so web apps can be protected while whitelisted uses can still work.)

For anyone else slamming into convert: not authorized, here's how to invoke Ghostscript directly:

gs -dSAFER -dEPSCrop -r300 -sDEVICE=jpeg -o image.png image.eps

-dSAFER puts Ghostscript into sandboxed mode so you can interpret untrusted Postscript. (It should be default, but backwards compatibility.)

-dEPSCrop asks Ghostscript to not pad it out to the size of a printable page. (details)

ImageMagick's -density 300 becomes -r300 when it invokes Ghostscript. (details)

-sDEVICE is how you set the output format (See the Devices section of the manual for other choices.)

-o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile= (details)

You could then use ImageMagick's mogrify command to resize it to fit exact pixel dimensions:

mogrify -resize 1024x1024 image.png

(mogrify is like convert but replaces the input file rather than writing to a new file.)

UPDATE: In hindsight, I should have checked whether Pillow supported EPS before posting that first answer.

The native Python solution would be to use Pillow's support for invoking Ghostscript (like ImageMagick in that respect, but with a native Python API).

However, Pillow's docs don't explain how they arrive at a size in pixels and only take an optional multiplier (scale) for the default size rather than an absolute DPI value.

If that doesn't bother you, and you've got both Pillow and Ghostscript installed, here's how to do it without ImageMagick:

#!/usr/bin/env python3

from PIL import Image

TARGET_BOUNDS = (1024, 1024)

# Load the EPS at 10 times whatever size Pillow thinks it should be
# (Experimentaton suggests that scale=1 means 72 DPI but that would
#  make 600 DPI scale=8⅓ and Pillow requires an integer)
pic = Image.open('image.eps')
pic.load(scale=10)

# Ensure scaling can anti-alias by converting 1-bit or paletted images
if pic.mode in ('P', '1'):
    pic = pic.convert("RGB")

# Calculate the new size, preserving the aspect ratio
ratio = min(TARGET_BOUNDS[0] / pic.size[0],
            TARGET_BOUNDS[1] / pic.size[1])
new_size = (int(pic.size[0] * ratio), int(pic.size[1] * ratio))

# Resize to fit the target size
pic = pic.resize(new_size, Image.ANTIALIAS)

# Save to PNG
pic.save("image.png")


来源: stackexchange

问:
How to access a private object within a private object in Java?
I am trying to access an object within an object here. Below are the three classes. I simplified this that it makes the same error as in the full program.
This is the main class.

```<code>import java.util.Scanner;
public class TestMain
{
    public static void main (String[] args)
    {
        createStudent();
    }

    public static Student createStudent()
    {
        Student another = new Student();
        another.depart(101,"CS");
        return another;
    }
}
</code>```

The second one,

```<code>public class Student
{
    private int sid;
    private String sname;
    private Department department;

    public int getSid()
    {
        return sid;
    }
    public String getSname()
    {
        return sname;
    }
    public void depart(int departid, String departname)
    {
        department.setDid(departid);
        department.setDname(departname);
    }

    public void setSid(int stusid)
    {
        this.sid = stusid;
    }
    public void setSname(String stusname)
    {
        this.sname = stusname;
    }

}
</code>```

The third one,

```<code>public class Department
{
    private int did;
    private String dname;

    public int getDid()
    {
        return did;
    }
    public String getDname()
    {
        return dname;
    }

    public void setDid(int deptdid)
    {
        this.did = deptdid;
    }
    public void setDname(String deptdname)
    {
        this.dname = deptdname;
    }
}
</code>```

No matter what I do, this program returns a run time error,

```<code>Exception in thread "main" java.lang.NullPointerException
    at Student.depart(Student.java:17)
    at TestMain.createStudent(TestMain.java:13)
    at TestMain.main(TestMain.java:7)
</code>```

What is NullPointerException and how to avoid this? Please help me.

答:
in your department class in depart method you don't create instance of department and department field is null use this instead:
department = new Department();</p>

```<code>public void depart(int departid, String departname){
   department = new Department();
   department.setDid(departid);
   department.setDname(departname);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to access an object within an object here. Below are the three classes. I simplified this that it makes the same error as in the full program.
This is the main class.

import java.util.Scanner;
public class TestMain
{
    public static void main (String[] args)
    {
        createStudent();
    }

    public static Student createStudent()
    {
        Student another = new Student();
        another.depart(101,"CS");
        return another;
    }
}

The second one,

public class Student
{
    private int sid;
    private String sname;
    private Department department;

    public int getSid()
    {
        return sid;
    }
    public String getSname()
    {
        return sname;
    }
    public void depart(int departid, String departname)
    {
        department.setDid(departid);
        department.setDname(departname);
    }

    public void setSid(int stusid)
    {
        this.sid = stusid;
    }
    public void setSname(String stusname)
    {
        this.sname = stusname;
    }

}

The third one,

public class Department
{
    private int did;
    private String dname;

    public int getDid()
    {
        return did;
    }
    public String getDname()
    {
        return dname;
    }

    public void setDid(int deptdid)
    {
        this.did = deptdid;
    }
    public void setDname(String deptdname)
    {
        this.dname = deptdname;
    }
}

No matter what I do, this program returns a run time error,

Exception in thread "main" java.lang.NullPointerException
    at Student.depart(Student.java:17)
    at TestMain.createStudent(TestMain.java:13)
    at TestMain.main(TestMain.java:7)

What is NullPointerException and how to avoid this? Please help me.

Body:
in your department class in depart method you don't create instance of department and department field is null use this instead:
department = new Department();

public void depart(int departid, String departname){
   department = new Department();
   department.setDid(departid);
   department.setDname(departname);
}


问:
How to check if dropdown is toggle on and add class
I want to check if the dropdown menu is toggled. If the menu has a class: mega-toggle-on then add a class to id #submenu-new.

Here is my code:

```<code>  <div id="submenu-new" class="submenu-balk active" style="padding-top: 226px;">

      </div>

<script type="text/javascript">
if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).is( ".mega-toggle-on" ) ) {

 jQuery("#submenu-new").addClass("active");
alert('ss');

}
</script>
</code>```

Example where you can find the mega-toggle-on class

答:
You can use hasClass in jQuery

```<code>if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) {
jQuery("#submenu-new").addClass("active");
} else {
jQuery("#submenu-new").removeClass("active");}
</code>```

Body:
I want to check if the dropdown menu is toggled. If the menu has a class: mega-toggle-on then add a class to id #submenu-new.

Here is my code:

Example where you can find the mega-toggle-on class

Body:
You can use hasClass in jQuery

if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) {
jQuery("#submenu-new").addClass("active");
} else {
jQuery("#submenu-new").removeClass("active");}


问:
C++ converting double to long
I used pow(double base, double exponent) in my program, how can I convert the answer to long data type?

答:
I was looking for an actual conversion from double to long.

After some research, casting actually does the trick:

```<code>double myDouble = 12.345;
long myTruncatedLong = (long) myDouble;
</code>```

myTruncatedLong will be 12.

ContentLicense: CC BY-SA 3.0

Title: C++ converting double to long

Body:
I was looking for an actual conversion from double to long.

After some research, casting actually does the trick:

double myDouble = 12.345;
long myTruncatedLong = (long) myDouble;

myTruncatedLong will be 12.


问:
Changing scale legend label after creation in ggplot2
Let's say I have a function like this one:

```<code>library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                         high = "red",
                         mid = "white",
                         midpoint = 0,
                         limit = c(-1, 1),
                         space = "Lab",
                         name = "Default label")
}
</code>```

We can then call it on some data:

```<code>#default
mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")
</code>```

But what if we want another label for the color scale without changing the gradient settings? One cannot just use labs():

```<code>mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  labs(color = "new label")
</code>```

This does not change anything since labs() apparently cannot override the scale_color_gradient2() in the function.

We can overwrite the scale, but this resets the color scheme:

```<code>mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  scale_color_gradient2("new label")
</code>```

I feel like this should be possible, either by specifying that ggplot2 should only update the label parameter, or by using ggplot2::ggplot_build() to directly change the label parameter only, and then rebuild the plot. However I can't find the label value for the color scale in the object. Too hard to search, but it should be there somewhere!

答:
The simplest is to add an extra argument to your scatterplot function, namely ...
If you don't add name, your legend name will default to you color variable name.

library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z, ...) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                          high = "red",
                          mid = "white",
                          midpoint = 0,
                          limit = c(-1, 1),
                          space = "Lab", ...) #note those three guys here
}

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")
```

<p><img src="https://i.imgur.com/4tXEFrj.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>
mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z", name = 'new_label')
</code>```

Created on 2020-02-16 by the reprex package (v0.3.0)

Body:
Let's say I have a function like this one:

library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                         high = "red",
                         mid = "white",
                         midpoint = 0,
                         limit = c(-1, 1),
                         space = "Lab",
                         name = "Default label")
}

We can then call it on some data:

#default
mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")

But what if we want another label for the color scale without changing the gradient settings? One cannot just use labs():

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  labs(color = "new label")

This does not change anything since labs() apparently cannot override the scale_color_gradient2() in the function.

We can overwrite the scale, but this resets the color scheme:

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  scale_color_gradient2("new label")

I feel like this should be possible, either by specifying that ggplot2 should only update the label parameter, or by using ggplot2::ggplot_build() to directly change the label parameter only, and then rebuild the plot. However I can't find the label value for the color scale in the object. Too hard to search, but it should be there somewhere!

Body:
The simplest is to add an extra argument to your scatterplot function, namely ...
If you don't add name, your legend name will default to you color variable name.

library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z, ...) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                          high = "red",
                          mid = "white",
                          midpoint = 0,
                          limit = c(-1, 1),
                          space = "Lab", ...) #note those three guys here
}

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z", name = 'new_label')

Created on 2020-02-16 by the reprex package (v0.3.0)


问:
How to correctly set default text with GTK 3
I've tried everything but I'm so lost. Here is what I need to achieve:

```<code>    backupDirs = gtk_entry_new();
    gtk_grid_attach(GTK_GRID(grid), backupDirs, 1, 1, 1, 1);
    gtk_entry_set_placeholder_text(*backupDirs,"Placeholder text here");
</code>```

I don't understand how to correctly pass the string into the function.

答:
You need to pass a pointer to a GtkEntry as the first argument of gtk_entry_set_placeholder_text. You didn't show your declaration of backupDirs, but since gtk_entry_new returns a GtkWidget *, I assume it's something like

```<code>GtkWidget *backupDirs = gtk_entry_new()
</code>```

So you need to cast it to GtkEntry *, using the built-in macros:

```<code>gtk_entry_set_placeholder_text(GTK_ENTRY(backupDirs), "Placeholder text here");
</code>```

Body:
I've tried everything but I'm so lost. Here is what I need to achieve:

    backupDirs = gtk_entry_new();
    gtk_grid_attach(GTK_GRID(grid), backupDirs, 1, 1, 1, 1);
    gtk_entry_set_placeholder_text(*backupDirs,"Placeholder text here");

I don't understand how to correctly pass the string into the function.

Body:
You need to pass a pointer to a GtkEntry as the first argument of gtk_entry_set_placeholder_text. You didn't show your declaration of backupDirs, but since gtk_entry_new returns a GtkWidget *, I assume it's something like

GtkWidget *backupDirs = gtk_entry_new()

So you need to cast it to GtkEntry *, using the built-in macros:

gtk_entry_set_placeholder_text(GTK_ENTRY(backupDirs), "Placeholder text here");


问:
JoinColumn Hibernate / API
I'm having the following problem: I want to simply join the table Markets (main) and Telephones, but I'm facing some problems while doing this with annotations.

I simply want to use the Comercio.id as the corresponding foreign key from Telefone.fk_id, but it doesn't recognize it. I also would like to ask if it's needed to create an Repository Interface for both classes.

EDIT. Also, how would look a POST req for such an example?

Comercio.java

```<code>@Entity
@Table(name = "comercio")
public class Comercio {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String cnpj;
    private String endereco;

    @OneToMany(targetEntity = Telefone.class , mappedBy = "comercio", fetch = FetchType.LAZY)
    private List<Telefone> telefones;
    private String email;
</code>```

Telefone.java

```<code>@Entity
@Table(name = "telefone")
public class Telefone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long telefone_id;

    @ManyToOne
    @JoinColumn(name="fk_id", referencedColumnName = "id")
    private Comercio comercio;
    private String telefone;
</code>```

The answer I get:

```<code>{
      "nome" : "Americanas",
      "cnpj" : "000",
      "endereco" : "SQN 112",
      "telefones" : [ ],
      "email" : "contato@americanas.com",
      "comercio_id" : 1
}
</code>```

Console:

```<code>Hibernate: select comercio0_.id as id1_0_, comercio0_.cnpj as cnpj2_0_, comercio0_.email as email3_0_, comercio0_.endereco as endereco4_0_, comercio0_.nome as nome5_0_ from comercio comercio0_
Hibernate: select telefones0_.fk_id as fk_id3_1_0_, telefones0_.telefone_id as telefone1_1_0_, telefones0_.telefone_id as telefone1_1_1_, telefones0_.fk_id as fk_id3_1_1_, telefones0_.telefone as telefone2_1_1_ from telefone telefones0_ where telefones0_.fk_id=**?**
</code>```

Apreciate any help.

答:
I would suggest that telephone is not an Entity in its own right: you will never want to query for a telefone and it only exists as part of a Comercio.

It could then be an Embeddable rather than an entity however as it only has one property - the number - then you can simplify to the below and map it as a collection of Strings. There is then no need for a Telefone class.

```<code>@Entity
@Table(name = "comercio")
public class Comercio {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String cnpj;
    private String endereco;

    @ELementCollection
    @CollectionTable(name = "comercio_telefone",
                joinColumns=@JoinColumn(name="comercio_id"))
    private List<String> telefones;

    private String email;
}
</code>```

Title: JoinColumn Hibernate / API

Body:
I'm having the following problem: I want to simply join the table Markets (main) and Telephones, but I'm facing some problems while doing this with annotations.

I simply want to use the Comercio.id as the corresponding foreign key from Telefone.fk_id, but it doesn't recognize it. I also would like to ask if it's needed to create an Repository Interface for both classes.

EDIT. Also, how would look a POST req for such an example?

Comercio.java

@Entity
@Table(name = "comercio")
public class Comercio {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String cnpj;
    private String endereco;

    @OneToMany(targetEntity = Telefone.class , mappedBy = "comercio", fetch = FetchType.LAZY)
    private List<Telefone> telefones;
    private String email;

Telefone.java

@Entity
@Table(name = "telefone")
public class Telefone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long telefone_id;

    @ManyToOne
    @JoinColumn(name="fk_id", referencedColumnName = "id")
    private Comercio comercio;
    private String telefone;

The answer I get:

{
      "nome" : "Americanas",
      "cnpj" : "000",
      "endereco" : "SQN 112",
      "telefones" : [ ],
      "email" : "contato@americanas.com",
      "comercio_id" : 1
}

Console:

Hibernate: select comercio0_.id as id1_0_, comercio0_.cnpj as cnpj2_0_, comercio0_.email as email3_0_, comercio0_.endereco as endereco4_0_, comercio0_.nome as nome5_0_ from comercio comercio0_
Hibernate: select telefones0_.fk_id as fk_id3_1_0_, telefones0_.telefone_id as telefone1_1_0_, telefones0_.telefone_id as telefone1_1_1_, telefones0_.fk_id as fk_id3_1_1_, telefones0_.telefone as telefone2_1_1_ from telefone telefones0_ where telefones0_.fk_id=**?**

Apreciate any help.

Body:
I would suggest that telephone is not an Entity in its own right: you will never want to query for a telefone and it only exists as part of a Comercio.

It could then be an Embeddable rather than an entity however as it only has one property - the number - then you can simplify to the below and map it as a collection of Strings. There is then no need for a Telefone class.

@Entity
@Table(name = "comercio")
public class Comercio {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String cnpj;
    private String endereco;

    @ELementCollection
    @CollectionTable(name = "comercio_telefone",
                joinColumns=@JoinColumn(name="comercio_id"))
    private List<String> telefones;

    private String email;
}


问:
jQuery get anchor value
I am trying to get the value of a clicked anchor but I am not sure which anchor is being clicked or how to latch onto it with jquery.  I have a document.ready function

```<code>$(document).ready(function () {
var ActiveBlogStats = $('#BlogSelectList');
$('#BlogSelectList').click(function () {
    alert(ActiveBlogStats.text)
}); })
</code>```

Here is the id that it is working on

```<code><ul class="submenu" id="BlogSelectList">
  <xsl:for-each select="oohru/user/oohblog">
    <li>
      <a>
        <xsl:attribute name="href">#<xsl:value-of select="normalize-space(blogid)"/></xsl:attribute>
        <xsl:value-of select="oohblogurl"/>
      </a>
    </li>
  </xsl:for-each>
<li><a href="AddNewBlog.aspx">+ Create a new oohblog</a></li>
</ul>
</code>```

How can I get the href of the actual anchor being clicked?  I don't see how to make a document.ready even for items that don't exist until after the document is ready.
I suppose I could get the # value from the URL since when they click one it will update the URL but I would rather get it directly from the click.

答:
You could get the href with something like this:

```<code>$("#BlogSelectList").delegate("a", "click", function() {

    var href = $(this).attr("href");
    alert(href);

});
</code>```

And if you needed to stop it from redirecting, you could do:

```<code>$("#BlogSelectList").delegate("a", "click", function(e) {

    e.preventDefault();

    var href = $(this).attr("href");
    alert(href);

});
</code>```

Title: jQuery get anchor value

Body:
I am trying to get the value of a clicked anchor but I am not sure which anchor is being clicked or how to latch onto it with jquery.  I have a document.ready function

$(document).ready(function () {
var ActiveBlogStats = $('#BlogSelectList');
$('#BlogSelectList').click(function () {
    alert(ActiveBlogStats.text)
}); })

Here is the id that it is working on

  <xsl:for-each select="oohru/user/oohblog">

        <xsl:attribute name="href">#<xsl:value-of select="normalize-space(blogid)"/></xsl:attribute>
        <xsl:value-of select="oohblogurl"/>

  </xsl:for-each>

+ Create a new oohblog

How can I get the href of the actual anchor being clicked?  I don't see how to make a document.ready even for items that don't exist until after the document is ready.
I suppose I could get the # value from the URL since when they click one it will update the URL but I would rather get it directly from the click.

Body:
You could get the href with something like this:

$("#BlogSelectList").delegate("a", "click", function() {

    var href = $(this).attr("href");
    alert(href);

});

And if you needed to stop it from redirecting, you could do:

$("#BlogSelectList").delegate("a", "click", function(e) {

    e.preventDefault();

    var href = $(this).attr("href");
    alert(href);

});


答:
The exception is occurring because you did't create the object in the depart method. You can use this:</p>

```<code>public void depart(int departid, String departname)
    {
        department = new Department();
        department.setDid(departid);
        department.setDname(departname);
    }
</code>```

Title: How to access a private object within a private object in Java?

Body:
The exception is occurring because you did't create the object in the depart method. You can use this:

public void depart(int departid, String departname)
    {
        department = new Department();
        department.setDid(departid);
        department.setDname(departname);
    }


问:
OOP : Inherit only to have a more accurate name - Good Practice?
Just a litle question about good practices in Object oriented programming.

Let's Image that I have a class like this (pseudo-code) :

```<code>class Activity{
   construct(duration){
           this.duration = duration
      }
}
</code>```

Now I want to define 2 types of Activities : "workTask" and "freeTime". I can imagine 3 possibilities :

Add a property to each instances of my class 'Activity'. Something like "Activity::type"

Inherite twice of the class "Activity" without changing anything exept the type of those classes. One would be "WorkTask" and the other "FreeTime"

Delegate the type assignement. The easier way might be by creating 2 arrays "workTasks" and "freeTimes" and store activities in those arrays.

I actually prefer the last choice but I don't know if it's the recommended way to do that stuff. Are those 3 patterns acceptable (even the second one that is in my opinion the weirder) ? Is there any other good ways to do it ?

答:
Best practices calls for (1) "Add a property to each instances of my class 'Activity'. Something like 'Activity::type'"

This will allow you to:

Put all activities in the same array and still know which are which.

Change the activity type at runtime.

Separate an array of activities into two arrays.

Neither of the other two options is as flexible.

Body:
Just a litle question about good practices in Object oriented programming.

Let's Image that I have a class like this (pseudo-code) :

class Activity{
   construct(duration){
           this.duration = duration
      }
}

Now I want to define 2 types of Activities : "workTask" and "freeTime". I can imagine 3 possibilities :

Add a property to each instances of my class 'Activity'. Something like "Activity::type"

Inherite twice of the class "Activity" without changing anything exept the type of those classes. One would be "WorkTask" and the other "FreeTime"

Delegate the type assignement. The easier way might be by creating 2 arrays "workTasks" and "freeTimes" and store activities in those arrays.

I actually prefer the last choice but I don't know if it's the recommended way to do that stuff. Are those 3 patterns acceptable (even the second one that is in my opinion the weirder) ? Is there any other good ways to do it ?


问:
SQL Select rows that have higher timestamp value
On a PostgreSQL Server i've a table like this below :

```<code>+------+------+------------------+
| Code |  kind|    timestamp     |
+------+------+------------------+
|  1   |  I   | 16-05-2011 09:17 |
|  1   |  O   | 16-05-2011 09:47 |
|  2   |  I   | 16-05-2011 09:37 |
|  3   |  I   | 16-05-2011 11:26 |
|  3   |  O   | 16-05-2011 12:11 |
|  3   |  I   | 16-05-2011 13:23 |
+------+------+------------------+
</code>```

This table represent IN and OUT of person in a pool with relative timestamp, and i want to know the person in the pool at a given moment.

Is there a way to retrieve The row of kind 'I' that not have a corresponding 'O' ?
can i do it with a single Query ?

The code represent the person code ...

答: Assuming Code is a person, you could convert kind I and O to numbers +1 and -1, then select SUM(Code*kind), grouped by Code, having the sum being nonzero.

Body:
On a PostgreSQL Server i've a table like this below :

+------+------+------------------+
| Code |  kind|    timestamp     |
+------+------+------------------+
|  1   |  I   | 16-05-2011 09:17 |
|  1   |  O   | 16-05-2011 09:47 |
|  2   |  I   | 16-05-2011 09:37 |
|  3   |  I   | 16-05-2011 11:26 |
|  3   |  O   | 16-05-2011 12:11 |
|  3   |  I   | 16-05-2011 13:23 |
+------+------+------------------+

This table represent IN and OUT of person in a pool with relative timestamp, and i want to know the person in the pool at a given moment.

Is there a way to retrieve The row of kind 'I' that not have a corresponding 'O' ?
can i do it with a single Query ?

The code represent the person code ...


问:
How can I ignore bodies while recording in wiremock
I would like to record requests in such a way that the mappings end up with no bodyPatterns tag. In other words I want recorded mappings to be matched only based on path and regardless of body. Is it possible?

答:
Although not exactly the removal of the tag, the contents of it can be influenced by setting the extractBodyCriteria to 1 byte. In the documentation on Record and Playback there is also a java example:

```<code>  "extractBodyCriteria" : {
    "textSizeThreshold" : "1",
    "binarySizeThreshold" : "1"
  },
</code>```

Body:
Although not exactly the removal of the tag, the contents of it can be influenced by setting the extractBodyCriteria to 1 byte. In the documentation on Record and Playback there is also a java example:

  "extractBodyCriteria" : {
    "textSizeThreshold" : "1",
    "binarySizeThreshold" : "1"
  },


问:
Deploy AWS state machine stage specific
I am new to serverless framework. I want to deploy my state machine for dev env only not for other env. How can I deploy it stage-specific?. I have tried serverless-plugin-ifelse for deployment but it is not working in the case of state machines. My serverless.yml looks like</p>

```<code>serverlessIfElse:
    - If: '"${self:custom.currentStage}" == "beta"'
      Exclude:
        - stepFunctions.stateMachines
 stepFunctions:
  stateMachines:
    pruneIndices:
      ${file(./handlers/prune-indexes/prune-indexes.yml)}
</code>```

答:
If you can provide a name for your state machine, add the stage you are deploying to as a part of that state machine name. I usually name my resources with multiple variables to namespace them better, so for example you could use:

${self:service}-myStateMachineName-${opt:stage, 'dev'}

In this way your statemachine will always be unique per service even if you re-use it on the same account and if you pass a stage during deployment such as serverless deploy --stage mystage it will be unique or default dev if a stage is not specified.

Title: Deploy AWS state machine stage specific

Body:
I am new to serverless framework. I want to deploy my state machine for dev env only not for other env. How can I deploy it stage-specific?. I have tried serverless-plugin-ifelse for deployment but it is not working in the case of state machines. My serverless.yml looks like

serverlessIfElse:
    - If: '"${self:custom.currentStage}" == "beta"'
      Exclude:
        - stepFunctions.stateMachines
 stepFunctions:
  stateMachines:
    pruneIndices:
      ${file(./handlers/prune-indexes/prune-indexes.yml)}


问:
Read a file, count delimiters and output line number with mismatched delimiter
I have a file named: test_file.txt. The second line has 4 pipe delimiters and all other lines except 2nd line has 3 pipe delimiters.
I just want to output line 2 since it has one more delimiter than other lines.</p>

```<code>$colCnt = "C:\test.txt"
[int]$LastSplitCount = $Null
Get-Content $colCnt | ?{$_} | Select -Skip 1 | %{if($LastSplitCount -and !

($_.split("|").Count -eq $LastSplitCount))

{"Process stopped at line number $($_.psobject.Properties.value[5]) for column count mis-match.";break}

elseif(!$LastSplitCount){$LastSplitCount = $_.split("|").Count}}
</code>```

答:
If your text file looks anything like this:

```<code>blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using two  |delimiters
</code>```

The the following code should output the lines with more (or less) than 3 | delimiters:

```<code>$line = 0
switch -Regex -File "C:\test.txt" {
    '^(?:[^|]*\|){3}[^|]*$' { $line++ }   # this line is OK, just increase the line counter
    default { "Bad delimiter count in line {0}: '{1}'" -f ++$line, $_ }
}
</code>```

Output:

```<code>Bad delimiter count in line 2: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 4: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 5: 'blah|using two  |delimiters'
</code>```

Regex details:

```
^           Assert position at the beginning of the string
(?:         Match the regular expression below
   [^|]     Match any character that is NOT a “|”
      *     Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \|       Match the character “|” literally
){3}        Exactly 3 times
[^|]        Match any character that is NOT a “|”
   *        Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$           Assert position at the end of the string (or before the line break at the end of the string, if any)
```

Body:
I have a file named: test_file.txt. The second line has 4 pipe delimiters and all other lines except 2nd line has 3 pipe delimiters.
I just want to output line 2 since it has one more delimiter than other lines.

$colCnt = "C:\test.txt"
[int]$LastSplitCount = $Null
Get-Content $colCnt | ?{$_} | Select -Skip 1 | %{if($LastSplitCount -and !

($_.split("|").Count -eq $LastSplitCount))

{"Process stopped at line number $($_.psobject.Properties.value[5]) for column count mis-match.";break}

elseif(!$LastSplitCount){$LastSplitCount = $_.split("|").Count}}

Body:
If your text file looks anything like this:

blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using two  |delimiters

The the following code should output the lines with more (or less) than 3 | delimiters:

$line = 0
switch -Regex -File "C:\test.txt" {
    '^(?:[^|]*\|){3}[^|]*$' { $line++ }   # this line is OK, just increase the line counter
    default { "Bad delimiter count in line {0}: '{1}'" -f ++$line, $_ }
}

Output:

Bad delimiter count in line 2: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 4: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 5: 'blah|using two  |delimiters'

Regex details:

^           Assert position at the beginning of the string
(?:         Match the regular expression below
   [^|]     Match any character that is NOT a “|”
      *     Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \|       Match the character “|” literally
){3}        Exactly 3 times
[^|]        Match any character that is NOT a “|”
   *        Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$           Assert position at the end of the string (or before the line break at the end of the string, if any)


问:
Removing a substring from a char array without using any libraries in C
I am a computer science first year student and our teachers gave a binary pattern search task to do. We have to remove a substring from a string without using any libraries and built-ins like(memmove or strstr). Our only hint is that its something to do with '\0'. I don't see how we are going to achive this because as i know the null character only ends a string not removes it. And given an unknown input it gets even harder to get around. I need help about the usage of null character. EDIT: Oh and also we are not allowed to create new arrays. EDIT2: The problem is much more complicated if you are here for the solution read the comments under this thread and the marked solution's also.</p>

答:
C strings are "null terminated" which means they are considered to end wherever a null (written '\0' in C) appears.

If I start with the string "Stack Overflow" and I overwrite the space with '\0', I now have the string "Stack".  The storage for "Overflow" still exists, but it is not part of the string according to C functions like strlen(), printf() etc.  In fact, if I hold a pointer to the "O" part of the original string, it will be just as if there are two strings: "Stack" and "Overflow", and you can still use both of them.

It's like if I come to where you live and I build a huge wall across the road just before your house.  The road is now shortened, and people on my side of it won't know you are there.


答:
The answer to this kind of question is always "It depends". There are many factors to consider when choosing which approach to use.

If you need to check the type of activities a lot, then 3 is a bad idea, as you need to loop through arrays in order to find out whether a particular activity is a WorkTask or FreeTime.

If WorkTask and FreeTime differs in behaviour/data (e.g. WorkTime could have an extra taskName field or something), then you should use 2. Also note that even if they are the same now, it doesn't mean it will stay this way forever.

Both 1 and 3 will allow you to accidentally assign WorkTasks to variables that are supposed to store FreeTime. This might not be such a big problem in a dynamically-typed language, since you can do this with 2 anyway.

Don't forget that there are a fourth way: Composition

Title: OOP : Inherit only to have a more accurate name - Good Practice?


问:
ASP.NET MVC 3 how to implement many to many relationship in Create View
I have quite a complex class that has three one-to-many relationships and two many-to-many relationships with other classes. What I would like to do is to enable the user to fill all the details one by one - in one step or even better in multiple steps (wizard).

My class is called PeriodicTask - user has to select one Server object (which represents SQL Server instance ) and depending on the selection I need to present the user with the ability to select which databases he wants to use ( the best option would be to use checkboxes). I don't really know how to achieve this.

I would start with creating an action that returns JSON with databases for the selected server. It'll be invoked by jQuery. So far so good, but what to do then?

Should I add <input type="checkbox"> to the form for every database or maybe create another form and post to some other action? How to parse that when the form is submitted? Can I split it somehow into smaller steps ? HTTP is stateless so I somehow need to pass or remember the data that was previously submitted - how?

PS> I'm using Entity Framework here, so part of the class hierarchy is as follows:

答:
I would look at creating helpers for each of the options that would be self contained, they could maintain the state themselves.

Another cool option would be to create a tree view, where the root level is your server and next level is database. Load the data into a ViewModel so that it can be used as the data source for a tree view.  It seems like a nice interface for what you have.

Believe it or not the Microsoft site is a great place to start when learning MVC

http://www.asp.net/mvc


问:
Exchange data.table columns with most prevalent value of columns
I have data

```<code>test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)
</code>```

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

```<code>test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)
</code>```

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

```<code>test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]
</code>```

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
</code>```

答:
@EmreKiratli is very close to what I would do:

```<code>test[ , c(
  list(a = unique(a)),
  lapply(.SD, function(x) as(tail(names(sort(table(x))), 1L), class(x)))
), .SDcols = !'a']
</code>```

The as(., class(x)) part is because names in R are always character, so we have to convert back to the original class of x.

You might like this better in magrittr form since it's many nested functions:

```<code>library(magrittr)
test[ , c(
  list(a = unique(a)),
  lapply(.SD, function(x) {
    table(x) %>% sort %>% names %>% tail(1L) %>% as(class(x))
  })
), .SDcols = !'a']
</code>```

Body:
I have data

test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))

Body:
@EmreKiratli is very close to what I would do:

test[ , c(
  list(a = unique(a)),
  lapply(.SD, function(x) as(tail(names(sort(table(x))), 1L), class(x)))
), .SDcols = !'a']

The as(., class(x)) part is because names in R are always character, so we have to convert back to the original class of x.

You might like this better in magrittr form since it's many nested functions:

library(magrittr)
test[ , c(
  list(a = unique(a)),
  lapply(.SD, function(x) {
    table(x) %>% sort %>% names %>% tail(1L) %>% as(class(x))
  })
), .SDcols = !'a']


问:
How to hook into onClick method inside a method using frida
I want to change behaviour of onClick method by hooking with frida.
The code I used is

```<code>Java.perform(function() {
    console.log("[*] START...")
    var mClass = Java.use("sg.vantagepoint.uncrackable1.MainActivity")
    mClass.a.onClick.implementation=function() {
        console.log("[*] Clicked ")
    }
})
</code>```

iam getting error

```<code>TypeError: cannot write property 'implementation' of undefined
    at [anon] (../../../frida-gum/bindings/gumjs/duktape.c:57636)
    at /uncrackable1.js:6
    at frida/node_modules/frida-java-bridge/lib/vm.js:11
    at E (frida/node_modules/frida-java-bridge/index.js:346)
    at frida/node_modules/frida-java-bridge/index.js:298
    at frida/node_modules/frida-java-bridge/lib/vm.js:11
    at frida/node_modules/frida-java-bridge/index.js:278
    at /uncrackable1.js:11
</code>```

source code is

```<code>    private void a(String str) {
        AlertDialog create = new AlertDialog.Builder(this).create();
        create.setTitle(str);
        create.setMessage("This is unacceptable. The app is now going to exit.");
        create.setButton(-3, "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                System.exit(0);
            }
        });
</code>```

答:
You are trying to hook the wrong class - most likely because you are using Jadx for decompiling the wrong settings and no knowledge on Java classes.

If you are using Jadx for decompiling the APK file make sure to disable the setting Inline anonymous classes to see the real class name a method belongs to.

The Method onClick() belongs to the anonymous inner class created by new DialogInterface.OnClickListener() and not to sg.vantagepoint.uncrackable1.MainActivity - hence you are trying to hook the wrong class. The method a(String) it is used in is totally irrelevant for hooking. Anonymous inner classes have their own class name based on the outer class appended by $ and a number.
Therefore the correct class name may be sg.vantagepoint.uncrackable1.MainActivity$1 or sg.vantagepoint.uncrackable1.MainActivity$2, depending on how many other anonymous inner classes are present.

Additionally something like mClass.a.onClick is not possible, as there is no method inside a method (a is a method and onClick is a method).

In the end you may end up with the following frida code:

```<code>Java.perform(function() {
    console.log("[*] START...")
    var mClass = Java.use("sg.vantagepoint.uncrackable1.MainActivity$1")
    mClass.onClick.implementation=function() {
        console.log("[*] Clicked ")
    }
})
</code>```

Body:
I want to change behaviour of onClick method by hooking with frida.
The code I used is

Java.perform(function() {
    console.log("[*] START...")
    var mClass = Java.use("sg.vantagepoint.uncrackable1.MainActivity")
    mClass.a.onClick.implementation=function() {
        console.log("[*] Clicked ")
    }
})

iam getting error

TypeError: cannot write property 'implementation' of undefined
    at [anon] (../../../frida-gum/bindings/gumjs/duktape.c:57636)
    at /uncrackable1.js:6
    at frida/node_modules/frida-java-bridge/lib/vm.js:11
    at E (frida/node_modules/frida-java-bridge/index.js:346)
    at frida/node_modules/frida-java-bridge/index.js:298
    at frida/node_modules/frida-java-bridge/lib/vm.js:11
    at frida/node_modules/frida-java-bridge/index.js:278
    at /uncrackable1.js:11

source code is

    private void a(String str) {
        AlertDialog create = new AlertDialog.Builder(this).create();
        create.setTitle(str);
        create.setMessage("This is unacceptable. The app is now going to exit.");
        create.setButton(-3, "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                System.exit(0);
            }
        });

Body:
You are trying to hook the wrong class - most likely because you are using Jadx for decompiling the wrong settings and no knowledge on Java classes.

If you are using Jadx for decompiling the APK file make sure to disable the setting Inline anonymous classes to see the real class name a method belongs to.

The Method onClick() belongs to the anonymous inner class created by new DialogInterface.OnClickListener() and not to sg.vantagepoint.uncrackable1.MainActivity - hence you are trying to hook the wrong class. The method a(String) it is used in is totally irrelevant for hooking. Anonymous inner classes have their own class name based on the outer class appended by $ and a number.
Therefore the correct class name may be sg.vantagepoint.uncrackable1.MainActivity$1 or sg.vantagepoint.uncrackable1.MainActivity$2, depending on how many other anonymous inner classes are present.

Additionally something like mClass.a.onClick is not possible, as there is no method inside a method (a is a method and onClick is a method).

In the end you may end up with the following frida code:

Java.perform(function() {
    console.log("[*] START...")
    var mClass = Java.use("sg.vantagepoint.uncrackable1.MainActivity$1")
    mClass.onClick.implementation=function() {
        console.log("[*] Clicked ")
    }
})


问:
TypeError: Cannot read property 'location' of undefined (jest)
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}
```

<p>// App.test.js</p>

<pre class="lang-js prettyprint-override"><code>import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
</code>```

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
```

Could you please tell me how I can fix this? Thanks.

答:
Just move your jest.mock declaration to the top of the file and it should work:

```<code>import App from './App';

jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
}));

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
</code>```

Body:
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}

// App.test.js

import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

Could you please tell me how I can fix this? Thanks.

Body:
Just move your jest.mock declaration to the top of the file and it should work:

import App from './App';

jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
}));

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});


问:
Seemingly Random Delay in queries
This is a follow up to this issue I posted a while ago.

I have the following code:

```<code>SET work_mem = '16MB';
SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id
WHERE       r.schedule_id = 10
ORDER BY    r.resource_id, s.start_date
</code>```

When I run EXPLAIN (ANALYZE, BUFFERS) I get the following:

```<code>Sort  (cost=3724.02..3724.29 rows=105 width=89) (actual time=245.802..247.573 rows=22302 loops=1)
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6692kB
  Buffers: shared hit=198702 read=5993 written=612
  ->  Nested Loop  (cost=703.76..3720.50 rows=105 width=89) (actual time=1.898..164.741 rows=22302 loops=1)
        Buffers: shared hit=198702 read=5993 written=612
        ->  Hash Join  (cost=703.34..3558.54 rows=105 width=101) (actual time=1.815..11.259 rows=22302 loops=1)
              Hash Cond: (s.usage_id = r.id)
              Buffers: shared hit=3 read=397 written=2
              ->  Bitmap Heap Scan on rm_o_resource_usage_instance_splits_new s  (cost=690.61..3486.58 rows=22477 width=69) (actual time=1.782..5.820 rows=22302 loops=1)
                    Recheck Cond: (solution = 10)
                    Heap Blocks: exact=319
                    Buffers: shared hit=2 read=396 written=2
                    ->  Bitmap Index Scan on rm_o_resource_usage_instance_splits_new_solution_idx  (cost=0.00..685.00 rows=22477 width=0) (actual time=1.609..1.609 rows=22302 loops=1)
                          Index Cond: (solution = 10)
                          Buffers: shared hit=2 read=77
              ->  Hash  (cost=12.66..12.66 rows=5 width=48) (actual time=0.023..0.023 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=1 read=1
                    ->  Bitmap Heap Scan on rm_o_resource_usage r  (cost=4.19..12.66 rows=5 width=48) (actual time=0.020..0.020 rows=1 loops=1)
                          Recheck Cond: (schedule_id = 10)
                          Heap Blocks: exact=1
                          Buffers: shared hit=1 read=1
                          ->  Bitmap Index Scan on rm_o_resource_usage_sched  (cost=0.00..4.19 rows=5 width=0) (actual time=0.017..0.017 rows=1 loops=1)
                                Index Cond: (schedule_id = 10)
                                Buffers: shared read=1
        ->  Index Scan using scheduledactivities_activity_index_idx on scheduledactivities sa  (cost=0.42..1.53 rows=1 width=16) (actual time=0.004..0.007 rows=1 loops=22302)
              Index Cond: (activity_index = s.activity_index)
              Filter: (solution_id = 10)
              Rows Removed by Filter: 5
              Buffers: shared hit=198699 read=5596 written=610
Planning time: 7.070 ms
Execution time: 248.691 ms
</code>```

Every time I run EXPLAIN, I get roughly the same results. The Execution Time is always between 170ms and 250ms, which, to me is perfectly fine. However, when this query is run through a C++ project (using PQexec(conn, query) where conn is a dedicated connection, and query is the above query), the time it takes seems to vary widely. In general, the query is very quick, and you don't notice a delay. The problem is, that on occasion, this query will take 2 to 3 minutes to complete.

If I open the pgadmin, and have a look at the "server activity" for the database, there's about 30 or so connections, mostly sitting at "idle". The above query's connection is marked as "active", and will stay as "active" for several minutes.

I am at a loss of why it randomly takes several minutes to complete the same query, with no change in data in the DB either. I have tried increasing the work_mem which didn't make any difference (nor did I really expect it to). Any help or suggestions would be greatly appreciated.

There isn't any more specific tags, but I'm currently using Postgres 10.11, but it's also been an issue on other versions of 10.x. System is a Xeon quad-core @ 3.4Ghz, with SSD and 24GB of memory.

Per jjanes's suggestion, I put in the auto_explain. Eventually go this output:

```<code>duration: 128057.373 ms
plan:
Query Text: SET work_mem = '32MB';SELECT        s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset FROM     rm_o_resource_usage_instance_splits_new s INNER JOIN    rm_o_resource_usage r ON s.usage_id = r.id INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id WHERE      r.schedule_id = 12642 ORDER BY   r.resource_id, s.start_date
Sort  (cost=14.36..14.37 rows=1 width=98) (actual time=128042.083..128043.287 rows=21899 loops=1)
  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6585kB
  Buffers: shared hit=21198435 read=388 dirtied=119
  ->  Nested Loop  (cost=0.85..14.35 rows=1 width=98) (actual time=4.995..127958.935 rows=21899 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        Buffers: shared hit=21198435 read=388 dirtied=119
        ->  Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=22102 read=388 dirtied=119
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12642)
                    Buffers: shared hit=203 read=388 dirtied=119
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.29 rows=1 width=57) (actual time=0.002..0.002 rows=1 loops=21899)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12642)
                    Rows Removed by Filter: 26
                    Buffers: shared hit=21899
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)
              Buffers: shared hit=21176333",,,,,,,,,""
</code>```

EDIT: Full definitions of the tables are below:

```<code>CREATE TABLE public.rm_o_resource_usage_instance_splits_new
(
    start_time integer NOT NULL,
    end_time integer NOT NULL,
    resources jsonb NOT NULL,
    activity_index integer NOT NULL,
    usage_id bigint NOT NULL,
    start_date text COLLATE pg_catalog."default" NOT NULL,
    end_date text COLLATE pg_catalog."default" NOT NULL,
    solution bigint NOT NULL,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_pkey PRIMARY KEY (start_time, activity_index, usage_id),
    CONSTRAINT rm_o_resource_usage_instance_splits_new_solution_fkey FOREIGN KEY (solution)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_usage_id_fkey FOREIGN KEY (usage_id)
        REFERENCES public.rm_o_resource_usage (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_activity_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_solution_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (solution ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_usage_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (usage_id ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

```<code>CREATE TABLE public.rm_o_resource_usage
(
    id bigint NOT NULL DEFAULT nextval('rm_o_resource_usage_id_seq'::regclass),
    schedule_id bigint NOT NULL,
    resource_id text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT rm_o_resource_usage_pkey PRIMARY KEY (id),
    CONSTRAINT rm_o_resource_usage_schedule_id_fkey FOREIGN KEY (schedule_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_idx
    ON public.rm_o_resource_usage USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_sched
    ON public.rm_o_resource_usage USING btree
    (schedule_id ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

```<code>CREATE TABLE public.scheduledactivities
(
    id bigint NOT NULL DEFAULT nextval('scheduledactivities_id_seq'::regclass),
    solution_id bigint NOT NULL,
    activity_id text COLLATE pg_catalog."default" NOT NULL,
    sequence_index integer,
    startminute integer,
    finishminute integer,
    issue text COLLATE pg_catalog."default",
    activity_index integer NOT NULL,
    is_objective boolean NOT NULL,
    usedresourceset integer DEFAULT '-1'::integer,
    start timestamp without time zone,
    finish timestamp without time zone,
    is_ore boolean,
    is_ignored boolean,
    CONSTRAINT scheduled_activities_pkey PRIMARY KEY (id),
    CONSTRAINT scheduledactivities_solution_id_fkey FOREIGN KEY (solution_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX scheduled_activities_activity_id_idx
    ON public.scheduledactivities USING btree
    (activity_id COLLATE pg_catalog."default" ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_id_idx
    ON public.scheduledactivities USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_idx
    ON public.scheduledactivities USING btree
    (solution_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduledactivities_activity_index_idx
    ON public.scheduledactivities USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;
</code>```

EDIT: Additional output from auto_explain after adding index on scheduledactivities (solution_id, activity_index)

```<code>  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6283kB
  Buffers: shared hit=20159117 read=375 dirtied=190
  ->  Nested Loop  (cost=0.85..10.76 rows=1 width=100) (actual time=5.518..122489.627 rows=20761 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 668815615
        Buffers: shared hit=20159117 read=375 dirtied=190
        ->  Nested Loop  (cost=0.42..5.80 rows=1 width=112) (actual time=0.057..217.563 rows=20761 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=20947 read=375 dirtied=190
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.44 rows=1 width=69) (actual time=0.049..17.622 rows=20761 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12644)
                    Buffers: shared hit=186 read=375 dirtied=190
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.35 rows=1 width=59) (actual time=0.002..0.002 rows=1 loops=20761)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12644)
                    Rows Removed by Filter: 22
                    Buffers: shared hit=20761
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.94 rows=1 width=16) (actual time=0.007..4.654 rows=32216 loops=20761)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12644)
              Buffers: shared hit=20138170",,,,,,,,,""
</code>```

The easiest way to reproduce the issue is to add more values to the three tables. I didn't delete any, only did a few thousand INSERTs.

答:
The SQL statement of the fast plan is using WHERE   r.schedule_id = 10 and returns about 22000 rows (with estimated 105).
The SQL statement of the slow plan is using WHERE   r.schedule_id = 12642 and returns about 21000 rows (with estimated only 1).

The slow plan is using nested loops instead of hash joins: maybe because there is a bad estimation for joins: estimated rows is 1 but actual rows is 21899.
For example in this step:

```<code>Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)
</code>```

If data does not change there is maybe a statistic issue (skew data) for some columns.

Title: Seemingly Random Delay in queries

Body:
This is a follow up to this issue I posted a while ago.

I have the following code:

SET work_mem = '16MB';
SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id
WHERE       r.schedule_id = 10
ORDER BY    r.resource_id, s.start_date

When I run EXPLAIN (ANALYZE, BUFFERS) I get the following:

Sort  (cost=3724.02..3724.29 rows=105 width=89) (actual time=245.802..247.573 rows=22302 loops=1)
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6692kB
  Buffers: shared hit=198702 read=5993 written=612
  ->  Nested Loop  (cost=703.76..3720.50 rows=105 width=89) (actual time=1.898..164.741 rows=22302 loops=1)
        Buffers: shared hit=198702 read=5993 written=612
        ->  Hash Join  (cost=703.34..3558.54 rows=105 width=101) (actual time=1.815..11.259 rows=22302 loops=1)
              Hash Cond: (s.usage_id = r.id)
              Buffers: shared hit=3 read=397 written=2
              ->  Bitmap Heap Scan on rm_o_resource_usage_instance_splits_new s  (cost=690.61..3486.58 rows=22477 width=69) (actual time=1.782..5.820 rows=22302 loops=1)
                    Recheck Cond: (solution = 10)
                    Heap Blocks: exact=319
                    Buffers: shared hit=2 read=396 written=2
                    ->  Bitmap Index Scan on rm_o_resource_usage_instance_splits_new_solution_idx  (cost=0.00..685.00 rows=22477 width=0) (actual time=1.609..1.609 rows=22302 loops=1)
                          Index Cond: (solution = 10)
                          Buffers: shared hit=2 read=77
              ->  Hash  (cost=12.66..12.66 rows=5 width=48) (actual time=0.023..0.023 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    Buffers: shared hit=1 read=1
                    ->  Bitmap Heap Scan on rm_o_resource_usage r  (cost=4.19..12.66 rows=5 width=48) (actual time=0.020..0.020 rows=1 loops=1)
                          Recheck Cond: (schedule_id = 10)
                          Heap Blocks: exact=1
                          Buffers: shared hit=1 read=1
                          ->  Bitmap Index Scan on rm_o_resource_usage_sched  (cost=0.00..4.19 rows=5 width=0) (actual time=0.017..0.017 rows=1 loops=1)
                                Index Cond: (schedule_id = 10)
                                Buffers: shared read=1
        ->  Index Scan using scheduledactivities_activity_index_idx on scheduledactivities sa  (cost=0.42..1.53 rows=1 width=16) (actual time=0.004..0.007 rows=1 loops=22302)
              Index Cond: (activity_index = s.activity_index)
              Filter: (solution_id = 10)
              Rows Removed by Filter: 5
              Buffers: shared hit=198699 read=5596 written=610
Planning time: 7.070 ms
Execution time: 248.691 ms

Every time I run EXPLAIN, I get roughly the same results. The Execution Time is always between 170ms and 250ms, which, to me is perfectly fine. However, when this query is run through a C++ project (using PQexec(conn, query) where conn is a dedicated connection, and query is the above query), the time it takes seems to vary widely. In general, the query is very quick, and you don't notice a delay. The problem is, that on occasion, this query will take 2 to 3 minutes to complete.

If I open the pgadmin, and have a look at the "server activity" for the database, there's about 30 or so connections, mostly sitting at "idle". The above query's connection is marked as "active", and will stay as "active" for several minutes.

I am at a loss of why it randomly takes several minutes to complete the same query, with no change in data in the DB either. I have tried increasing the work_mem which didn't make any difference (nor did I really expect it to). Any help or suggestions would be greatly appreciated.

There isn't any more specific tags, but I'm currently using Postgres 10.11, but it's also been an issue on other versions of 10.x. System is a Xeon quad-core @ 3.4Ghz, with SSD and 24GB of memory.

Per jjanes's suggestion, I put in the auto_explain. Eventually go this output:

duration: 128057.373 ms
plan:
Query Text: SET work_mem = '32MB';SELECT        s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset FROM     rm_o_resource_usage_instance_splits_new s INNER JOIN    rm_o_resource_usage r ON s.usage_id = r.id INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index AND r.schedule_id = sa.solution_id and s.solution = sa.solution_id WHERE      r.schedule_id = 12642 ORDER BY   r.resource_id, s.start_date
Sort  (cost=14.36..14.37 rows=1 width=98) (actual time=128042.083..128043.287 rows=21899 loops=1)
  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6585kB
  Buffers: shared hit=21198435 read=388 dirtied=119
  ->  Nested Loop  (cost=0.85..14.35 rows=1 width=98) (actual time=4.995..127958.935 rows=21899 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 705476285
        Buffers: shared hit=21198435 read=388 dirtied=119
        ->  Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=22102 read=388 dirtied=119
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..8.44 rows=1 width=69) (actual time=0.082..17.418 rows=21899 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12642)
                    Buffers: shared hit=203 read=388 dirtied=119
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.29 rows=1 width=57) (actual time=0.002..0.002 rows=1 loops=21899)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12642)
                    Rows Removed by Filter: 26
                    Buffers: shared hit=21899
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.60 rows=1 width=16) (actual time=0.006..4.612 rows=32216 loops=21899)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12642)
              Buffers: shared hit=21176333",,,,,,,,,""

EDIT: Full definitions of the tables are below:

CREATE TABLE public.rm_o_resource_usage_instance_splits_new
(
    start_time integer NOT NULL,
    end_time integer NOT NULL,
    resources jsonb NOT NULL,
    activity_index integer NOT NULL,
    usage_id bigint NOT NULL,
    start_date text COLLATE pg_catalog."default" NOT NULL,
    end_date text COLLATE pg_catalog."default" NOT NULL,
    solution bigint NOT NULL,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_pkey PRIMARY KEY (start_time, activity_index, usage_id),
    CONSTRAINT rm_o_resource_usage_instance_splits_new_solution_fkey FOREIGN KEY (solution)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT rm_o_resource_usage_instance_splits_new_usage_id_fkey FOREIGN KEY (usage_id)
        REFERENCES public.rm_o_resource_usage (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_activity_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_solution_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (solution ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_instance_splits_new_usage_idx
    ON public.rm_o_resource_usage_instance_splits_new USING btree
    (usage_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE TABLE public.rm_o_resource_usage
(
    id bigint NOT NULL DEFAULT nextval('rm_o_resource_usage_id_seq'::regclass),
    schedule_id bigint NOT NULL,
    resource_id text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT rm_o_resource_usage_pkey PRIMARY KEY (id),
    CONSTRAINT rm_o_resource_usage_schedule_id_fkey FOREIGN KEY (schedule_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_idx
    ON public.rm_o_resource_usage USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX rm_o_resource_usage_sched
    ON public.rm_o_resource_usage USING btree
    (schedule_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE TABLE public.scheduledactivities
(
    id bigint NOT NULL DEFAULT nextval('scheduledactivities_id_seq'::regclass),
    solution_id bigint NOT NULL,
    activity_id text COLLATE pg_catalog."default" NOT NULL,
    sequence_index integer,
    startminute integer,
    finishminute integer,
    issue text COLLATE pg_catalog."default",
    activity_index integer NOT NULL,
    is_objective boolean NOT NULL,
    usedresourceset integer DEFAULT '-1'::integer,
    start timestamp without time zone,
    finish timestamp without time zone,
    is_ore boolean,
    is_ignored boolean,
    CONSTRAINT scheduled_activities_pkey PRIMARY KEY (id),
    CONSTRAINT scheduledactivities_solution_id_fkey FOREIGN KEY (solution_id)
        REFERENCES public.rm_o_schedule_stats (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE INDEX scheduled_activities_activity_id_idx
    ON public.scheduledactivities USING btree
    (activity_id COLLATE pg_catalog."default" ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_id_idx
    ON public.scheduledactivities USING btree
    (id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduled_activities_idx
    ON public.scheduledactivities USING btree
    (solution_id ASC NULLS LAST)
    TABLESPACE pg_default;

CREATE INDEX scheduledactivities_activity_index_idx
    ON public.scheduledactivities USING btree
    (activity_index ASC NULLS LAST)
    TABLESPACE pg_default;

EDIT: Additional output from auto_explain after adding index on scheduledactivities (solution_id, activity_index)

  Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
  Sort Key: r.resource_id, s.start_date
  Sort Method: quicksort  Memory: 6283kB
  Buffers: shared hit=20159117 read=375 dirtied=190
  ->  Nested Loop  (cost=0.85..10.76 rows=1 width=100) (actual time=5.518..122489.627 rows=20761 loops=1)
        Output: s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
        Join Filter: (s.activity_index = sa.activity_index)
        Rows Removed by Join Filter: 668815615
        Buffers: shared hit=20159117 read=375 dirtied=190
        ->  Nested Loop  (cost=0.42..5.80 rows=1 width=112) (actual time=0.057..217.563 rows=20761 loops=1)
              Output: s.start_date, s.end_date, s.resources, s.activity_index, s.solution, r.resource_id, r.schedule_id
              Inner Unique: true
              Join Filter: (s.usage_id = r.id)
              Buffers: shared hit=20947 read=375 dirtied=190
              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on public.rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.44 rows=1 width=69) (actual time=0.049..17.622 rows=20761 loops=1)
                    Output: s.start_time, s.end_time, s.resources, s.activity_index, s.usage_id, s.start_date, s.end_date, s.solution
                    Index Cond: (s.solution = 12644)
                    Buffers: shared hit=186 read=375 dirtied=190
              ->  Seq Scan on public.rm_o_resource_usage r  (cost=0.00..1.35 rows=1 width=59) (actual time=0.002..0.002 rows=1 loops=20761)
                    Output: r.id, r.schedule_id, r.resource_id
                    Filter: (r.schedule_id = 12644)
                    Rows Removed by Filter: 22
                    Buffers: shared hit=20761
        ->  Index Scan using scheduled_activities_idx on public.scheduledactivities sa  (cost=0.42..4.94 rows=1 width=16) (actual time=0.007..4.654 rows=32216 loops=20761)
              Output: sa.usedresourceset, sa.activity_index, sa.solution_id
              Index Cond: (sa.solution_id = 12644)
              Buffers: shared hit=20138170",,,,,,,,,""

The easiest way to reproduce the issue is to add more values to the three tables. I didn't delete any, only did a few thousand INSERTs.

Body:
The SQL statement of the fast plan is using WHERE   r.schedule_id = 10 and returns about 22000 rows (with estimated 105).
The SQL statement of the slow plan is using WHERE   r.schedule_id = 12642 and returns about 21000 rows (with estimated only 1).

The slow plan is using nested loops instead of hash joins: maybe because there is a bad estimation for joins: estimated rows is 1 but actual rows is 21899.
For example in this step:

Nested Loop  (cost=0.42..9.74 rows=1 width=110) (actual time=0.091..227.705 rows=21899 loops=1)

If data does not change there is maybe a statistic issue (skew data) for some columns.


问:
Upgrade to new version of JasperServer
How in the world do I go about updating to the new version  of JasperServer? Their site has no real documentation on how to accomplish this.

I have downloaded the JasperServer archive (Windows, btw), but what is next?

The reason for doing this is that the new version of iReport has some sort of file compatibly issue with it's own new jrxml file, and the current fix is updating JasperServer.

答:
The reason they don't say how to do it is because JasperReports isn't a standalone app that end users upgrade themselves - it's a library used for reporting features. If you didn't build the application that uses JasperReports yourself you don't really have any reason to upgrade to 4.0.2.

If you did build the application yourself, then you just need to swap the jars from the old jasperreports out with the new ones and then test to make sure there weren't any breaking changes made to the API. (The changelog doesn't seem to indicate there were any, but you don't ever indicate what version you are upgrading from so perhaps there are some)

If you are using something like maven to build whatever you are using, you can update the version in the dependency information and run a new build and after all your existing unit tests pass you can run your app with the new version of jasperreports and make sure it is all still working.

Title: Upgrade to new version of JasperServer


问:
How to set current date in active month using Pabo Calendar?
I want to show the current date in Pabo calendar but there is only a read-only property.

How can I set the current date?

```<code>namespace Pabo.Calendar
{
    [DefaultEvent("MonthChanged")]
    [DefaultProperty("Name")]
    [Designer(typeof(MonthCalendarDesigner))]
    [ToolboxBitmap(typeof(MonthCalendar), "Pabo.Calendar.MonthCalendar.bmp")]
    [ToolboxItem(true)]
    public class MonthCalendar : Control
    {
        public WeekCallBack WeeknumberCallBack;

        public MonthCalendar();

        [Category("Behavior")]
        [Description("")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ActiveMonth ActiveMonth { get; }
        [Category("Behavior")]
        [DefaultValue(0)]
        [Description("First day of week.")]
        [RefreshProperties(RefreshProperties.All)]
        [TypeConverter(typeof(FirstDayOfWeekConverter))]
        public int FirstDayOfWeek { get; set; }

    }
}
</code>```

答:
I am not very familiar with the Pabo.Calendar control but it looks like you can just update the Month or Year properties of the object that is returned from the ActiveMonth property. Something like this should work:

```<code>// This code example assumes you have an instance of the
// MonthCalendar object that is called `myMonthCalendar`.
var today = DateTime.Today;
myMonthCalendar.ActiveMonth.Year = today.Year;
myMonthCalendar.ActiveMonth.Month = today.Month;
</code>```

The above code reads the value from the ActiveMonth property (which is an instance of the ActiveMonth class, which in turn contains two properties Year and Month). Next it will set the Year and Month properties to the desired values. A more verbose version of the code above would be:

```<code>// This code example assumes you have an instance of the
// MonthCalendar object that is called `myMonthCalendar`.
var today = DateTime.Today;
var activeMonth = myMonthCalendar.ActiveMonth; // Here we only read the ActiveMonth property.
activeMonth.Year = today.Year; // Here we update or set the Year value
activeMonth.Month = today.Month; // Here we update or set the Month value
</code>```

Body:
I want to show the current date in Pabo calendar but there is only a read-only property.

How can I set the current date?

namespace Pabo.Calendar
{
    [DefaultEvent("MonthChanged")]
    [DefaultProperty("Name")]
    [Designer(typeof(MonthCalendarDesigner))]
    [ToolboxBitmap(typeof(MonthCalendar), "Pabo.Calendar.MonthCalendar.bmp")]
    [ToolboxItem(true)]
    public class MonthCalendar : Control
    {
        public WeekCallBack WeeknumberCallBack;

        public MonthCalendar();

        [Category("Behavior")]
        [Description("")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ActiveMonth ActiveMonth { get; }
        [Category("Behavior")]
        [DefaultValue(0)]
        [Description("First day of week.")]
        [RefreshProperties(RefreshProperties.All)]
        [TypeConverter(typeof(FirstDayOfWeekConverter))]
        public int FirstDayOfWeek { get; set; }

    }
}

Body:
I am not very familiar with the Pabo.Calendar control but it looks like you can just update the Month or Year properties of the object that is returned from the ActiveMonth property. Something like this should work:

// This code example assumes you have an instance of the
// MonthCalendar object that is called `myMonthCalendar`.
var today = DateTime.Today;
myMonthCalendar.ActiveMonth.Year = today.Year;
myMonthCalendar.ActiveMonth.Month = today.Month;

The above code reads the value from the ActiveMonth property (which is an instance of the ActiveMonth class, which in turn contains two properties Year and Month). Next it will set the Year and Month properties to the desired values. A more verbose version of the code above would be:

// This code example assumes you have an instance of the
// MonthCalendar object that is called `myMonthCalendar`.
var today = DateTime.Today;
var activeMonth = myMonthCalendar.ActiveMonth; // Here we only read the ActiveMonth property.
activeMonth.Year = today.Year; // Here we update or set the Year value
activeMonth.Month = today.Month; // Here we update or set the Month value


问:
Reverse linked list - how to remove "None" which is coming at the end (of output)
I am solving this problem on leetcode - Reverse linked list

My code is running fine I believe but I am receiving "None" in the output. How can I remove this?

This is how output is coming for the input [1,2,3,4,5]:

Output: [5,4,3,2,1,None]

Here is the code I tried:

```<code>class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        if head is None: return None

        if head.next is None: return head

        cur = head
        prev = ListNode(None)
        temp = head.next

        while temp:
            cur.next = prev
            prev = cur
            cur = temp
            temp = temp.next

        if temp is None:
            cur.next = prev

        head = cur
        return head
</code>```

答:
As a complementary answer, you are using too many useless if statements that you could avoid. Similarly to your answer, your could reduce it simply to the following:</p>

```<code>def reverseList(self, head: ListNode) -> ListNode:
prev = None

while head:
    temp  = head.next
    head.next = prev
    prev = head
    head = temp

return prev
</code>```

Body:
I am solving this problem on leetcode - Reverse linked list

My code is running fine I believe but I am receiving "None" in the output. How can I remove this?

This is how output is coming for the input [1,2,3,4,5]:

Output: [5,4,3,2,1,None]

Here is the code I tried:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        if head is None: return None

        if head.next is None: return head

        cur = head
        prev = ListNode(None)
        temp = head.next

        while temp:
            cur.next = prev
            prev = cur
            cur = temp
            temp = temp.next

        if temp is None:
            cur.next = prev

        head = cur
        return head

Body:
As a complementary answer, you are using too many useless if statements that you could avoid. Similarly to your answer, your could reduce it simply to the following:

def reverseList(self, head: ListNode) -> ListNode:
prev = None

while head:
    temp  = head.next
    head.next = prev
    prev = head
    head = temp

return prev


问:
Is any ways to speedup work of Map.getOrElse(val, 0) on big tuple maps?
I has simple immutable Map in Scala:

```<code>// ... - mean and so on
val myLibrary = Map("qwe" -> 1.2, "qasd" -> -0.59, ...)
</code>```

And for that myMap i calling MyFind method which call getOrElse(val, 0):

```<code>def MyFind (srcMap: Map[String,Int], str: String): Int ={
    srcMap.getOrElse(str,0)
}

val res = MyFind(myLibrary, "qwe")
</code>```

Problem in that this method called several times for different input strings. E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

What you can advice to speedup that code?

Maybe use another type of Map?

Maybe another collection?

答:
Map does not have linear time lookup. Default concrete implementation of Map is HashMap

Map is the interface for immutable maps
  while scala.collection.immutable.HashMap is a concrete implementation.

which has effective constant lookup time, as per collections performance characteristic

```<code>                lookup  add  remove  min

HashSet/HashMap  eC     eC    eC     L
</code>```

Body:
I has simple immutable Map in Scala:

// ... - mean and so on
val myLibrary = Map("qwe" -> 1.2, "qasd" -> -0.59, ...)

And for that myMap i calling MyFind method which call getOrElse(val, 0):

def MyFind (srcMap: Map[String,Int], str: String): Int ={
    srcMap.getOrElse(str,0)
}

val res = MyFind(myLibrary, "qwe")

Problem in that this method called several times for different input strings. E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

What you can advice to speedup that code?

Maybe use another type of Map?

Maybe another collection?

Body:
Map does not have linear time lookup. Default concrete implementation of Map is HashMap

Map is the interface for immutable maps
  while scala.collection.immutable.HashMap is a concrete implementation.

which has effective constant lookup time, as per collections performance characteristic

                lookup  add  remove  min

HashSet/HashMap  eC     eC    eC     L