问:
How to adjust the sizes in JFrame and JPanel?
I'm creating a simple game by Java GUI, but I have some problems with the initial design with panels.

I want the design to be like this (see picture)

But I always have problems with sizes I suppose.

This is my code if you have any suggestions.

```<code>public class GameProject extends JFrame {

ImagePanel gamePanel;
Image image = null;

public GameProject() {

    setTitle("");
    setSize(1100, 900);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    ImageIcon image = new ImageIcon("logo.jpg");
    JLabel label = new JLabel("", image, JLabel.CENTER);
    JPanel leftPanel = new JPanel(new BorderLayout());
    leftPanel.setBackground(Color.LIGHT_GRAY);
    leftPanel.setBounds(300, 900, 180, 110);
    leftPanel.add(label, BorderLayout.WEST);

    add(leftPanel);

    gamePanel = new ImagePanel("SnakesLadders2.jpg");

    add(gamePanel, BorderLayout.CENTER);

    setVisible(true);
}

class ImagePanel extends JPanel {

    public ImagePanel() {

    }

    public ImagePanel(String filename) {
        image = new ImageIcon(filename).getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
    }

}

public static void main(String[] args) {
    new GameProject();

}
}
</code>```

答:
Never use setBounds(...). For one layout managers are geared towards respecting a components preferred size and not its size, and for another, if you hard-code sizes and positions, you almost guarantee that the GUI will not work well on all platforms except your own. For your problem, if you display the image as an ImageIcon within a JLabel, then the JLabel will set its preferred size based on the image. If you need to display the image within a JPanel, then it's up to you to do this. I sometimes do something like:

```<code>class ImagePanel extends JPanel {
    private BufferedImage image;

    public ImagePanel() {

    }

    public ImagePanel(String filename) {
        // image = new ImageIcon(filename).getImage();
        // don't get images this way.
        // use ImageIO.read(URL url) and get the image as a resource
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return super.getPreferredSize();
        } else {
            int w = image.getWidth();
            int h = image.getHeight();
            return new Dimension(w, h);
        }
    }
}
</code>```

Also, don't get images as you're doing. Better to

use ImageIO.read(...)

if you're going to use the images as Images, then get the images as images, not as ImageIcons

get the image as a resource, not as a File.

An example.....

```<code>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class SnakesAndLaddersProgram extends JPanel {
    public static final String GAME_BOARD_PATH = "http://www.righttoremain.org."
            + "uk/blog/wp-content/uploads/2015/11/snakesladders.jpg";
    public static final String GAME_LOGO_PATH = "https://loteries.lotoquebec.com"
            + "/loteries/___W9a9e8ef6-0c97-4d1b-a4c3-2588fee936d3___.png";
    private static final double BOARD_SCALE = 0.5; // online images too big
    private static final double LOGO_SCALE = 0.3; // online images too big
    private ImagePanel imagePanel = null;

    public SnakesAndLaddersProgram() throws IOException {
        URL gameBoardUrl = new URL(GAME_BOARD_PATH);
        Image gameBoard = ImageIO.read(gameBoardUrl);
        // scale to size:
        int w = (int) (gameBoard.getWidth(this) * BOARD_SCALE);
        int h = (int) (gameBoard.getHeight(this) * BOARD_SCALE);
        gameBoard = gameBoard.getScaledInstance(w, h, Image.SCALE_DEFAULT);
        imagePanel = new ImagePanel(gameBoard);

        URL logoUrl = new URL(GAME_LOGO_PATH);
        Image logo = ImageIO.read(logoUrl);
        // scale to size:
        w = (int) (logo.getWidth(this) * LOGO_SCALE);
        h = (int) (logo.getHeight(this) * LOGO_SCALE);
        Icon logoIcon = new ImageIcon(logo);
        JLabel logoLabel = new JLabel(logoIcon);
        JPanel westPanel = new JPanel();
        westPanel.add(logoLabel);

        setLayout(new BorderLayout());
        add(imagePanel, BorderLayout.CENTER);
        add(westPanel, BorderLayout.LINE_START);
    }

    private static void createAndShowGui() {
        SnakesAndLaddersProgram mainPanel = null;
        try {
            mainPanel = new SnakesAndLaddersProgram();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        JFrame frame = new JFrame("Snakes And Ladders");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class ImagePanel extends JPanel {
    private Image image;

    public ImagePanel() {

    }

    public ImagePanel(Image image) {
        this.image = image;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return super.getPreferredSize();
        } else {
            int w = image.getWidth(this);
            int h = image.getHeight(this);
            return new Dimension(w, h);
        }
    }
}
</code>```

Body:
I'm creating a simple game by Java GUI, but I have some problems with the initial design with panels.

I want the design to be like this (see picture)

But I always have problems with sizes I suppose.

This is my code if you have any suggestions.

public class GameProject extends JFrame {

ImagePanel gamePanel;
Image image = null;

public GameProject() {

    setTitle("");
    setSize(1100, 900);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    ImageIcon image = new ImageIcon("logo.jpg");
    JLabel label = new JLabel("", image, JLabel.CENTER);
    JPanel leftPanel = new JPanel(new BorderLayout());
    leftPanel.setBackground(Color.LIGHT_GRAY);
    leftPanel.setBounds(300, 900, 180, 110);
    leftPanel.add(label, BorderLayout.WEST);

    add(leftPanel);

    gamePanel = new ImagePanel("SnakesLadders2.jpg");

    add(gamePanel, BorderLayout.CENTER);

    setVisible(true);
}

class ImagePanel extends JPanel {

    public ImagePanel() {

    }

    public ImagePanel(String filename) {
        image = new ImageIcon(filename).getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
    }

}

public static void main(String[] args) {
    new GameProject();

}
}

Body:
Never use setBounds(...). For one layout managers are geared towards respecting a components preferred size and not its size, and for another, if you hard-code sizes and positions, you almost guarantee that the GUI will not work well on all platforms except your own. For your problem, if you display the image as an ImageIcon within a JLabel, then the JLabel will set its preferred size based on the image. If you need to display the image within a JPanel, then it's up to you to do this. I sometimes do something like:

class ImagePanel extends JPanel {
    private BufferedImage image;

    public ImagePanel() {

    }

    public ImagePanel(String filename) {
        // image = new ImageIcon(filename).getImage();
        // don't get images this way.
        // use ImageIO.read(URL url) and get the image as a resource
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return super.getPreferredSize();
        } else {
            int w = image.getWidth();
            int h = image.getHeight();
            return new Dimension(w, h);
        }
    }
}

Also, don't get images as you're doing. Better to

use ImageIO.read(...)

if you're going to use the images as Images, then get the images as images, not as ImageIcons

get the image as a resource, not as a File.

An example.....

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class SnakesAndLaddersProgram extends JPanel {
    public static final String GAME_BOARD_PATH = "http://www.righttoremain.org."
            + "uk/blog/wp-content/uploads/2015/11/snakesladders.jpg";
    public static final String GAME_LOGO_PATH = "https://loteries.lotoquebec.com"
            + "/loteries/___W9a9e8ef6-0c97-4d1b-a4c3-2588fee936d3___.png";
    private static final double BOARD_SCALE = 0.5; // online images too big
    private static final double LOGO_SCALE = 0.3; // online images too big
    private ImagePanel imagePanel = null;

    public SnakesAndLaddersProgram() throws IOException {
        URL gameBoardUrl = new URL(GAME_BOARD_PATH);
        Image gameBoard = ImageIO.read(gameBoardUrl);
        // scale to size:
        int w = (int) (gameBoard.getWidth(this) * BOARD_SCALE);
        int h = (int) (gameBoard.getHeight(this) * BOARD_SCALE);
        gameBoard = gameBoard.getScaledInstance(w, h, Image.SCALE_DEFAULT);
        imagePanel = new ImagePanel(gameBoard);

        URL logoUrl = new URL(GAME_LOGO_PATH);
        Image logo = ImageIO.read(logoUrl);
        // scale to size:
        w = (int) (logo.getWidth(this) * LOGO_SCALE);
        h = (int) (logo.getHeight(this) * LOGO_SCALE);
        Icon logoIcon = new ImageIcon(logo);
        JLabel logoLabel = new JLabel(logoIcon);
        JPanel westPanel = new JPanel();
        westPanel.add(logoLabel);

        setLayout(new BorderLayout());
        add(imagePanel, BorderLayout.CENTER);
        add(westPanel, BorderLayout.LINE_START);
    }

    private static void createAndShowGui() {
        SnakesAndLaddersProgram mainPanel = null;
        try {
            mainPanel = new SnakesAndLaddersProgram();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        JFrame frame = new JFrame("Snakes And Ladders");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class ImagePanel extends JPanel {
    private Image image;

    public ImagePanel() {

    }

    public ImagePanel(Image image) {
        this.image = image;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return super.getPreferredSize();
        } else {
            int w = image.getWidth(this);
            int h = image.getHeight(this);
            return new Dimension(w, h);
        }
    }
}


来源: stackexchange

问:
How to use Where operator in Linq
```<code>SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported
</code>```

but why when I use number instead of parameter it works fine ?

```<code>SomeObject.Where(p => FunctionOn(1));
</code>```

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

答: You need to be more specific with the error you are actually getting, however, as a general guide normally this would fail if FunctionOn cannot be translated into a database specific language query (if SomeObject is a DB entity) or it does not return a boolean value which the Where function expects.

ContentLicense: CC BY-SA 2.5

Title: How to use Where operator in Linq

Body:
SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported

but why when I use number instead of parameter it works fine ?

SomeObject.Where(p => FunctionOn(1));

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .


问:
Pass data to spyOn andReturnValue
I'm trying to mock a call to a service which makes a http call.  I'd like to supply fake data in the mock and check against it in my test.

Here is my set up.

```<code>beforeEach(() => {
  fixture = TestBed.createComponent(MhSearchFormComponent);
  component = fixture.componentInstance;
  component.propertyCount = 0;
  spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {} });
  fixture.detectChanges();
});
</code>```

I want to reassign propertyCount value in the return of the spy.

Here is my test :

```<code>  it('should get a count on load', () => {
    expect(component.propertyCount).toBe('1000');
  });
</code>```

I've tried this but it's evidently wrong

spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {'Count':1000} });

答:
I do not know how your component/service looks like. Please try the below sample. If you face any issue, then please post the component and service template.</p>

```<code>beforeEach(() => {
  fixture = TestBed.createComponent(MhSearchFormComponent);
  component = fixture.componentInstance;
  component.propertyCount = 0;
  // To get injected Service Instance from Component.
  const searchService = fixture.debugElement.injector.get(SearchService);
  // Observable.of('1000') will ensure the subscribe method and its handling
  // And the subscriber will get '1000' as argument.
  spyOn(searchService, 'getCount').and.returnValue(Observable.of('1000'));

  fixture.detectChanges();
});

it('should get a count on load', () => {
  expect(component.propertyCount).toBe('1000');
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pass data to spyOn andReturnValue

Body:
I'm trying to mock a call to a service which makes a http call.  I'd like to supply fake data in the mock and check against it in my test.

Here is my set up.

beforeEach(() => {
  fixture = TestBed.createComponent(MhSearchFormComponent);
  component = fixture.componentInstance;
  component.propertyCount = 0;
  spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {} });
  fixture.detectChanges();
});

I want to reassign propertyCount value in the return of the spy.

Here is my test :

  it('should get a count on load', () => {
    expect(component.propertyCount).toBe('1000');
  });

I've tried this but it's evidently wrong

spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {'Count':1000} });

Body:
I do not know how your component/service looks like. Please try the below sample. If you face any issue, then please post the component and service template.

beforeEach(() => {
  fixture = TestBed.createComponent(MhSearchFormComponent);
  component = fixture.componentInstance;
  component.propertyCount = 0;
  // To get injected Service Instance from Component.
  const searchService = fixture.debugElement.injector.get(SearchService);
  // Observable.of('1000') will ensure the subscribe method and its handling
  // And the subscriber will get '1000' as argument.
  spyOn(searchService, 'getCount').and.returnValue(Observable.of('1000'));

  fixture.detectChanges();
});

it('should get a count on load', () => {
  expect(component.propertyCount).toBe('1000');
});


问:
Directly assigning to a std::vector after reserving does not throw error but does not increase vector size
Let's create a helper class to assist visualizing the issue:

```<code>class C
{
int ID = 0;

public:
C(const int newID)
{
    ID = newID;
}

int getID()
{
    return ID;
}
};
</code>```

Suppose you create an empty std::vector<C> and then reserve it to hold 10 elements:

```<code>std::vector<C> pack;
pack.reserve(10);
printf("pack has  %i\n", pack.size()); //will print '0'
</code>```

Now, you assign a new instance of C into index 4 of the vector:

```<code>pack[4] = C(57);
printf("%i\n", pack[4].getID()); //will print '57'
printf("pack has  %i\n", pack.size()); //will still print '0'
</code>```

I found two things to be weird here:

1) shouldn't the assignment make the compiler (Visual Studio 2015, Release Mode) throw an error even in Release mode?

2) since it does not and the element is in fact stored in position 4, shouldn't the vector then have size = 1 instead of zero?

答:
Short answers:

1) There is no reason to throw an exception since operator[] is not supposed to verify the position you have passed. It might do so in Debug mode, but for sure not in Release (otherwise performance would suffer). In Release mode compiler trusts you that code you provide is error-proof and does everything to make your code fast.

Returns a reference to the element at specified location pos. No
  bounds checking is performed.

http://en.cppreference.com/w/cpp/container/vector/operator_at

2) You simply accessed memory you don't own yet (reserve is not resize), anything you do on it is undefined behavior. But, you have never added an element into vector and it has no idea you even modified its buffer. And as @Bill have shown, the vector is allowed to change its buffer without copying your local change.

EDIT:
Also, you can get exception due to boundary checking if you use vector::at function.

That is: pack.at(4) = C(57); throws exception

Example:
https://ideone.com/sXnPzT

Body:
Let's create a helper class to assist visualizing the issue:

class C
{
int ID = 0;

public:
C(const int newID)
{
    ID = newID;
}

int getID()
{
    return ID;
}
};

Suppose you create an empty std::vector<C> and then reserve it to hold 10 elements:

std::vector<C> pack;
pack.reserve(10);
printf("pack has  %i\n", pack.size()); //will print '0'

Now, you assign a new instance of C into index 4 of the vector:

pack[4] = C(57);
printf("%i\n", pack[4].getID()); //will print '57'
printf("pack has  %i\n", pack.size()); //will still print '0'

I found two things to be weird here:

1) shouldn't the assignment make the compiler (Visual Studio 2015, Release Mode) throw an error even in Release mode?

2) since it does not and the element is in fact stored in position 4, shouldn't the vector then have size = 1 instead of zero?


问:
Oracle Trigger How to get Inserted value's parameter
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

```<code>**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))
</code>```

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

```<code>INSERT INTO employee values (1000, 'PAUL', 10, 4000);
</code>```

Then Trigger would like to have the following output:

```<code>Department [10]'s average of Salary = <avg (salary)>
</code>```

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?

答:
Trigger is not the best place for such things, but it can be done with compound trigger:

```<code>create or replace trigger avg_dept_salary for insert on employee compound trigger

  type tb_num is table of number;
  v_depts tb_num := tb_num();
  v_sum number;

before each row is
  begin
    if :new.deptno not member of v_depts then
      v_depts.extend();
      v_depts(v_depts.count()) := :new.deptno;
    end if;
  end before each row;

after statement is
  begin
    for i in 1..v_depts.count() loop
      select avg(salary) into v_sum from employee where deptno = v_depts(i);
      dbms_output.put_line('Department '||v_depts(i)||' average salary: '||v_sum);
    end loop;
  end after statement;

end;
</code>```

Test:

```<code>insert into employee
  select 1001, 'PAUL', 10, 1000 from dual union all
  select 1002, 'ANNE', 10, 1700 from dual union all
  select 1003, 'MARY', 10,  900 from dual union all
  select 1004, 'JOHN', 20, 1200 from dual;
</code>```

Output for each affected department:

```<code>Department 10 average salary: 1900
Department 20 average salary: 1200
</code>```

Body:
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

INSERT INTO employee values (1000, 'PAUL', 10, 4000);

Then Trigger would like to have the following output:

Department [10]'s average of Salary = <avg (salary)>

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?

Body:
Trigger is not the best place for such things, but it can be done with compound trigger:

create or replace trigger avg_dept_salary for insert on employee compound trigger

  type tb_num is table of number;
  v_depts tb_num := tb_num();
  v_sum number;

before each row is
  begin
    if :new.deptno not member of v_depts then
      v_depts.extend();
      v_depts(v_depts.count()) := :new.deptno;
    end if;
  end before each row;

after statement is
  begin
    for i in 1..v_depts.count() loop
      select avg(salary) into v_sum from employee where deptno = v_depts(i);
      dbms_output.put_line('Department '||v_depts(i)||' average salary: '||v_sum);
    end loop;
  end after statement;

end;

Test:

insert into employee
  select 1001, 'PAUL', 10, 1000 from dual union all
  select 1002, 'ANNE', 10, 1700 from dual union all
  select 1003, 'MARY', 10,  900 from dual union all
  select 1004, 'JOHN', 20, 1200 from dual;

Output for each affected department:

Department 10 average salary: 1900
Department 20 average salary: 1200


问:
Validate in Shiny doesn't work as expected when making a highcharter treemap
When trying to make a highcharter treemap in Shiny I encountered this strange thing. When the condition for validate a highchart isn't met I get this interactive text treemap togehter with my validate message (instead of just the text).

Am I doing something wrong or is this just a bug within Highchart?

```<code>## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n",
                             "Input number", value = 1),
                highchartOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )
  output$tree <- renderHighchart({
    validate(need(input$n == 1, "Please input number 1"))
    hctreemap(tm = tm)
  })
}

shinyApp(ui, server)
</code>```

答:
Here is a work around using the renderUI

```<code>## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n","Input number", value = 1),
                htmlOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )

  output$tree <- renderUI({
    validate(need(input$n == 1, "Please input number 1"))
    if(input$n != 1){
      h1 <- highchart()
    }
    else{
      h1 <- hctreemap(tm = tm)
    }
    hw_grid(h1,rowheight = 390)
  })

}

shinyApp(ui, server)
</code>```

Body:
When trying to make a highcharter treemap in Shiny I encountered this strange thing. When the condition for validate a highchart isn't met I get this interactive text treemap togehter with my validate message (instead of just the text).

Am I doing something wrong or is this just a bug within Highchart?

## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n",
                             "Input number", value = 1),
                highchartOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )
  output$tree <- renderHighchart({
    validate(need(input$n == 1, "Please input number 1"))
    hctreemap(tm = tm)
  })
}

shinyApp(ui, server)

Body:
Here is a work around using the renderUI

## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n","Input number", value = 1),
                htmlOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )

  output$tree <- renderUI({
    validate(need(input$n == 1, "Please input number 1"))
    if(input$n != 1){
      h1 <- highchart()
    }
    else{
      h1 <- hctreemap(tm = tm)
    }
    hw_grid(h1,rowheight = 390)
  })

}

shinyApp(ui, server)


问:
Javascript: highlight substring keeping original case but searching in case insensitive mode
I'm trying to write a "suggestion search box" and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.

For example if I search for "ca" I search server side in a case insensitive mode and I have the following results:

Calculator

calendar

ESCAPE

I would like to view the search string in all the previous words, so the result should be:

Calculator

calendar

ESCAPE

I tried with the following code:

```<code>var reg = new RegExp(querystr, 'gi');
var final_str = 'foo ' + result.replace(reg, '<b>'+querystr+'</b>');
$('#'+id).html(final_str);
</code>```

But obviously in this way I loose the original case!

Is there a way to solve this problem?

答:
ES6 version</p>
```<code>const highlight = (needle, haystack) =>
  haystack.replace(
      new RegExp(needle, 'gi'),
      (str) => `<strong>${str}</strong>`
  );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a "suggestion search box" and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.

For example if I search for "ca" I search server side in a case insensitive mode and I have the following results:

Calculator

calendar

ESCAPE

I would like to view the search string in all the previous words, so the result should be:

Calculator

calendar

ESCAPE

I tried with the following code:

var reg = new RegExp(querystr, 'gi');
var final_str = 'foo ' + result.replace(reg, ''+querystr+'');
$('#'+id).html(final_str);

But obviously in this way I loose the original case!

Is there a way to solve this problem?

Body:
ES6 version

const highlight = (needle, haystack) =>
  haystack.replace(
      new RegExp(needle, 'gi'),
      (str) => `<strong>${str}</strong>`
  );


问:
AngularJS use custom filter in javascript file
Pretty new to angularjs, this is my struggle :

```<code>//my-filter.filter.js

function myFilter($filter){
    return filter(input){
        return $filter('currency')(input, 'X');;
    }
}

myFilter.$inject = ['$filter'];

export default myFilter;
</code>```

And :

```<code>//my-component.component.js

class MyComponentController {
    constructor(currencyFilter){
        this.currencyFilter = currencyFilter;
    }

    $onChanges(changes) {
        this.message = changes.data.message;

        this.message = this.currencyFilter(this.message);
    }

    ...
}
</code>```

And :

```<code>.filter('bsMyFilter', myFilter);
</code>```

What I want to achieve is inside my-component.component.js not to use the default angular currencyFilter, but instead to use myFilter. Is this possible and how ? Thx

答:
inject $filter, $filter('bsMyFilter') is you filter.
At least in angular 1.6 - but I doupt they change it.

Note: if you not gonna use it in templates - just create factory.

Body:
Pretty new to angularjs, this is my struggle :

//my-filter.filter.js

function myFilter($filter){
    return filter(input){
        return $filter('currency')(input, 'X');;
    }
}

myFilter.$inject = ['$filter'];

export default myFilter;

And :

//my-component.component.js

class MyComponentController {
    constructor(currencyFilter){
        this.currencyFilter = currencyFilter;
    }

    $onChanges(changes) {
        this.message = changes.data.message;

        this.message = this.currencyFilter(this.message);
    }

    ...
}

And :

.filter('bsMyFilter', myFilter);

What I want to achieve is inside my-component.component.js not to use the default angular currencyFilter, but instead to use myFilter. Is this possible and how ? Thx


问:
How to get parameter from URL(Routing) Angular 2?
I tried to do that in ngOnInit() like:

ngOnInit() {
    this.route.queryParams
      .filter(params => params.type)
      .subscribe(params => {
        this.tab = params.type;
        this.setHeader();
      });
  }
```

<p>My URL is:</p>

<pre class="lang-none prettyprint-override"><code>http://localhost:4200/s/6/t/p/create/1
</code>```

Routing is:

{path: ':Id/t/p/create/:type', component: CalendarComponent},
```

答:
Try</p>

```<code>this.route.params.subscribe(params => {
    this.tab = params.type;
    this.setHeader();
  });
</code>```

Body:
I tried to do that in ngOnInit() like:

ngOnInit() {
    this.route.queryParams
      .filter(params => params.type)
      .subscribe(params => {
        this.tab = params.type;
        this.setHeader();
      });
  }

My URL is:

http://localhost:4200/s/6/t/p/create/1

Routing is:

{path: ':Id/t/p/create/:type', component: CalendarComponent},

Body:
Try

this.route.params.subscribe(params => {
    this.tab = params.type;
    this.setHeader();
  });


问:
In c# how to prevent a class from being modified
Let's say I have an interface:

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}
</code>```

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}
</code>```

I would want it to not compile as well, or at the very least give me a compile warning.

答:
No it is not possible. Are you not trying to define a class itself here? Why do you really need an interface?

However, what you can achieve is make calls to your interface and not your class by doing

```<code> IPerson person = new Person();
</code>```

this way you limit the person object to access only the methods defined in your interface.

Body:
Let's say I have an interface:

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}

I would want it to not compile as well, or at the very least give me a compile warning.

Body:
No it is not possible. Are you not trying to define a class itself here? Why do you really need an interface?

However, what you can achieve is make calls to your interface and not your class by doing

 IPerson person = new Person();

this way you limit the person object to access only the methods defined in your interface.


问:
Great grandchild route won't activate
I am trying to activate a component by url "/Recruitment/Application/2/ApplicantDetails". I am using angular@5.0.0

The routes:

Parent route

```<code>        {
            path: 'Recruitment', loadChildren: 'ngModules/dashboard/RecruitmentDashboardModule#RecruitmentDashboardModule',
            canActivate: [AuthGuard]
        },
      {
            path: '**', component: NotFoundComponent,

            }
        }
</code>```

Child

```<code>   RouterModule.forChild([
        { path: 'Application/:applicantId', loadChildren: '/ngModules/recruitment/RecruitmentModule#RecruitmentModule', pathMatch: 'full' }
    ])
</code>```

Grand child& great grandchild

```<code>    {
    path: '', component: RecruitmentComponent,
    children: [
        { path: 'ApplicantDetails', component: ApplicantDetailsStageComponent },

        {
            path: '',
            redirectTo: 'ApplicantDetails',
            pathMatch: 'full',
        },
    ]
}
</code>```

If I pass "/Recruitment/Application/2" into browser,the last redirectTo will be triggered and the url will be changed to "/Recruitment/Application/2/ApplicantDetails" , but the component won't be ApplicantDetailsStageComponent and  the 404 page will be loaded instead.

The "RecruitmentComponent" is getting loaded fine (if I remove the redirectTo), and I could extract ":applicantId" in it.

Does anyone sees anything obvious?

答: The problem was in "  pathMatch: 'full'," I removed it from children routes and everything started to work. </p>

Title: Great grandchild route won't activate

Body:
I am trying to activate a component by url "/Recruitment/Application/2/ApplicantDetails". I am using angular@5.0.0

The routes:

Parent route

        {
            path: 'Recruitment', loadChildren: 'ngModules/dashboard/RecruitmentDashboardModule#RecruitmentDashboardModule',
            canActivate: [AuthGuard]
        },
      {
            path: '**', component: NotFoundComponent,

            }
        }

Child

   RouterModule.forChild([
        { path: 'Application/:applicantId', loadChildren: '/ngModules/recruitment/RecruitmentModule#RecruitmentModule', pathMatch: 'full' }
    ])

Grand child& great grandchild

    {
    path: '', component: RecruitmentComponent,
    children: [
        { path: 'ApplicantDetails', component: ApplicantDetailsStageComponent },

        {
            path: '',
            redirectTo: 'ApplicantDetails',
            pathMatch: 'full',
        },
    ]
}

If I pass "/Recruitment/Application/2" into browser,the last redirectTo will be triggered and the url will be changed to "/Recruitment/Application/2/ApplicantDetails" , but the component won't be ApplicantDetailsStageComponent and  the 404 page will be loaded instead.

The "RecruitmentComponent" is getting loaded fine (if I remove the redirectTo), and I could extract ":applicantId" in it.

Does anyone sees anything obvious?


问:
Interop word dynamic table creation
I need to export Dataset Tables to Word. I have tried a solution using Interop Word. Here I'm facing a problem,

I need to Place the tables in the word document with a series of space, my problem I cant able to create a new table each table on the Dataset.

Here is my code,

```<code>    private void Exporttoword_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet Ds = objMB.ExeQueryStrRetDsBL("SP_PreviewSeries" + cbMatches.SelectedValue, 1);
            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc";
            Microsoft.Office.Interop.Word._Application objWord;
            Microsoft.Office.Interop.Word._Document objDoc;
            objWord = new Microsoft.Office.Interop.Word.Application();
            objWord.Visible = true;
            objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            for (var w = 0; w < Ds.Tables.Count; w++)
            {
                Microsoft.Office.Interop.Word.Table objTable;

                Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                objTable = objDoc.Tables.Add(wrdRng, Convert.ToInt32(Ds.Tables[w].Rows.Count), Convert.ToInt32(Ds.Tables[w].Columns.Count), ref oMissing, ref oMissing);
                objTable.Range.ParagraphFormat.SpaceAfter = 3;
                for (var i = 0; i < Ds.Tables[w].Rows.Count; i++)
                    for (var j = 0; j < Ds.Tables[w].Columns.Count; j++)
                    {
                        objTable.Cell(i + 1, j + 1).Range.Text = Ds.Tables[w].Rows[i][j].ToString();
                        objTable.Cell(i + 1, j + 1).Range.Borders.Enable = 1;
                    }
                objTable.Rows[1].Range.Font.Bold = 1;
                objTable.Rows[1].Range.Font.Italic = 1;
            }
            this.Close();
            string fp = @"D:\Practice\test.docx";
            objDoc.SaveAs2(fp);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
</code>```

答:
You need to declare a Paragraph like Word inside your for loop.

```<code> Microsoft.Office.Interop.Word.Paragraph paragraph;
</code>```

and at the end of for loop

```<code> paragraph = objDoc.Paragraphs.Add();
</code>```

This solution works fine for me. Try this.

Title: Interop word dynamic table creation

Body:
I need to export Dataset Tables to Word. I have tried a solution using Interop Word. Here I'm facing a problem,

I need to Place the tables in the word document with a series of space, my problem I cant able to create a new table each table on the Dataset.

Here is my code,

    private void Exporttoword_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet Ds = objMB.ExeQueryStrRetDsBL("SP_PreviewSeries" + cbMatches.SelectedValue, 1);
            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc";
            Microsoft.Office.Interop.Word._Application objWord;
            Microsoft.Office.Interop.Word._Document objDoc;
            objWord = new Microsoft.Office.Interop.Word.Application();
            objWord.Visible = true;
            objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            for (var w = 0; w < Ds.Tables.Count; w++)
            {
                Microsoft.Office.Interop.Word.Table objTable;

                Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                objTable = objDoc.Tables.Add(wrdRng, Convert.ToInt32(Ds.Tables[w].Rows.Count), Convert.ToInt32(Ds.Tables[w].Columns.Count), ref oMissing, ref oMissing);
                objTable.Range.ParagraphFormat.SpaceAfter = 3;
                for (var i = 0; i < Ds.Tables[w].Rows.Count; i++)
                    for (var j = 0; j < Ds.Tables[w].Columns.Count; j++)
                    {
                        objTable.Cell(i + 1, j + 1).Range.Text = Ds.Tables[w].Rows[i][j].ToString();
                        objTable.Cell(i + 1, j + 1).Range.Borders.Enable = 1;
                    }
                objTable.Rows[1].Range.Font.Bold = 1;
                objTable.Rows[1].Range.Font.Italic = 1;
            }
            this.Close();
            string fp = @"D:\Practice\test.docx";
            objDoc.SaveAs2(fp);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Body:
You need to declare a Paragraph like Word inside your for loop.

 Microsoft.Office.Interop.Word.Paragraph paragraph;

and at the end of for loop

 paragraph = objDoc.Paragraphs.Add();

This solution works fine for me. Try this.


问:
Extract value from enum using guard or if case in Swift
I have enum with cases:

```<code>case one(value: myClassOne)
case two(value: myClassTwo)
</code>```

I want to check value of that enum. Now i ended with:

```<code>switch self.model! {
case .one:
    // Great, my case here
default:
    break
}
</code>```

But i rather want to do something like:

```<code>if case self.model(let value) is myClassOne { // do smth } // Not compiling
</code>```

Is there is easy way to simply extract enum value and check it for some condition or class equality?

答:
This is the correct syntax:</p>

```<code>if case .one(value: let value) = self.model {
    // do something with `value`
}

guard case .one(value: let value) = self.model else {
    //handle case where self.model != .one
}
// do something with `value`
</code>```

Body:
I have enum with cases:

case one(value: myClassOne)
case two(value: myClassTwo)

I want to check value of that enum. Now i ended with:

switch self.model! {
case .one:
    // Great, my case here
default:
    break
}

But i rather want to do something like:

if case self.model(let value) is myClassOne { // do smth } // Not compiling

Is there is easy way to simply extract enum value and check it for some condition or class equality?

Body:
This is the correct syntax:

if case .one(value: let value) = self.model {
    // do something with `value`
}

guard case .one(value: let value) = self.model else {
    //handle case where self.model != .one
}
// do something with `value`


问:
What is the meaning of error message: The return type is incompatible
I'm trying to create the entrySet() method for a custom HashMap. I've attached both my entry class, called MyEntry, and my entrySet() method.

I receive the error:

The return type is incompatible with Map<K,V>.entrySet()

... and the return type is underlined in red. I don't understand what this is expressing.

```<code>@Override
public Set<HashMap<K,V>.MyEntry<K, V>> entrySet(){
if (entrySetView != null) return entrySetView;
    else return entrySetView = new AbstractSet<HashMap<K,V>.MyEntry<K,V>>() {
        @Override
        public Iterator<HashMap<K,V>.MyEntry<K, V>> iterator() {
            return new HashIterator<HashMap<K,V>.MyEntry<K, V>>() {
                @Override
                public HashMap<K,V>.MyEntry<K, V> next() {
                    return nextEntry();
                }
            };
        }

        @Override
        public int size() {
            return HashMap.this.size();
        }

        @Override
        public void clear() {
            HashMap.this.clear();
        }
    };
}

public class MyEntry<K, V> implements Map.Entry<K,V>{
    private K key;
    private V value;
    private MyEntry<K,V> next;
    private int hash;

    public MyEntry() {
        counter++;
    }

    public MyEntry(K key, V value, MyEntry<K,V> next, int h) {
        this.key = key;
        this.value = value;
        this.next = next;
        this.hash = h;
        counter++;
    }

    public boolean equals(Object o) {
        if(this == o) return true;
        if (!(o instanceof MyEntry))
            return false;
        MyEntry entry = (MyEntry)o;
        Object k1 = getKey();
        Object k2 = entry.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            Object v1 = getValue();
            Object v2 = entry.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

    public K getKey() {
        return key;
    }
    public V getValue() {
        return value;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public Object setValue(Object val) {
        V oldValue = value;
        value = (V) val;
        return oldValue;
    }

    public MyEntry<K,V> getNext(){
        return next;
    }

    public void setNext(MyEntry<K,V> n) {
        this.next = n;
    }

    public String toString() {
        return "{" + getKey() + "," + getValue() + "}";
    }
}
</code>```

答:
entrySet of the Map interface has a return type of Set<Map.Entry<K, V>>, so you can't return a Set<HashMap<K,V>.MyEntry<K, V>>.

Set<HashMap<K,V>.MyEntry<K, V>> is not a sub-interface of Set<Map.Entry<K, V>>.

I believe something like this should work (you might have to change the type of entrySetView as well):

```<code>@Override
public Set<Map.Entry<K, V>> entrySet(){
  if (entrySetView != null)
    return entrySetView;
  else
    return entrySetView = new AbstractSet<Map.Entry<K, V>>() {
        @Override
        public Iterator<Map.Entry<K, V>> iterator() {
            return new HashIterator<Map.Entry<K, V>>() {
                @Override
                public Map.Entry<K, V> next() {
                    return nextEntry();
                }
            };
        }

        @Override
        public int size() {
            return HashMap.this.size();
        }

        @Override
        public void clear() {
            HashMap.this.clear();
        }
    };
}
</code>```

Body:
I'm trying to create the entrySet() method for a custom HashMap. I've attached both my entry class, called MyEntry, and my entrySet() method.

I receive the error:

The return type is incompatible with Map<K,V>.entrySet()

... and the return type is underlined in red. I don't understand what this is expressing.

@Override
public Set<HashMap<K,V>.MyEntry<K, V>> entrySet(){
if (entrySetView != null) return entrySetView;
    else return entrySetView = new AbstractSet<HashMap<K,V>.MyEntry<K,V>>() {
        @Override
        public Iterator<HashMap<K,V>.MyEntry<K, V>> iterator() {
            return new HashIterator<HashMap<K,V>.MyEntry<K, V>>() {
                @Override
                public HashMap<K,V>.MyEntry<K, V> next() {
                    return nextEntry();
                }
            };
        }

        @Override
        public int size() {
            return HashMap.this.size();
        }

        @Override
        public void clear() {
            HashMap.this.clear();
        }
    };
}

public class MyEntry<K, V> implements Map.Entry<K,V>{
    private K key;
    private V value;
    private MyEntry<K,V> next;
    private int hash;

    public MyEntry() {
        counter++;
    }

    public MyEntry(K key, V value, MyEntry<K,V> next, int h) {
        this.key = key;
        this.value = value;
        this.next = next;
        this.hash = h;
        counter++;
    }

    public boolean equals(Object o) {
        if(this == o) return true;
        if (!(o instanceof MyEntry))
            return false;
        MyEntry entry = (MyEntry)o;
        Object k1 = getKey();
        Object k2 = entry.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            Object v1 = getValue();
            Object v2 = entry.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

    public K getKey() {
        return key;
    }
    public V getValue() {
        return value;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public Object setValue(Object val) {
        V oldValue = value;
        value = (V) val;
        return oldValue;
    }

    public MyEntry<K,V> getNext(){
        return next;
    }

    public void setNext(MyEntry<K,V> n) {
        this.next = n;
    }

    public String toString() {
        return "{" + getKey() + "," + getValue() + "}";
    }
}

Body:
entrySet of the Map interface has a return type of Set<Map.Entry<K, V>>, so you can't return a Set<HashMap<K,V>.MyEntry<K, V>>.

Set<HashMap<K,V>.MyEntry<K, V>> is not a sub-interface of Set<Map.Entry<K, V>>.

I believe something like this should work (you might have to change the type of entrySetView as well):

@Override
public Set<Map.Entry<K, V>> entrySet(){
  if (entrySetView != null)
    return entrySetView;
  else
    return entrySetView = new AbstractSet<Map.Entry<K, V>>() {
        @Override
        public Iterator<Map.Entry<K, V>> iterator() {
            return new HashIterator<Map.Entry<K, V>>() {
                @Override
                public Map.Entry<K, V> next() {
                    return nextEntry();
                }
            };
        }

        @Override
        public int size() {
            return HashMap.this.size();
        }

        @Override
        public void clear() {
            HashMap.this.clear();
        }
    };
}


问:
Does the constraint or its anchors reference items in different view hierarchies? That's illegal
I am trying to create UIButtons programmatically with constraints. it should create buttons on basis of items in array.

I have taken UIView outlets as a viewSingle and given leading, bottom ,trailing and height constraints in storyboard.

Now, when I am trying to constraint the UIButton programmatically it gives below mentioned error.

```<code>for (index,item) in (self.planModel.plan_settings?.sticky_buttons?.enumerated())!{

        var btnOne = UIButton()
        var btnSecond = UIButton()
        var btnThird = UIButton()

        let totalItems = self.planModel.plan_settings?.sticky_buttons?.count ?? 1

        let multiplier = (UIScreen.main.bounds.width / CGFloat(totalItems)) / UIScreen.main.bounds.width
        switch index {
        case 0:
            btnOne = UIButton(type: UIButtonType.system)
            btnOne.backgroundColor = UIColor.green
            viewSingle.addSubview(btnOne)

            btnOne.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnOne.leadingAnchor.constraint(equalTo: viewSingle.leadingAnchor, constant: 0),
                btnOne.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnOne.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnOne.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()
        case 1:
            btnSecond = UIButton(type: UIButtonType.system)
            btnSecond.backgroundColor = UIColor.yellow
            viewSingle.addSubview(btnSecond)

            btnSecond.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnSecond.leadingAnchor.constraint(equalTo: btnOne.leadingAnchor, constant: 0),
                btnSecond.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnSecond.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnSecond.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()

        case 2:
            btnThird = UIButton(type: UIButtonType.system)
            btnThird.backgroundColor = UIColor.orange
            viewSingle.addSubview(btnThird)

            btnThird.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnThird.leadingAnchor.constraint(equalTo: viewSingle.leadingAnchor, constant: 0),
                btnThird.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnThird.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnThird.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()
        default:
            break
        }

    }
</code>```

Error:-

2017-12-06 19:16:03.601661+0530 WayOL[8637:3028327] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors  and  because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

Can anyone help me to resolve this?

答:
Your main issue is that you are creating NEW buttons each time through the loop:

```<code>for (index,item) in (self.planModel.plan_settings?.sticky_buttons?.enumerated())!{

        var btnOne = UIButton()
        var btnSecond = UIButton()
        var btnThird = UIButton()

        // rest of code inside loop
}
</code>```

So, the first time through the loop, index equals 0, and you add btnOne as a subview of viewSingle.

The next time through the loop, you create a new btnOne -- then you add btnSecond to viewSingle and try to constrain it to the new btnOne, which hasn't been added to viewSingle.

If you create your 3 button vars outside the loop - such as the same level where you create viewSingle, then remove any = UIButton(...) statements from inside the loop, you won't get that error.

Not sure if your overall totalItems and multiplier calculations and the rest of your constraints will actually do what you want though. You may need to re-think your approach (you haven't shown / explained what you're going for, so tough to say).

Body:
I am trying to create UIButtons programmatically with constraints. it should create buttons on basis of items in array.

I have taken UIView outlets as a viewSingle and given leading, bottom ,trailing and height constraints in storyboard.

Now, when I am trying to constraint the UIButton programmatically it gives below mentioned error.

for (index,item) in (self.planModel.plan_settings?.sticky_buttons?.enumerated())!{

        var btnOne = UIButton()
        var btnSecond = UIButton()
        var btnThird = UIButton()

        let totalItems = self.planModel.plan_settings?.sticky_buttons?.count ?? 1

        let multiplier = (UIScreen.main.bounds.width / CGFloat(totalItems)) / UIScreen.main.bounds.width
        switch index {
        case 0:
            btnOne = UIButton(type: UIButtonType.system)
            btnOne.backgroundColor = UIColor.green
            viewSingle.addSubview(btnOne)

            btnOne.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnOne.leadingAnchor.constraint(equalTo: viewSingle.leadingAnchor, constant: 0),
                btnOne.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnOne.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnOne.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()
        case 1:
            btnSecond = UIButton(type: UIButtonType.system)
            btnSecond.backgroundColor = UIColor.yellow
            viewSingle.addSubview(btnSecond)

            btnSecond.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnSecond.leadingAnchor.constraint(equalTo: btnOne.leadingAnchor, constant: 0),
                btnSecond.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnSecond.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnSecond.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()

        case 2:
            btnThird = UIButton(type: UIButtonType.system)
            btnThird.backgroundColor = UIColor.orange
            viewSingle.addSubview(btnThird)

            btnThird.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                btnThird.leadingAnchor.constraint(equalTo: viewSingle.leadingAnchor, constant: 0),
                btnThird.topAnchor.constraint(equalTo: viewSingle.topAnchor, constant: 0),
                // button.widthAnchor.constraint(equalTo: viewSingle!.widthAnchor, constant: 0),
                btnThird.heightAnchor.constraint(equalTo: viewSingle!.heightAnchor, constant: 0),
                btnThird.widthAnchor.constraint(equalTo: viewSingle.widthAnchor, multiplier: multiplier, constant: 0)
                ])
            self.view.layoutIfNeeded()
        default:
            break
        }

    }

Error:-

2017-12-06 19:16:03.601661+0530 WayOL[8637:3028327] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors  and  because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

Can anyone help me to resolve this?

Body:
Your main issue is that you are creating NEW buttons each time through the loop:

for (index,item) in (self.planModel.plan_settings?.sticky_buttons?.enumerated())!{

        var btnOne = UIButton()
        var btnSecond = UIButton()
        var btnThird = UIButton()

        // rest of code inside loop
}

So, the first time through the loop, index equals 0, and you add btnOne as a subview of viewSingle.

The next time through the loop, you create a new btnOne -- then you add btnSecond to viewSingle and try to constrain it to the new btnOne, which hasn't been added to viewSingle.

If you create your 3 button vars outside the loop - such as the same level where you create viewSingle, then remove any = UIButton(...) statements from inside the loop, you won't get that error.

Not sure if your overall totalItems and multiplier calculations and the rest of your constraints will actually do what you want though. You may need to re-think your approach (you haven't shown / explained what you're going for, so tough to say).


问:
UWP LogicalTreeViewHelper
I'm trying to convert an library from wpf to uwp.
I'm almost done but now there is the LogicalTreeViewHelper which doesn't exist in UWP anymore.

does anyone know how to replace it in uwp?

```<code>var parent = LogicalTreeHelper.GetParent(MyDependencyObject);
</code>```

答:
You can also try using the UWP Toolkit to get some handy extensions for traversing the Visual Tree (Microsoft.Toolkit.Uwp.UI nuget package)

https://github.com/Microsoft/UWPCommunityToolkit

Title: UWP LogicalTreeViewHelper

Body:
I'm trying to convert an library from wpf to uwp.
I'm almost done but now there is the LogicalTreeViewHelper which doesn't exist in UWP anymore.

does anyone know how to replace it in uwp?

var parent = LogicalTreeHelper.GetParent(MyDependencyObject);


问:
Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart
I am trying to figure out a way to get the product ids of items that have their quantity reduced to 0 from the cart page.

I hook into the after woocommerce_after_cart_item_quantity_update which fires if user changes quantity to anything BUT 0. :(

```<code>function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
    var_error_log([$cart_item_key, $quantity, $old_quantity]);
};

add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );

function var_error_log( $object=null ){
    ob_start();                    // start buffer capture
    var_dump( $object );           // dump the values
    $contents = ob_get_contents(); // put the buffer into a variable
    ob_end_clean();                // end capture
    error_log( $contents );        // log contents of the result of var_dump( $object )
}
</code>```

Is there another way?

Edit:

Also the woocommerce_cart_item_removed hook is no good as it only runs when user clicks remove button, not when quantity for that item is changed to 0.

And the woocommerce_cart_item_removed hook occurs in a similar way to the woocommerce_cart_item_removed hook.

答:
There is a seperate hook for this occurrence:

woocommerce_before_cart_item_quantity_zero

```<code>function woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45($cart_item_key) {
    global $woocommerce;
    $cart_item = $woocommerce->cart->get_cart_item( $cart_item_key );
    $product_id = $cart_item['product_id'];
}
add_action( 'woocommerce_before_cart_item_quantity_zero', 'woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45' );
</code>```

Body:
I am trying to figure out a way to get the product ids of items that have their quantity reduced to 0 from the cart page.

I hook into the after woocommerce_after_cart_item_quantity_update which fires if user changes quantity to anything BUT 0. :(

function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
    var_error_log([$cart_item_key, $quantity, $old_quantity]);
};

add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );

function var_error_log( $object=null ){
    ob_start();                    // start buffer capture
    var_dump( $object );           // dump the values
    $contents = ob_get_contents(); // put the buffer into a variable
    ob_end_clean();                // end capture
    error_log( $contents );        // log contents of the result of var_dump( $object )
}

Is there another way?

Edit:

Also the woocommerce_cart_item_removed hook is no good as it only runs when user clicks remove button, not when quantity for that item is changed to 0.

And the woocommerce_cart_item_removed hook occurs in a similar way to the woocommerce_cart_item_removed hook.

Body:
There is a seperate hook for this occurrence:

woocommerce_before_cart_item_quantity_zero

function woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45($cart_item_key) {
    global $woocommerce;
    $cart_item = $woocommerce->cart->get_cart_item( $cart_item_key );
    $product_id = $cart_item['product_id'];
}
add_action( 'woocommerce_before_cart_item_quantity_zero', 'woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45' );


问:
end daemon processes with multiprocessing module
I include an example usage of multiprocessing below. This is a process pool model. It is not as simple as it might be, but is relatively close in structure to the code I'm actually using. It also uses sqlalchemy, sorry.

My question is - I currently have a situation where I have a relatively long running Python script which is executing a number of functions which each look like the code below, so the parent process is the same in all cases. In other words, multiple pools are created by one python script. (I don't have to do it this way, I suppose, but the alternative is to use something like os.system and subprocess.) The problem is that these processes hang around and hold on to memory. The docs say these daemon processes are supposed to stick around till the parent process exits, but what about if the parent process then goes on to generate another pool or processes and doesn't exit immediately.

Calling terminate() works, but this doesn't seem terribly polite. Is there a good way to ask the processes to terminate nicely? I.e. clean up after yourself and go away now, I need to start up the next pool?

I also tried calling join() on the processes. According to the documentation this means wait for the processes to terminate. What if they don't plan to terminate? What actually happens is that the process hangs.

Thanks in advance.

Regards, Faheem.

```<code>import multiprocessing, time

class Worker(multiprocessing.Process):
    """Process executing tasks from a given tasks queue"""
    def __init__(self, queue, num):
        multiprocessing.Process.__init__(self)
        self.num = num
        self.queue = queue
        self.daemon = True

    def run(self):
        import traceback
        while True:
            func, args, kargs = self.queue.get()
            try:
                print "trying %s with args %s"%(func.__name__, args)
                func(*args, **kargs)
            except:
                traceback.print_exc()
            self.queue.task_done()

class ProcessPool:
    """Pool of threads consuming tasks from a queue"""
    def __init__(self, num_threads):
        self.queue = multiprocessing.JoinableQueue()
        self.workerlist = []
        self.num = num_threads
        for i in range(num_threads):
            self.workerlist.append(Worker(self.queue, i))

    def add_task(self, func, *args, **kargs):
        """Add a task to the queue"""
        self.queue.put((func, args, kargs))

    def start(self):
        for w in self.workerlist:
            w.start()

    def wait_completion(self):
        """Wait for completion of all the tasks in the queue"""
        self.queue.join()
        for worker in self.workerlist:
            print worker.__dict__
            #worker.terminate()        <--- terminate used here
            worker.join()              <--- join used here

start = time.time()

from sqlalchemy import *
from sqlalchemy.orm import *

dbuser = ''
password = ''
dbname = ''
dbstring = "postgres://%s:%s@localhost:5432/%s"%(dbuser, password, dbname)
db = create_engine(dbstring, echo=True)
m = MetaData(db)

def make_foo(i):
    t1 = Table('foo%s'%i, m, Column('a', Integer, primary_key=True))

conn = db.connect()
for i in range(10):
    conn.execute("DROP TABLE IF EXISTS foo%s"%i)
conn.close()

for i in range(10):
    make_foo(i)

m.create_all()

def do(i, dbstring):
    dbstring = "postgres://%s:%s@localhost:5432/%s"%(dbuser, password, dbname)
    db = create_engine(dbstring, echo=True)
    Session = scoped_session(sessionmaker())
    Session.configure(bind=db)
    Session.execute("ALTER TABLE foo%s SET ( autovacuum_enabled = false );"%i)
    Session.execute("ALTER TABLE foo%s SET ( autovacuum_enabled = true );"%i)
    Session.commit()

pool = ProcessPool(5)
for i in range(10):
    pool.add_task(do, i, dbstring)
pool.start()
pool.wait_completion()
</code>```

答:
My way of dealing with this was:

```<code>import multiprocessing

for prc in multiprocessing.active_children():
    prc.terminate()
</code>```

I like this more so I don't have to pollute the worker function with some if clause.

Body:
I include an example usage of multiprocessing below. This is a process pool model. It is not as simple as it might be, but is relatively close in structure to the code I'm actually using. It also uses sqlalchemy, sorry.

My question is - I currently have a situation where I have a relatively long running Python script which is executing a number of functions which each look like the code below, so the parent process is the same in all cases. In other words, multiple pools are created by one python script. (I don't have to do it this way, I suppose, but the alternative is to use something like os.system and subprocess.) The problem is that these processes hang around and hold on to memory. The docs say these daemon processes are supposed to stick around till the parent process exits, but what about if the parent process then goes on to generate another pool or processes and doesn't exit immediately.

Calling terminate() works, but this doesn't seem terribly polite. Is there a good way to ask the processes to terminate nicely? I.e. clean up after yourself and go away now, I need to start up the next pool?

I also tried calling join() on the processes. According to the documentation this means wait for the processes to terminate. What if they don't plan to terminate? What actually happens is that the process hangs.

Thanks in advance.

Regards, Faheem.

import multiprocessing, time

class Worker(multiprocessing.Process):
    """Process executing tasks from a given tasks queue"""
    def __init__(self, queue, num):
        multiprocessing.Process.__init__(self)
        self.num = num
        self.queue = queue
        self.daemon = True

    def run(self):
        import traceback
        while True:
            func, args, kargs = self.queue.get()
            try:
                print "trying %s with args %s"%(func.__name__, args)
                func(*args, **kargs)
            except:
                traceback.print_exc()
            self.queue.task_done()

class ProcessPool:
    """Pool of threads consuming tasks from a queue"""
    def __init__(self, num_threads):
        self.queue = multiprocessing.JoinableQueue()
        self.workerlist = []
        self.num = num_threads
        for i in range(num_threads):
            self.workerlist.append(Worker(self.queue, i))

    def add_task(self, func, *args, **kargs):
        """Add a task to the queue"""
        self.queue.put((func, args, kargs))

    def start(self):
        for w in self.workerlist:
            w.start()

    def wait_completion(self):
        """Wait for completion of all the tasks in the queue"""
        self.queue.join()
        for worker in self.workerlist:
            print worker.__dict__
            #worker.terminate()        <--- terminate used here
            worker.join()              <--- join used here

start = time.time()

from sqlalchemy import *
from sqlalchemy.orm import *

dbuser = ''
password = ''
dbname = ''
dbstring = "postgres://%s:%s@localhost:5432/%s"%(dbuser, password, dbname)
db = create_engine(dbstring, echo=True)
m = MetaData(db)

def make_foo(i):
    t1 = Table('foo%s'%i, m, Column('a', Integer, primary_key=True))

conn = db.connect()
for i in range(10):
    conn.execute("DROP TABLE IF EXISTS foo%s"%i)
conn.close()

for i in range(10):
    make_foo(i)

m.create_all()

def do(i, dbstring):
    dbstring = "postgres://%s:%s@localhost:5432/%s"%(dbuser, password, dbname)
    db = create_engine(dbstring, echo=True)
    Session = scoped_session(sessionmaker())
    Session.configure(bind=db)
    Session.execute("ALTER TABLE foo%s SET ( autovacuum_enabled = false );"%i)
    Session.execute("ALTER TABLE foo%s SET ( autovacuum_enabled = true );"%i)
    Session.commit()

pool = ProcessPool(5)
for i in range(10):
    pool.add_task(do, i, dbstring)
pool.start()
pool.wait_completion()

Body:
My way of dealing with this was:

import multiprocessing

for prc in multiprocessing.active_children():
    prc.terminate()

I like this more so I don't have to pollute the worker function with some if clause.


问:
Linux backup script won't run
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

```<code>TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/
</code>```

The cronjob is;

```<code>30 7 * * * /home/centos/backupfile/runbackup
</code>```

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?

答: Try setting the keys as environment variables AWS_ACCESS_KEY_ID (your AWS access key) and AWS_SECRET_ACCESS_KEY (your AWS secret key) in the beginning of your script.</p>

Title: Linux backup script won't run

Body:
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/

The cronjob is;

30 7 * * * /home/centos/backupfile/runbackup

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?


问:
Does creating a column name with brackets actually insert brackets in the column name?
For example if I create a table like this:

```<code>CREATE TABLE FIREARM_BUILD
(
    [SCOPE] VARCHAR(max)
);
</code>```

Do the brackets actually result in a column named [SCOPE]?

Edit: I believe my question is not a duplicate because the question in "question" does not explicitly answer what I'm asking.

答:
I typically include brackets in field and type name definitions because when you script out an object that's what SSMS does, and it's easier to add a few than change a lot if you're aiming for consistency. If you're building an object name dynamically, such as below, you should probably include brackets because you don't really know that the underlying table/schema name is legal. That's obviously why SSMS does it as well.

```<code>declare @object [NVARCHAR](1000) = QUOTENAME(OBJECT_SCHEMA_NAME(@@PROCID)) + N'.' + QUOTENAME(OBJECT_NAME(@@PROCID));
</code>```

For the procedure [dbo].[Get Monthly Report] this results in a value for @object of N'[dbo].[Get Monthly Report]'. Had you not bracketed the names using QUOTENAME this would result in a value for @object of N'dbo.Get Monthly Report'. In certain scenario, such as dynamic sql, the second would fail.

Body:
For example if I create a table like this:

CREATE TABLE FIREARM_BUILD
(
    [SCOPE] VARCHAR(max)
);

Do the brackets actually result in a column named [SCOPE]?

Edit: I believe my question is not a duplicate because the question in "question" does not explicitly answer what I'm asking.

Body:
I typically include brackets in field and type name definitions because when you script out an object that's what SSMS does, and it's easier to add a few than change a lot if you're aiming for consistency. If you're building an object name dynamically, such as below, you should probably include brackets because you don't really know that the underlying table/schema name is legal. That's obviously why SSMS does it as well.

declare @object [NVARCHAR](1000) = QUOTENAME(OBJECT_SCHEMA_NAME(@@PROCID)) + N'.' + QUOTENAME(OBJECT_NAME(@@PROCID));

For the procedure [dbo].[Get Monthly Report] this results in a value for @object of N'[dbo].[Get Monthly Report]'. Had you not bracketed the names using QUOTENAME this would result in a value for @object of N'dbo.Get Monthly Report'. In certain scenario, such as dynamic sql, the second would fail.


问:
Centimeter to pixel
How do I convert centimeter to pixel in c# ?</p>

答:
You can use the DpiX and DpiY properties of the Graphics object on which you're
drawing (which you must have, since conversion is meaningless in the absence of a
graphics context of some kind.)

In DpiX and DpiY, the "D" stands for
"dots" or pixels, while the "i" stands for "inches". So, it will
convert pixels to inches. Then all you have to do is convert inches to
centimeters => (x * 2.54)

Also if you want to be more "precise", have a look at the following:
HOWTO: How to Make an Application Display Real Units of Measurement

Title: Centimeter to pixel


问:
Merge k sorted arrays - comparing two solutions
If I have K sorted arrays of N elements each, e.g.

```<code>[0, 1, 2]
[1, 6, 8]
[10, 11, 12]
</code>```

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?

答:
The first method is fine when you have enough memory to perform the sorting of all the input lists, but it'd be even simpler to just perform a k-way merge between the already-sorted lists, with a bit of extra space (a list of K elements) for keeping track of the index where you're at each input list. That's an O(K^2 * N) solution.

Which is better - the first method or the k-way merge, depends on how big is K compared to N, and let's not forget the O(KN) cost of building a heap for the first method. To give an idea:

```<code>k=5; n=100
k*n*log(k*n)
=> 3107
k*k*n
=> 2500

k=100; n=100
k*n*log(k*n)
=> 92103
k*k*n
=> 1000000
</code>```

The second method uses less memory, and that's very important! it's the way to go when the input lists don't fit in memory - hence we'd take one element from each list, put it in the heap, determine the next one that goes into the final result, and write it to the output, updating the heap accordingly: that's O(KN * log(K)) in complexity. Again, to give an idea:

```<code>k=5; n=100
k*n*log(k)
=> 804

k=100; n=100
k*n*log(k)
=> 46051
</code>```

Bottom line: Use a k-way merge instead of the first method when the input fits in memory and k is small, and as @btilly points out, the second method is theoretically the best of them all, but practical considerations might make a k-way merge faster. As usual: the best strategy is to profile with some real data, and pick the winner!

Body:
If I have K sorted arrays of N elements each, e.g.

[0, 1, 2]
[1, 6, 8]
[10, 11, 12]

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?

Body:
The first method is fine when you have enough memory to perform the sorting of all the input lists, but it'd be even simpler to just perform a k-way merge between the already-sorted lists, with a bit of extra space (a list of K elements) for keeping track of the index where you're at each input list. That's an O(K^2 * N) solution.

Which is better - the first method or the k-way merge, depends on how big is K compared to N, and let's not forget the O(KN) cost of building a heap for the first method. To give an idea:

k=5; n=100
k*n*log(k*n)
=> 3107
k*k*n
=> 2500

k=100; n=100
k*n*log(k*n)
=> 92103
k*k*n
=> 1000000

The second method uses less memory, and that's very important! it's the way to go when the input lists don't fit in memory - hence we'd take one element from each list, put it in the heap, determine the next one that goes into the final result, and write it to the output, updating the heap accordingly: that's O(KN * log(K)) in complexity. Again, to give an idea:

k=5; n=100
k*n*log(k)
=> 804

k=100; n=100
k*n*log(k)
=> 46051

Bottom line: Use a k-way merge instead of the first method when the input fits in memory and k is small, and as @btilly points out, the second method is theoretically the best of them all, but practical considerations might make a k-way merge faster. As usual: the best strategy is to profile with some real data, and pick the winner!


问:
Not able to click on first element in the table through Java selenium
I have to click on first link in the table.
Not able to click the link, it's id and xpath is changing when a new record is created as follows :

```<code>Action  Exception Number
Edit | Del  EX-0000529

Edit | Del  EX-0000528

Edit | Del  EX-0000527

Edit | Del  EX-0000526

Edit | Del  EX-0000525
</code>```

HTML is as follows :

```<code> <td class="x-grid3-col x-grid3-cell x-grid3-td-NAME " tabindex="0"
 style="width:251px;">
 <div id="a3h290000001fC6_NAME" class="x-grid3-cell-inner x-grid3-col-NAME">
 <a href="/a3h290000001fC6">
 <span>EX-0000529</span>
 </a>
 </div>
 </td>
 <td class="x-grid3-col x-grid3-cell x-grid3-td-NAME " tabindex="0"
  style="width:251px;">
  <div id="a3h290000001f9v_NAME" class="x-grid3-cell-inner x-grid3-col-
  NAME">
  <a href="/a3h290000001f9v">
  <span>EX-0000528</span>
  </a>
  </div>
  </td>
</code>```

答:
The provided html shows the table element you want to click is having a link. So First get all the links and then you can click on your desired link by index.

below is the sample code yo can workwith.

```<code>java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println(links.size());
for (WebElement elem : links)
{
    elem.click();
}
</code>```

If you just want to click on the first link then just use below line instead of for loop.

```<code>links.get(0).click();
</code>```

Body:
I have to click on first link in the table.
Not able to click the link, it's id and xpath is changing when a new record is created as follows :

Action  Exception Number
Edit | Del  EX-0000529

Edit | Del  EX-0000528

Edit | Del  EX-0000527

Edit | Del  EX-0000526

Edit | Del  EX-0000525

HTML is as follows :

 EX-0000529

  EX-0000528

Body:
The provided html shows the table element you want to click is having a link. So First get all the links and then you can click on your desired link by index.

below is the sample code yo can workwith.

java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println(links.size());
for (WebElement elem : links)
{
    elem.click();
}

If you just want to click on the first link then just use below line instead of for loop.

links.get(0).click();


问:
How to protect AWS API gateway URL from unauthorized access?
I want to host my static website in AWS  S3. But it contains "contact us" page which is for sending emails. When the user clicks the submit button it sends the request to AWS API gateway, API gateway triggers the lambda function; the lambda function sends the mail to Admin.

But it has some problem . when we host the website at server we can use captcha to prevent the submit request automation and fraudulent activities . in this case the anybody can misuse (sending more request by passing a query string in the URL ) my API gateway URL who know it.

So my question is how to know that the submit request is requested from my website only and is there any way to use instead of Captcha?.

答:
Googles reCAPTCHA looks fairly simple to integrate -

https://developers.google.com/recaptcha/intro
which breaks into -

Validate user with captcha (https://developers.google.com/recaptcha/docs/display)

Validate the response (https://developers.google.com/recaptcha/docs/verify)

This can easily be achieved with API gateway endpoints and lambda (your secret will be in lambda [Maybe as env variable], site key will go in s3 static site)

Anyway why not design your own verification mechanism (If you really want to do stuff yourself :))? Ask for users phone number before letting them submit (or on submit..). Then invoke a API gateway endpoint which gets this number and sends an otp via SNS. Once user verifies this otp (another api gateway call) then only send the admin email (do further processing). You can store this otp is some rds with validated boolean flag. You don't have to worry about these API gateway endpoints since they are really for authentication only and are scaled automatically with cloud front.


问:
AndroidManifest.xml does not have the right value
I'm trying to display GoogleMaps inside a nested fragment:

```<code>    // inflate and return the layout
    View v = inflater.inflate(R.layout.fragment_nearby_map, container, false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
</code>```

But I'm getting an exception that seem to have to do with the play service version somehow as can be seen from the exception: Expected 7095000 but found 4323000

```<code>04-19 17:20:20.841  20612-20612/com.mahlzeit E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mahlzeit, PID: 20612
    java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 7095000 but found 4323000.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            at com.google.android.gms.common.GooglePlayServicesUtil.zzJ(Unknown Source)
            at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
            at com.google.android.gms.maps.internal.zzx.zzad(Unknown Source)
</code>```

I'm not sure what I have to do here since the version.xml file does contain the value 7095000:

version.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="google_play_services_version">7095000</integer>
</resources>
</code>```

AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@drawable/ic_app"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key" />

    <activity> <!-- ... -->
</code>```

答: Try to find that if there is any another 'version.xml' file available and in that file replace 4323000(which value you got in error) to 7095000(which value you got in error).

Body:
I'm trying to display GoogleMaps inside a nested fragment:

    // inflate and return the layout
    View v = inflater.inflate(R.layout.fragment_nearby_map, container, false);
    mMapView = (MapView) v.findViewById(R.id.mapView);

But I'm getting an exception that seem to have to do with the play service version somehow as can be seen from the exception: Expected 7095000 but found 4323000

04-19 17:20:20.841  20612-20612/com.mahlzeit E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mahlzeit, PID: 20612
    java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 7095000 but found 4323000.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            at com.google.android.gms.common.GooglePlayServicesUtil.zzJ(Unknown Source)
            at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
            at com.google.android.gms.maps.internal.zzx.zzad(Unknown Source)

I'm not sure what I have to do here since the version.xml file does contain the value 7095000:

version.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="google_play_services_version">7095000</integer>
</resources>

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_app"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key" />

    <activity>


问:
How to bind a control to an element of a XmlDocument in the ViewModel (MVVM Pattern)?
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

```<code><Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>
</code>```

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

```<code><XmlDataProvider x:Key="data" Source="Books.xml"/>
</code>```

And here's how I'm binding to the xml file.

```<code><TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />
</code>```

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

```<code>public XmlDocument Books { get; set; }
</code>```

And here's the syntax that I'm using to bind to ViewModel:

```<code><TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />
</code>```

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.

答:
ColinE has completely answered the question. But the other solution consists in exposing property BookName. </p>

```<code>public class ViewModel
{
    public ViewModel(XDocument doc)
    {
        this.Document = doc;
    }

    private XDocument Document
    {
        get;
        set;
    }

    public string BookName
    {
        get
        {
            return this.Document
                       .Element("Books")
                       .Element("Book")
                       .Attribute("Name").Value;
        }
    }
</code>```

<p>Then you should bind directly to Name property: </p>

```<code><TextBlock Text="{Binding BookName}" />
</code>```

Body:
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

<Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

<XmlDataProvider x:Key="data" Source="Books.xml"/>

And here's how I'm binding to the xml file.

<TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

public XmlDocument Books { get; set; }

And here's the syntax that I'm using to bind to ViewModel:

<TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.

Body:
ColinE has completely answered the question. But the other solution consists in exposing property BookName.

public class ViewModel
{
    public ViewModel(XDocument doc)
    {
        this.Document = doc;
    }

    private XDocument Document
    {
        get;
        set;
    }

    public string BookName
    {
        get
        {
            return this.Document
                       .Element("Books")
                       .Element("Book")
                       .Attribute("Name").Value;
        }
    }

Then you should bind directly to Name property:

<TextBlock Text="{Binding BookName}" />


问:
AEM 6.2 How to change template of a page
I have created live copy of a page branch from sample website, inside my website. I was just trying to update the template so that I can create a local copy of the template used with original page and then change the UI. I can see the property with the cq:template and sling:resourceType as component name in development environment(CRXDE Lite). Can anyone suggest if we can update the property to change the template and component or if there any other way to change the template.

答:
You can update cq:template and sling:resourceType on page/jcr:content node with corresponding new values and it would effectively change the template of page.

you might run into errors if code on new page component is expecting a different content than what is currently under your jcr:content.

ps- I dont know what your use case is but this would be  very crude approach and should be avoided.


问:
Convert a date to intervals of time
I have a column in my data.frame that is formatted as date ("2006-03-09 17:00:00") and I want a new column that gives me ranges like "morning", "afternoon", "evening". I am trying the following without success:

```<code>mydf <- mydf %>%
        mutate (dateInterval = ifelse (data < "13:00", "morning",
                               ifelse (data > "18:00", "evening", "afternoon")))
</code>```

Title: Convert a date to intervals of time

Body:
I have a column in my data.frame that is formatted as date ("2006-03-09 17:00:00") and I want a new column that gives me ranges like "morning", "afternoon", "evening". I am trying the following without success:

mydf <- mydf %>%
        mutate (dateInterval = ifelse (data < "13:00", "morning",
                               ifelse (data > "18:00", "evening", "afternoon")))

Body:
## Building your datetime data
datetime <- c("2006-03-09 17:00:00", "2006-03-09 19:00:00", "2006-03-09 10:00:00", "2006-03-09 22:00:00")

hour <- as.integer(substr(datetime, 12, 13))
df <- data.frame(datetime=datetime, hour=hour, dateInterval=cut(hour, c(0, 7, 10, 12, 18, 24), labels=c("night", "morning", "noon", "afternoon", "evening")))

df
#             datetime   hour  dateInterval
#1 2006-03-09 17:00:00    17      afternoon
#2 2006-03-09 19:00:00    19        evening
#3 2006-03-09 10:00:00    10        morning
#4 2006-03-09 22:00:00    22        evening


问:
sed replace spaces in directory names
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

```<code>cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done
</code>```

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

答:
sed is versatile but I suggest you use a more specialised tool such as rename:

```<code>rename 's/ /-/g' "$directory"
</code>```

Also you're very likely to try and rename already renamed directories (and thus no longer existing). I suggest you use find options -depth (depth first) and -execdir (execute command inside directory, to avoid affecting parent directories):

```<code>find foo -depth -type d -execdir rename 's/ /-/g' {} +
</code>```

Title: sed replace spaces in directory names

Body:
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

Body:
sed is versatile but I suggest you use a more specialised tool such as rename:

rename 's/ /-/g' "$directory"

Also you're very likely to try and rename already renamed directories (and thus no longer existing). I suggest you use find options -depth (depth first) and -execdir (execute command inside directory, to avoid affecting parent directories):

find foo -depth -type d -execdir rename 's/ /-/g' {} +