问:
Add unique constraint and deduplicate column data
I am working on a Spring project which uses PostgreSQL and Liquibase. I need to add a unique constraint to a specific column in a table. The table already has a lot of entries and some of them violate the new unique constraint.

Since the application is in production, dropping the table is not an option. I need to implement some sort of modification to the data in the column, so that duplicates get indexed (e.g. we have 2 entries with the value 'foo', after the operation these entries should look something like 'foo' and 'foo2').

So far I've only implemented the change which adds the unique constraint, but I have yet to implement this modification. Is there any functionality in either PostgreSQL or Liquibase which might address this issue?

答:
You need to create an SQL UPDATE query (or queries) that will modify the database and implement the logic that updates duplicates and sets unique values to them.

Then use change type sql in liquibase to instruct liquibase to run that query.


来源: stackexchange

问:
Generate the SVG with constant size by python-qrcode
I am working for an app, which will generate the SVG file. I am using python-qrcode. But the problem is that this generates the SVG file with the size of depending on string size.

```<code>import qrcode
import qrcode.image.svg

currentTime = str(datetime.datetime.now())
getfileName = currentTime.replace(':', '_').replace(' ', '_')

fileName = "qrcodes/" + getfileName + '.svg'

url = 'https://stackoverflow.com'
img = qrcode.make( url, image_factory=qrcode.image.svg.SvgImage)
img.save( fileName )
</code>```

Now if you try long string in URL. then the image of size will be large than the current one.

I want to the SVG file with constant size.

答:
You can control the number of pixels in the QR code using the version parameter to the make function. From the docs:

The version parameter is an integer from 1 to 40 that controls the
  size of the QR Code.

So in your case, you can do:

```<code>img = qrcode.make( url, image_factory=qrcode.image.svg.SvgImage, version=10)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working for an app, which will generate the SVG file. I am using python-qrcode. But the problem is that this generates the SVG file with the size of depending on string size.

import qrcode
import qrcode.image.svg

currentTime = str(datetime.datetime.now())
getfileName = currentTime.replace(':', '_').replace(' ', '_')

fileName = "qrcodes/" + getfileName + '.svg'

url = 'https://stackoverflow.com'
img = qrcode.make( url, image_factory=qrcode.image.svg.SvgImage)
img.save( fileName )

Now if you try long string in URL. then the image of size will be large than the current one.

I want to the SVG file with constant size.

Body:
You can control the number of pixels in the QR code using the version parameter to the make function. From the docs:

The version parameter is an integer from 1 to 40 that controls the
  size of the QR Code.

So in your case, you can do:

img = qrcode.make( url, image_factory=qrcode.image.svg.SvgImage, version=10)


问:
Admin application not starting up
I have below spring boot  dependency :

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
</code>```

and admin dependency

```<code><dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.1.0</version>
</dependency>
</code>```

At startup Application is failing with below error :

```<code>An attempt was made to call the method reactor.retry.Retry.retryMax(J)Lreactor/retry/Retry; but it does not exist. Its class, reactor.retry.Retry, is available from the following locations:

    jar:file:/C:/Users/313158/.m2/repository/io/projectreactor/addons/reactor-extra/3.1.7.RELEASE/reactor-extra-3.1.7.RELEASE.jar!/reactor/retry/Retry.class

It was loaded from the following location:

    file:/C:/Users/313158/.m2/repository/io/projectreactor/addons/reactor-extra/3.1.7.RELEASE/reactor-extra-3.1.7.RELEASE.jar
</code>```

Action:

Correct the classpath of your application so that it contains a single, compatible version of reactor.retry.Retry

Note :After Updating version of spring and admin to 2.1.4 ,getting different errors

Are there any other dependencies required to start admin application

答:
Spring Boot Admin uses Spring Boot version 2.1.4.RELEASE

Update your parent to this version

Title: Admin application not starting up

Body:
I have below spring boot  dependency :

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath />
    </parent>

and admin dependency

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.1.0</version>
</dependency>

At startup Application is failing with below error :

An attempt was made to call the method reactor.retry.Retry.retryMax(J)Lreactor/retry/Retry; but it does not exist. Its class, reactor.retry.Retry, is available from the following locations:

    jar:file:/C:/Users/313158/.m2/repository/io/projectreactor/addons/reactor-extra/3.1.7.RELEASE/reactor-extra-3.1.7.RELEASE.jar!/reactor/retry/Retry.class

It was loaded from the following location:

    file:/C:/Users/313158/.m2/repository/io/projectreactor/addons/reactor-extra/3.1.7.RELEASE/reactor-extra-3.1.7.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of reactor.retry.Retry

Note :After Updating version of spring and admin to 2.1.4 ,getting different errors

Are there any other dependencies required to start admin application


问:
Using Silverlight for an entire website?
We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?

The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.

I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.

Are there any big no-nos from the experience of StackOverflowers? What are the big positives?

答: It sounds like your problem is that you need a rich-client admin application. Why not use click-once?</p>

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sam

OwnerDisplayName: Keith


问:
How to check whetherpop up blocker is turned ON or not in a browser using Code ?
How to check whether pop up blocker is turned ON or not in a browser using java or Java script Code ?

```<code>function check ()
{
    document.login.action= url+"test.jsp";
    document.login.submit();
}
</code>```

I will call this function on click of submit button

答:
If you use window.open() to open the popup, check for the return value.
According to the MDC doc center (a good javascript reference) the return value is null if opening the window didn't succeed for whatever reason.

```<code>var windowReference = window.open(url);
</code>```

See the documentation on window.open here.

ContentLicense: CC BY-SA 3.0

Body:
How to check whether pop up blocker is turned ON or not in a browser using java or Java script Code ?

function check ()
{
    document.login.action= url+"test.jsp";
    document.login.submit();
}

I will call this function on click of submit button

Body:
If you use window.open() to open the popup, check for the return value.
According to the MDC doc center (a good javascript reference) the return value is null if opening the window didn't succeed for whatever reason.

var windowReference = window.open(url);

See the documentation on window.open here.


问:
Get BarsSince() for nth occurrence instead of 1st occurrence
The function BarsSince() will return number of bars (time periods) that have passed since ARRAY was true (or 1) for the 1st occurrence of the condition true.
https://www.amibroker.com/guide/afl/barssince.html

For example, I have an array like this;

```<code>arr_test = [1 0 0 0 1 0 0 1 0 0 1 0 0];
</code>```

BarsSince(arr_test) will return 3 as that is the first occurrence of 1.

What if I want to find out the number of bars that have passed for the nth occurrence of the true condition? As illustration, I would like to have a function such that
BarsSince_N(arr_test, n=2) will return 6.

Thank you.

I am using Amibroker ver6.30.5

答:
You might want to look at Valuewhen.

So, then you can do something like:

```<code>bi = ValueWhen(arr_test > 0, BarIndex(), "nth occurence - 0 is the latest");
bars_since = LastValue(Close) - bi;
</code>```

Here, I'm just using LastValue to get the last barnumber of the entire price series. This is untested, but you should get the idea.

Body:
The function BarsSince() will return number of bars (time periods) that have passed since ARRAY was true (or 1) for the 1st occurrence of the condition true.
https://www.amibroker.com/guide/afl/barssince.html

For example, I have an array like this;

arr_test = [1 0 0 0 1 0 0 1 0 0 1 0 0];

BarsSince(arr_test) will return 3 as that is the first occurrence of 1.

What if I want to find out the number of bars that have passed for the nth occurrence of the true condition? As illustration, I would like to have a function such that
BarsSince_N(arr_test, n=2) will return 6.

Thank you.

I am using Amibroker ver6.30.5

Body:
You might want to look at Valuewhen.

So, then you can do something like:

bi = ValueWhen(arr_test > 0, BarIndex(), "nth occurence - 0 is the latest");
bars_since = LastValue(Close) - bi;

Here, I'm just using LastValue to get the last barnumber of the entire price series. This is untested, but you should get the idea.


问:
JOptionPane showMessageDialog - Un-focus 'OK' button
I am trying to create showMessageDialog that will have ONLY ONE button (i.e. OK). I want that button to be un-focused. That means when the dialog opens, is user clicks on Enter key, the dialog should not close. Use must have to click on 'OK' button then only the dialog should disappear.

But I am getting now is always the 'OK' button is focused. So when the dialog popup, and user doesn't see and press Enter key, the dialog closes.

Why I need this: This is not an error message. Only informational message that user must need to see before proceeding. And in this case the big monitors are a little far away from the users location. I have written code to make a sound when the dialog shows up, but user may not listen and hits Enter key. So I want user to see the dialog and clicks on OK button

Sample Code:

```<code>import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.awt.Color;
import java.awt.Font;

public class MessageDialogInFrame extends JFrame{

    public MessageDialogInFrame() {
        getContentPane().setBackground(Color.DARK_GRAY);
        setTitle("Message Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(400, 300);
        getContentPane().setLayout(null);
    }

    public static void main(String[] args){
        ImageIcon icon = new ImageIcon("src/images/turtle64.png");
        JTextArea commentTextArea = new JTextArea("Hello", 10, 50);
        commentTextArea.setBackground(Color.YELLOW);
        Font font = new java.awt.Font("Dialog", 0, 15);
        commentTextArea.setFont(font);
        commentTextArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(commentTextArea);
        scrollPane.setBackground(Color.YELLOW);

        JOptionPane.showMessageDialog(new MessageDialogInFrame(),
                "I appear as part of the frame!!", "Customized Dialog",
                JOptionPane.INFORMATION_MESSAGE, icon);
    }
}
</code>```

Original Code:

```<code>private static int showColoredDialog(int category, Component parentComp, String message, String title, int optionType, int messageType, Color color) {
    JTextArea commentTextArea = new JTextArea(message, 10, 50);
    commentTextArea.setBackground(color);
    commentTextArea.setFont(UiFactory.getInfo().getLabelFont());
    commentTextArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(commentTextArea);
    scrollPane.setBackground(color);

    switch (category) {
    case 0:
        JOptionPane.showMessageDialog(parentComp, scrollPane, title, messageType);
        return 0;
    case 1:
        return JOptionPane.showConfirmDialog(parentComp, scrollPane, title, optionType, messageType);
    }
    return -1;
}
</code>```

SOLUTION:

```<code>int result = JOptionPane.CLOSED_OPTION;
final JOptionPane pane = new JOptionPane(scrollPane, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_OPTION, null, new String[] {"OK"});
            JDialog dialog = pane.createDialog(null, title);
            commentTextArea.requestFocus();
            dialog.setVisible(true);
            if (pane.getValue() != null) result = JOptionPane.OK_OPTION;
            return result;
</code>```

答:
One way: create a JOptionPane object via its constructor, recursively search its component tree for the JButton, and make it non-focusable:

```<code>JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("Fubars Rule!");
optionPane.setMessageType(JOptionPane.PLAIN_MESSAGE);
optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
recursiveUnfocusButtons(optionPane);
JDialog dialog = optionPane.createDialog(null, "Option Title");
dialog.setVisible(true);
System.exit(0);
</code>```

and the magic sauce:

```<code>private static void recursiveUnfocusButtons(Component component) {
    if (component instanceof JButton) {
        component.setFocusable(false);
        return;
    } else if (component instanceof Container) {
        for (Component c : ((Container) component).getComponents()) {
            recursiveUnfocusButtons(c);
        }
    }
}
</code>```

To get rid of the enter action, you need to change the key bindings for the enter key in the JOptionPane:

```<code>import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class JOptionNoFocus {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JOptionPane optionPane = new JOptionPane();
            optionPane.setMessage("Fubars Rule!");
            optionPane.setMessageType(JOptionPane.PLAIN_MESSAGE);
            optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);

            KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            optionPane.getInputMap(JComponent.WHEN_FOCUSED).put(enterStroke, enterStroke.toString());
            optionPane.getActionMap().put(enterStroke.toString(), new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // do nothing
                }
            });

            recursiveUnfocusButtons(optionPane);
            JDialog dialog = optionPane.createDialog(null, "Option Title");
            dialog.setVisible(true);
            System.exit(0);
        });
    }

    private static void recursiveUnfocusButtons(Component component) {
        if (component instanceof JButton) {
            JButton button = (JButton) component;
            button.setFocusable(false);
            return;
        } else if (component instanceof Container) {
            for (Component c : ((Container) component).getComponents()) {
                recursiveUnfocusButtons(c);
            }
        }
    }
}
</code>```

Once you get into creating more complex dialogs though, just skip creating JDialogs and instead create your own JDialog, one with components placed where you desire. Make them modal if you want them to stop the application until dealt with.

Body:
I am trying to create showMessageDialog that will have ONLY ONE button (i.e. OK). I want that button to be un-focused. That means when the dialog opens, is user clicks on Enter key, the dialog should not close. Use must have to click on 'OK' button then only the dialog should disappear.

But I am getting now is always the 'OK' button is focused. So when the dialog popup, and user doesn't see and press Enter key, the dialog closes.

Why I need this: This is not an error message. Only informational message that user must need to see before proceeding. And in this case the big monitors are a little far away from the users location. I have written code to make a sound when the dialog shows up, but user may not listen and hits Enter key. So I want user to see the dialog and clicks on OK button

Sample Code:

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.awt.Color;
import java.awt.Font;

public class MessageDialogInFrame extends JFrame{

    public MessageDialogInFrame() {
        getContentPane().setBackground(Color.DARK_GRAY);
        setTitle("Message Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(400, 300);
        getContentPane().setLayout(null);
    }

    public static void main(String[] args){
        ImageIcon icon = new ImageIcon("src/images/turtle64.png");
        JTextArea commentTextArea = new JTextArea("Hello", 10, 50);
        commentTextArea.setBackground(Color.YELLOW);
        Font font = new java.awt.Font("Dialog", 0, 15);
        commentTextArea.setFont(font);
        commentTextArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(commentTextArea);
        scrollPane.setBackground(Color.YELLOW);

        JOptionPane.showMessageDialog(new MessageDialogInFrame(),
                "I appear as part of the frame!!", "Customized Dialog",
                JOptionPane.INFORMATION_MESSAGE, icon);
    }
}

Original Code:

private static int showColoredDialog(int category, Component parentComp, String message, String title, int optionType, int messageType, Color color) {
    JTextArea commentTextArea = new JTextArea(message, 10, 50);
    commentTextArea.setBackground(color);
    commentTextArea.setFont(UiFactory.getInfo().getLabelFont());
    commentTextArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(commentTextArea);
    scrollPane.setBackground(color);

    switch (category) {
    case 0:
        JOptionPane.showMessageDialog(parentComp, scrollPane, title, messageType);
        return 0;
    case 1:
        return JOptionPane.showConfirmDialog(parentComp, scrollPane, title, optionType, messageType);
    }
    return -1;
}

SOLUTION:

int result = JOptionPane.CLOSED_OPTION;
final JOptionPane pane = new JOptionPane(scrollPane, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_OPTION, null, new String[] {"OK"});
            JDialog dialog = pane.createDialog(null, title);
            commentTextArea.requestFocus();
            dialog.setVisible(true);
            if (pane.getValue() != null) result = JOptionPane.OK_OPTION;
            return result;

Body:
One way: create a JOptionPane object via its constructor, recursively search its component tree for the JButton, and make it non-focusable:

JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("Fubars Rule!");
optionPane.setMessageType(JOptionPane.PLAIN_MESSAGE);
optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
recursiveUnfocusButtons(optionPane);
JDialog dialog = optionPane.createDialog(null, "Option Title");
dialog.setVisible(true);
System.exit(0);

and the magic sauce:

private static void recursiveUnfocusButtons(Component component) {
    if (component instanceof JButton) {
        component.setFocusable(false);
        return;
    } else if (component instanceof Container) {
        for (Component c : ((Container) component).getComponents()) {
            recursiveUnfocusButtons(c);
        }
    }
}

To get rid of the enter action, you need to change the key bindings for the enter key in the JOptionPane:

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class JOptionNoFocus {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JOptionPane optionPane = new JOptionPane();
            optionPane.setMessage("Fubars Rule!");
            optionPane.setMessageType(JOptionPane.PLAIN_MESSAGE);
            optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);

            KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            optionPane.getInputMap(JComponent.WHEN_FOCUSED).put(enterStroke, enterStroke.toString());
            optionPane.getActionMap().put(enterStroke.toString(), new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // do nothing
                }
            });

            recursiveUnfocusButtons(optionPane);
            JDialog dialog = optionPane.createDialog(null, "Option Title");
            dialog.setVisible(true);
            System.exit(0);
        });
    }

    private static void recursiveUnfocusButtons(Component component) {
        if (component instanceof JButton) {
            JButton button = (JButton) component;
            button.setFocusable(false);
            return;
        } else if (component instanceof Container) {
            for (Component c : ((Container) component).getComponents()) {
                recursiveUnfocusButtons(c);
            }
        }
    }
}

Once you get into creating more complex dialogs though, just skip creating JDialogs and instead create your own JDialog, one with components placed where you desire. Make them modal if you want them to stop the application until dealt with.


问:
Why JavaScript implicitly stringify the parameter value when using objects as keys?
I have been studying some Javascript Interview Questions and the concept behind this specific question's answer is a bit hard to figure out. The output of the following code is 456 instead of 123 and the reason for this behavior stated as "JavaScript implicitly stringify the parameter value when Using Objects as Keys". Can anyone please explain this concept or provide me any resources to study? Thanks in advance.

var a = {};
var b = { key: "b" };
var c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]); // Output is 456```

答:
Expecting that you have defined a as an object. Now on setting b as key it will be

{"[object Object]":123} and on doing a[c] it will be {"[object Object]":456}. Object does not allow duplicate key. So the previous key value is overwritten by the latest one

let a = {};
var b = {
  key: "b"
};
var c = {
  key: "c"
};
a[b] = 123;
a[c] = 456;

console.log(a)
console.log(a[b]);```
</div>
</div>
</p>

<p>If you set another key the previous one will overwrite by the latest</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = {};
var b = {
  key: "b"
};
var c = {
  key: "c"
};

var d = {
  key: "d"
};
a[b] = 123;
a[c] = 456;
a[d] = 123;

console.log(a)
console.log(a[b]);</code>```

Body:
Expecting that you have defined a as an object. Now on setting b as key it will be

{"[object Object]":123} and on doing a[c] it will be {"[object Object]":456}. Object does not allow duplicate key. So the previous key value is overwritten by the latest one

let a = {};
var b = {
  key: "b"
};
var c = {
  key: "c"
};
a[b] = 123;
a[c] = 456;

console.log(a)
console.log(a[b]);

If you set another key the previous one will overwrite by the latest

let a = {};
var b = {
  key: "b"
};
var c = {
  key: "c"
};

var d = {
  key: "d"
};
a[b] = 123;
a[c] = 456;
a[d] = 123;

console.log(a)
console.log(a[b]);


问:
Open Select after a click on label
I'm looking for a way to open a Select (not native) component from Material UI after a click on the label with htmlFor specified.

```<code><label htmlFor='menu'>Label to open Menu</label>

<MUISelect inputProps={{id: 'menu'}} native={false}>{options}</MUISelect>
</code>```

Obviously it doesn't work

答:
There are two main aspects to this problem:

You need to get the id onto the same element that has the click-handler for opening the menu.

The element with the click-handler is a div and not an input. Labels do not automatically trigger the click event of the labelled element when it is not an input element.

The first aspect can be solved by using SelectDisplayProps:

```<code>SelectDisplayProps={{ id: "menu" }}
</code>```

The second aspect can be solved with a custom label component:

```<code>import React from "react";

const LabelForClickableDiv = ({ htmlFor, ...other }) => {
  const onClick = () => {
    document.getElementById(htmlFor).click();
  };
  return <label htmlFor={htmlFor} onClick={onClick} {...other} />;
};
export default LabelForClickableDiv;
</code>```

Here's a working example:

```<code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import LabelForClickableDiv from "./LabelForClickableDiv";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

function SimpleSelect() {
  const classes = useStyles();
  const [value, setValue] = React.useState("");

  return (
    <>
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl}>
          <LabelForClickableDiv htmlFor="menu">
            Label to open Menu
          </LabelForClickableDiv>
          <Select
            value={value}
            onChange={event => {
              setValue(event.target.value);
            }}
            SelectDisplayProps={{
              id: "menu"
            }}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </form>
    </>
  );
}

export default SimpleSelect;
</code>```

Title: Open Select after a click on label

Body:
I'm looking for a way to open a Select (not native) component from Material UI after a click on the label with htmlFor specified.

Label to open Menu

<MUISelect inputProps={{id: 'menu'}} native={false}>{options}</MUISelect>

Obviously it doesn't work

Body:
There are two main aspects to this problem:

You need to get the id onto the same element that has the click-handler for opening the menu.

The element with the click-handler is a div and not an input. Labels do not automatically trigger the click event of the labelled element when it is not an input element.

The first aspect can be solved by using SelectDisplayProps:

SelectDisplayProps={{ id: "menu" }}

The second aspect can be solved with a custom label component:

import React from "react";

const LabelForClickableDiv = ({ htmlFor, ...other }) => {
  const onClick = () => {
    document.getElementById(htmlFor).click();
  };
  return <label htmlFor={htmlFor} onClick={onClick} {...other} />;
};
export default LabelForClickableDiv;

Here's a working example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import LabelForClickableDiv from "./LabelForClickableDiv";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

function SimpleSelect() {
  const classes = useStyles();
  const [value, setValue] = React.useState("");

  return (
    <>
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl}>
          <LabelForClickableDiv htmlFor="menu">
            Label to open Menu
          </LabelForClickableDiv>
          <Select
            value={value}
            onChange={event => {
              setValue(event.target.value);
            }}
            SelectDisplayProps={{
              id: "menu"
            }}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </form>
    </>
  );
}

export default SimpleSelect;


问:
How to connect to on-premise Oracle-db using Azure Functions?
I'm trying to create an Azure Function to connect and query an on-premise Oracle-DB. I can not see that the Oracle Client or an ODBC-driver is installed on the servers to handle this.

Are there any solutions to this using JS or Python?

I have tried using the node-odbc driver, but the server is missing the Oracle client.

答:
You will need to establish a hybrid connection. see https://learn.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections

Then you can refer to this thread to establish a context:

https://social.msdn.microsoft.com/Forums/en-US/2434fe10-3219-4625-bdbf-b9e96421230b/entity-framework-with-oracle-and-sql

For a nodejs solution, I would add the NPM and install it using Kudu using node-oracledb:
https://oracle.github.io/node-oracledb/doc/api.html#getstarted

// myscript.js
// This example uses Node 8's async/await syntax.

```<code>var oracledb = require('oracledb');

var mypw = ...  // set mypw to the hr schema password

async function run() {

  let connection;

  try {
    connection = await oracledb.getConnection(  {
      user          : "hr",
      password      : mypw,
      connectString : "localhost/XEPDB1"
    });

    let result = await connection.execute(
      `SELECT manager_id, department_id, department_name
       FROM departments
       WHERE manager_id = :id`,
      [103],  // bind value for :id
    );
    console.log(result.rows);

  } catch (err) {
    console.error(err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

run();
</code>```

sample code

Body:
You will need to establish a hybrid connection. see https://learn.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections

Then you can refer to this thread to establish a context:

https://social.msdn.microsoft.com/Forums/en-US/2434fe10-3219-4625-bdbf-b9e96421230b/entity-framework-with-oracle-and-sql

For a nodejs solution, I would add the NPM and install it using Kudu using node-oracledb:
https://oracle.github.io/node-oracledb/doc/api.html#getstarted

// myscript.js
// This example uses Node 8's async/await syntax.

var oracledb = require('oracledb');

var mypw = ...  // set mypw to the hr schema password

async function run() {

  let connection;

  try {
    connection = await oracledb.getConnection(  {
      user          : "hr",
      password      : mypw,
      connectString : "localhost/XEPDB1"
    });

    let result = await connection.execute(
      `SELECT manager_id, department_id, department_name
       FROM departments
       WHERE manager_id = :id`,
      [103],  // bind value for :id
    );
    console.log(result.rows);

  } catch (err) {
    console.error(err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

run();

sample code


问:
How can I translate a typed query into a criteria builder object?
I have the following code using TypedQuery, but due to some lack of dynamic functionality with ORDER BY, I would like to transform it into a criteria builder object. Is it possible to achieve the same query with the criteria builder?

```<code>TypedQuery<User> query = this.entityManager.createQuery("SELECT u FROM User u LEFT JOIN sales s ON u.id = s.user_id AND u.username LIKE :username", User.class);

query.setParameter("username", "%" + sampleUsername.toLowerCase() + "%");
</code>```

答: Yes. Every JPQL query can be implemented with Criteria API</p>

Body:
I have the following code using TypedQuery, but due to some lack of dynamic functionality with ORDER BY, I would like to transform it into a criteria builder object. Is it possible to achieve the same query with the criteria builder?

TypedQuery<User> query = this.entityManager.createQuery("SELECT u FROM User u LEFT JOIN sales s ON u.id = s.user_id AND u.username LIKE :username", User.class);

query.setParameter("username", "%" + sampleUsername.toLowerCase() + "%");


问:
React: can I use a prop named "index"
You can see from the code blocks below that inside Description.js I had to pass down a prop named "index", because handleChange is a function that must be called with two parameters handleChange(newValue,index).

The handleChange function updates the state, which in this case, is an array if length 3 (one value for each input).

And since the index is created by the Description.js component, I had to pass that down as props.

It works as intended.

QUESTION

Is this a bad practice? Is index a reserved word somehow (of React, Javascript or HTML)?

Is there a better approach to this?

App.js

```<code>import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import Description from "./Description";

function App() {
  console.log("Rendering App...");
  const [inputValues, setInputValues] = useState(["", "", ""]);

  const handleChange = useCallback((newValue, index) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[index] = newValue;
      return aux;
    });
  }, []);

  return <Description values={inputValues} handleChange={handleChange} />;
}
</code>```

Description.js

```<code>import React from "react";
import TextInput from "./TextInput";

function Description(props) {
  console.log("Rendering Description...");
  const inputItems = props.values.map((item, index) => (
    <div key={index}>
      <div>Input {index + 1}</div>
      <TextInput value={item} handleChange={props.handleChange} index={index} />
    </div>
  ));

  return <React.Fragment>{inputItems}</React.Fragment>;
}
</code>```

TextInput.js

```<code>import React from "react";

const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.index);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.index)}
    />
  );
});

</code>```

答:
There’s nothing wrong with what you’re doing, but you can call the prop and the function argument whatever you want. It doesn’t have to be named index. They don’t even have to be the same.

You could do this and it would work exactly the same:

```<code>const handleChange = useCallback((newValue, bananas) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[bananas] = newValue;
      return aux;
    });
  }, []);
</code>```

Same with this:

```<code>const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.wookie);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.wookie)}
    />
  );
});

// and then...
<TextInput value={item} handleChange={props.handleChange} wookie={index} />

</code>```

Title: React: can I use a prop named "index"

Body:
You can see from the code blocks below that inside Description.js I had to pass down a prop named "index", because handleChange is a function that must be called with two parameters handleChange(newValue,index).

The handleChange function updates the state, which in this case, is an array if length 3 (one value for each input).

And since the index is created by the Description.js component, I had to pass that down as props.

It works as intended.

QUESTION

Is this a bad practice? Is index a reserved word somehow (of React, Javascript or HTML)?

Is there a better approach to this?

App.js

import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import Description from "./Description";

function App() {
  console.log("Rendering App...");
  const [inputValues, setInputValues] = useState(["", "", ""]);

  const handleChange = useCallback((newValue, index) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[index] = newValue;
      return aux;
    });
  }, []);

  return <Description values={inputValues} handleChange={handleChange} />;
}

Description.js

import React from "react";
import TextInput from "./TextInput";

function Description(props) {
  console.log("Rendering Description...");
  const inputItems = props.values.map((item, index) => (

Input {index + 1}

      <TextInput value={item} handleChange={props.handleChange} index={index} />

  ));

  return <React.Fragment>{inputItems}</React.Fragment>;
}

TextInput.js

import React from "react";

const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.index);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.index)}
    />
  );
});

Body:
There’s nothing wrong with what you’re doing, but you can call the prop and the function argument whatever you want. It doesn’t have to be named index. They don’t even have to be the same.

You could do this and it would work exactly the same:

const handleChange = useCallback((newValue, bananas) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[bananas] = newValue;
      return aux;
    });
  }, []);

Same with this:

const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.wookie);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.wookie)}
    />
  );
});

// and then...
<TextInput value={item} handleChange={props.handleChange} wookie={index} />


问:
iOS (swift) exit/dismiss preselect textView in share extension
when launching the iOS share extension the textView will by default already be selected / entered. (the keyboard will be visible and the textView will be in edit mode)

I don't want this to happen, how do I programatically exit the textView

```<code>override func viewDidLoad() {
  self.textView.exit() // obviously doesn't work
}
</code>```

I see tons of posts about how to exit when user press enter on the keyboard, I do not want to do it "when something delegate" I just want the textview to not be in edit mode when the extension is launched (on viewDidLoad).

I have also tried (as suggested in other post)

```<code>self.textView.endEditing(true)
</code>```

which did not hide the keyboard or exit the textView

答:
You can call textView.resignFirstResponder() in presentationAnimationDidFinish

```<code>class ShareViewController: SLComposeServiceViewController {

    var textViewTintColor: UIColor?

    override func viewDidLoad() {
        super.viewDidLoad()

        // hide cursor which appears during presentation animation
        self.textViewTintColor = self.textView.tintColor
        self.textView.tintColor = .clear
    }

    override func presentationAnimationDidFinish() {
        super.presentationAnimationDidFinish()

        guard let tintColor = self.textViewTintColor else { return }

        self.textView.resignFirstResponder()

        // reset cursor
        self.textView.tintColor = tintColor
        self.textViewTintColor = nil
    }

}
</code>```

Body:
when launching the iOS share extension the textView will by default already be selected / entered. (the keyboard will be visible and the textView will be in edit mode)

I don't want this to happen, how do I programatically exit the textView

override func viewDidLoad() {
  self.textView.exit() // obviously doesn't work
}

I see tons of posts about how to exit when user press enter on the keyboard, I do not want to do it "when something delegate" I just want the textview to not be in edit mode when the extension is launched (on viewDidLoad).

I have also tried (as suggested in other post)

self.textView.endEditing(true)

which did not hide the keyboard or exit the textView

Body:
You can call textView.resignFirstResponder() in presentationAnimationDidFinish

class ShareViewController: SLComposeServiceViewController {

    var textViewTintColor: UIColor?

    override func viewDidLoad() {
        super.viewDidLoad()

        // hide cursor which appears during presentation animation
        self.textViewTintColor = self.textView.tintColor
        self.textView.tintColor = .clear
    }

    override func presentationAnimationDidFinish() {
        super.presentationAnimationDidFinish()

        guard let tintColor = self.textViewTintColor else { return }

        self.textView.resignFirstResponder()

        // reset cursor
        self.textView.tintColor = tintColor
        self.textViewTintColor = nil
    }

}


问:
How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?
I currently have PHP 5.5.12 and Apache 2.4 installed on Windows Server 2008 R2. Everything is running perfectly with no issue/warnings.

What I have done is copied the same Apache file/configuration to another server. I copied the C:\PHP directory and then the C:\Apache24 directory and pasted them into the new server.

Then I installed the Apache with one change (ie httpd -k install.) I changed the port number from 80 to 8877. The Apache is working with no issue and it is running on the 8877 port. I can also open the default page by going to SERVER_IP_ADDRESS:8877 and it works.

But, PHP is not working as it should. In the error.log file from the Apache server I get the warning listed below

```<code>PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_ldap.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_mysqli.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_openssl.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_pdo_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_sqlsrv_55_ts.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_pdo_sqlsrv_55_ts.dll' - The specified module could not be found.\r\n in Unknown on line 0
</code>```

I can't seem to figure out why I get this error? All the .dll files that the warning is stating "The specified module could not be found" do exists in the C:\PHP\ext directoryphp

The PHP extensions are located in

```<code>C:\php\ext
</code>```

Inside the file php.ini I have this variable

```<code>extension_dir = "ext"
</code>```

here is a directory listing of the ext folder

```<code> Volume in drive C is OS
 Volume Serial Number is C63C-1D75

 Directory of C:\php\ext

07/29/2014  06:42 PM    <DIR>          .
07/29/2014  06:42 PM    <DIR>          ..
04/30/2014  02:46 PM            66,560 php_bz2.dll
04/30/2014  02:46 PM            72,704 php_com_dotnet.dll
04/30/2014  02:46 PM           507,392 php_curl.dll
04/30/2014  02:46 PM            18,944 php_enchant.dll
04/30/2014  02:46 PM            43,008 php_exif.dll
04/30/2014  02:46 PM         2,679,808 php_fileinfo.dll
04/30/2014  02:46 PM         1,358,848 php_gd2.dll
04/30/2014  02:46 PM            40,960 php_gettext.dll
04/30/2014  02:46 PM           240,128 php_gmp.dll
04/30/2014  02:46 PM           831,488 php_imap.dll
04/30/2014  02:46 PM            65,024 php_interbase.dll
04/30/2014  02:46 PM           261,632 php_intl.dll
04/30/2014  02:46 PM           179,200 php_ldap.dll
04/30/2014  02:46 PM         1,239,552 php_mbstring.dll
04/30/2014  02:46 PM            36,864 php_mysql.dll
04/30/2014  02:46 PM            88,576 php_mysqli.dll
04/30/2014  02:46 PM           141,824 php_oci8.dll
04/30/2014  02:46 PM           142,336 php_oci8_11g.dll
04/30/2014  02:46 PM           120,320 php_opcache.dll
04/30/2014  02:46 PM            72,704 php_openssl.dll
04/30/2014  02:46 PM            21,504 php_pdo_firebird.dll
04/30/2014  02:46 PM            24,576 php_pdo_mysql.dll
04/30/2014  02:46 PM            23,040 php_pdo_oci.dll
04/30/2014  02:46 PM            20,480 php_pdo_odbc.dll
04/30/2014  02:46 PM            27,648 php_pdo_pgsql.dll
04/30/2014  02:46 PM           465,408 php_pdo_sqlite.dll
08/28/2012  04:15 PM           186,520 php_pdo_sqlsrv_54_ts.dll
06/26/2013  03:22 PM           166,400 php_pdo_sqlsrv_55_ts.dll
04/30/2014  02:46 PM            90,112 php_pgsql.dll
04/30/2014  02:46 PM            12,288 php_shmop.dll
04/30/2014  02:46 PM           385,536 php_snmp.dll
04/30/2014  02:46 PM           236,544 php_soap.dll
04/30/2014  02:46 PM            54,784 php_sockets.dll
04/30/2014  02:46 PM           617,472 php_sqlite3.dll
08/28/2012  04:15 PM           204,952 php_sqlsrv_54_ts.dll
06/26/2013  03:22 PM           183,296 php_sqlsrv_55_ts.dll
04/30/2014  02:46 PM            31,744 php_sybase_ct.dll
04/30/2014  02:46 PM           236,544 php_tidy.dll
04/30/2014  02:46 PM            51,712 php_xmlrpc.dll
04/30/2014  02:46 PM           231,936 php_xsl.dll
              40 File(s)     11,480,368 bytes
               2 Dir(s)  83,103,895,552 bytes free
</code>```

When I try to access the website I get this error

Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'

which is because the extensions are not loaded.

I am assuming that the configuration are correct since the same configuration are working on a different server.

How can I fix this PHP Startup issue?

答:
maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.

```<code>php.ini conf>

extension_dir="C:/Server/PHP7/ext"
</code>```

php on apache works ok but on cli problem with libs loading, as a result, I changed to

```<code>extension_dir="C:/server/PHP7/ext"
</code>```

Body:
I currently have PHP 5.5.12 and Apache 2.4 installed on Windows Server 2008 R2. Everything is running perfectly with no issue/warnings.

What I have done is copied the same Apache file/configuration to another server. I copied the C:\PHP directory and then the C:\Apache24 directory and pasted them into the new server.

Then I installed the Apache with one change (ie httpd -k install.) I changed the port number from 80 to 8877. The Apache is working with no issue and it is running on the 8877 port. I can also open the default page by going to SERVER_IP_ADDRESS:8877 and it works.

But, PHP is not working as it should. In the error.log file from the Apache server I get the warning listed below

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_ldap.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_mysqli.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_openssl.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_pdo_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_sqlsrv_55_ts.dll' - The specified module could not be found.\r\n in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\\php_pdo_sqlsrv_55_ts.dll' - The specified module could not be found.\r\n in Unknown on line 0

I can't seem to figure out why I get this error? All the .dll files that the warning is stating "The specified module could not be found" do exists in the C:\PHP\ext directoryphp

The PHP extensions are located in

C:\php\ext

Inside the file php.ini I have this variable

extension_dir = "ext"

here is a directory listing of the ext folder

 Volume in drive C is OS
 Volume Serial Number is C63C-1D75

 Directory of C:\php\ext

07/29/2014  06:42 PM    <DIR>          .
07/29/2014  06:42 PM    <DIR>          ..
04/30/2014  02:46 PM            66,560 php_bz2.dll
04/30/2014  02:46 PM            72,704 php_com_dotnet.dll
04/30/2014  02:46 PM           507,392 php_curl.dll
04/30/2014  02:46 PM            18,944 php_enchant.dll
04/30/2014  02:46 PM            43,008 php_exif.dll
04/30/2014  02:46 PM         2,679,808 php_fileinfo.dll
04/30/2014  02:46 PM         1,358,848 php_gd2.dll
04/30/2014  02:46 PM            40,960 php_gettext.dll
04/30/2014  02:46 PM           240,128 php_gmp.dll
04/30/2014  02:46 PM           831,488 php_imap.dll
04/30/2014  02:46 PM            65,024 php_interbase.dll
04/30/2014  02:46 PM           261,632 php_intl.dll
04/30/2014  02:46 PM           179,200 php_ldap.dll
04/30/2014  02:46 PM         1,239,552 php_mbstring.dll
04/30/2014  02:46 PM            36,864 php_mysql.dll
04/30/2014  02:46 PM            88,576 php_mysqli.dll
04/30/2014  02:46 PM           141,824 php_oci8.dll
04/30/2014  02:46 PM           142,336 php_oci8_11g.dll
04/30/2014  02:46 PM           120,320 php_opcache.dll
04/30/2014  02:46 PM            72,704 php_openssl.dll
04/30/2014  02:46 PM            21,504 php_pdo_firebird.dll
04/30/2014  02:46 PM            24,576 php_pdo_mysql.dll
04/30/2014  02:46 PM            23,040 php_pdo_oci.dll
04/30/2014  02:46 PM            20,480 php_pdo_odbc.dll
04/30/2014  02:46 PM            27,648 php_pdo_pgsql.dll
04/30/2014  02:46 PM           465,408 php_pdo_sqlite.dll
08/28/2012  04:15 PM           186,520 php_pdo_sqlsrv_54_ts.dll
06/26/2013  03:22 PM           166,400 php_pdo_sqlsrv_55_ts.dll
04/30/2014  02:46 PM            90,112 php_pgsql.dll
04/30/2014  02:46 PM            12,288 php_shmop.dll
04/30/2014  02:46 PM           385,536 php_snmp.dll
04/30/2014  02:46 PM           236,544 php_soap.dll
04/30/2014  02:46 PM            54,784 php_sockets.dll
04/30/2014  02:46 PM           617,472 php_sqlite3.dll
08/28/2012  04:15 PM           204,952 php_sqlsrv_54_ts.dll
06/26/2013  03:22 PM           183,296 php_sqlsrv_55_ts.dll
04/30/2014  02:46 PM            31,744 php_sybase_ct.dll
04/30/2014  02:46 PM           236,544 php_tidy.dll
04/30/2014  02:46 PM            51,712 php_xmlrpc.dll
04/30/2014  02:46 PM           231,936 php_xsl.dll
              40 File(s)     11,480,368 bytes
               2 Dir(s)  83,103,895,552 bytes free

When I try to access the website I get this error

Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'

which is because the extensions are not loaded.

I am assuming that the configuration are correct since the same configuration are working on a different server.

How can I fix this PHP Startup issue?

Body:
maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.

php.ini conf>

extension_dir="C:/Server/PHP7/ext"

php on apache works ok but on cli problem with libs loading, as a result, I changed to

extension_dir="C:/server/PHP7/ext"


问:
python3 default class attribute to method in same class
```<code>class Test:
    func = self.func2 # default: func is func2 by default
    # tried Test.func2 as well and Pycharm shows error

    def __init__(self, func=None):
        if func is not None:
            self.func = func

    def func1(self):
        pass

    def func2(self):
        pass
</code>```

Can anyone advise how to achieve something like the above?

I have tried setting the func parameter to default to func2 in the constructor too but this also errors.

so later, somewhere in the class Test, I can just call self.func instead of repeatedly running conditions to find out whether func1 or func2 should be used

```<code>self.func()
</code>```

**** SOLUTION (what I did) ****

in the main.py:

```<code>t = Test(func=Test.func1)
t.func(t, **kwargs)
</code>```

this should successfully call t.func1 (or t.func2 if specified) with access to the t instance_attributes through a call of higher order method t.func

答:
You could set the default in the __init__ method, based on the value of the func parameter:

Maybe something like this:

```<code>class Test:

    def __init__(self, func=None):
        if func is None:
            self.func = self.func2
        else:
            self.func = func

    def func1():
        print('func1')

    def func2(self):
        print('func2')

Test().func()
Test(Test.func1).func()
</code>```

output:

```<code>func2
func1
</code>```

Body:
class Test:
    func = self.func2 # default: func is func2 by default
    # tried Test.func2 as well and Pycharm shows error

    def __init__(self, func=None):
        if func is not None:
            self.func = func

    def func1(self):
        pass

    def func2(self):
        pass

Can anyone advise how to achieve something like the above?

I have tried setting the func parameter to default to func2 in the constructor too but this also errors.

so later, somewhere in the class Test, I can just call self.func instead of repeatedly running conditions to find out whether func1 or func2 should be used

self.func()

**** SOLUTION (what I did) ****

in the main.py:

t = Test(func=Test.func1)
t.func(t, **kwargs)

this should successfully call t.func1 (or t.func2 if specified) with access to the t instance_attributes through a call of higher order method t.func

Body:
You could set the default in the __init__ method, based on the value of the func parameter:

Maybe something like this:

class Test:

    def __init__(self, func=None):
        if func is None:
            self.func = self.func2
        else:
            self.func = func

    def func1():
        print('func1')

    def func2(self):
        print('func2')

Test().func()
Test(Test.func1).func()

output:

func2
func1


问:
Retrieve Linkedin user’s information
I’m currently developing a NodeJS App and am intending to retrieve Linkedin user’s experience, education and skills. When doing so I get the error below. How can I avoid this error?

Here the workflow followed that leads to the error: http://3.14.113.64:4000/

```<code>InternalOAuthError: failed to fetch user profile
at _oauth2.get (/linkedin-connection/node_modules/passport-linkedin-oauth2/lib/oauth2.js:70:23)
at passBackControl (/linkedin-connection/node_modules/oauth/lib/oauth2.js:132:9)
at IncomingMessage.<anonymous> (/linkedin-connection/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
</code>```

答:
Looks like this is a known issue of this library:
https://github.com/auth0/passport-linkedin-oauth2/issues/75

this module that has not been updated to linkedin API 2.0 as reported in this issue

Switch this for fork:

```<code>npm install @sokratis/passport-linkedin-oauth2
</code>```

And replace the require / import statement:

```<code>var LinkedInStrategy = require('@sokratis/passport-linkedin-oauth2').Strategy;
</code>```

Title: Retrieve Linkedin user’s information

Body:
I’m currently developing a NodeJS App and am intending to retrieve Linkedin user’s experience, education and skills. When doing so I get the error below. How can I avoid this error?

Here the workflow followed that leads to the error: http://3.14.113.64:4000/

InternalOAuthError: failed to fetch user profile
at _oauth2.get (/linkedin-connection/node_modules/passport-linkedin-oauth2/lib/oauth2.js:70:23)
at passBackControl (/linkedin-connection/node_modules/oauth/lib/oauth2.js:132:9)
at IncomingMessage.<anonymous> (/linkedin-connection/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

Body:
Looks like this is a known issue of this library:
https://github.com/auth0/passport-linkedin-oauth2/issues/75

this module that has not been updated to linkedin API 2.0 as reported in this issue

Switch this for fork:

npm install @sokratis/passport-linkedin-oauth2

And replace the require / import statement:

var LinkedInStrategy = require('@sokratis/passport-linkedin-oauth2').Strategy;


问:
How to rank variables in SAS by summarising another variable
For example:

```<code>Groupvar    Value
A           5
A           1
B           0
B           9
B           8
C           2
C           2
</code>```

I want to rank by the Groupvar summarising on Value. So in this example sum(A) = 6, sum(B) = 17, sum(C) = 4. So Rank 1 = B, rank 2 = A, rank 3 = 6.

Ideal output:

```<code>Groupvar    Value    Rank
A           5         2
A           1         2
B           0         1
B           9         1
B           8         1
C           2         3
C           2         3
</code>```

Any ideas how this can be done? I can create a proc summary > then rank> then merge the rank back on. But I'm wondering if there's a better way to do it.

答:
you can do it at one proc sql:

```<code>data test1;
    Ord + 1;
    input Groupvar$ Value;
    cards;
    A 5
    A 1
    B 0
    B 9
    B 8
    C 2
    C 2
    ;
run;

proc sql noprint;
    create table Test2 as
    select Groupvar, sum(Value) as Sum
    from Test1
    group by Groupvar
    order by Sum
    ;

    create table Test3 as
    select a.*, b.Sum, b.Rank
    from Test1 as a
    left join (
        select a.*, monotonic() as Rank
        from Test2 as a
    ) as b
    on a.Groupvar = b.Groupvar
    order by Ord
    ;
quit;

</code>```

Body:
For example:

Groupvar    Value
A           5
A           1
B           0
B           9
B           8
C           2
C           2

I want to rank by the Groupvar summarising on Value. So in this example sum(A) = 6, sum(B) = 17, sum(C) = 4. So Rank 1 = B, rank 2 = A, rank 3 = 6.

Ideal output:

Groupvar    Value    Rank
A           5         2
A           1         2
B           0         1
B           9         1
B           8         1
C           2         3
C           2         3

Any ideas how this can be done? I can create a proc summary > then rank> then merge the rank back on. But I'm wondering if there's a better way to do it.

Body:
you can do it at one proc sql:

data test1;
    Ord + 1;
    input Groupvar$ Value;
    cards;
    A 5
    A 1
    B 0
    B 9
    B 8
    C 2
    C 2
    ;
run;

proc sql noprint;
    create table Test2 as
    select Groupvar, sum(Value) as Sum
    from Test1
    group by Groupvar
    order by Sum
    ;

    create table Test3 as
    select a.*, b.Sum, b.Rank
    from Test1 as a
    left join (
        select a.*, monotonic() as Rank
        from Test2 as a
    ) as b
    on a.Groupvar = b.Groupvar
    order by Ord
    ;
quit;


问:
Replace zeros of array with last non-zero value in Amibroker
I have an array that looks like this;

```<code>arr_with_zeros = [1 0 0 2 0 0 3 0 0 6 0 0 8 0 0]
</code>```

I want to replace the zeros with the last non-zero value in the array. The new array should look like this;

```<code>arr_non_zeros = [1 1 1 2 2 2 3 3 3 6 6 6 8 8 8]
</code>```

This is the code I wrote.

```<code>arr_non_zeros = ValueWhen(True, arr_with_zeros, n=1);
</code>```

It does not work. arr_non_zeros has the same contents as arr_with_zeros. Can someone help? Thank you.

I am using Amibroker ver6.30.5

答:
Have a look at IIF</p>

```<code>arr_new = iif(arr_non_zeros == 0, ref(arr_non_zeros,-1), arr_non_zeros);
</code>```

Body:
I have an array that looks like this;

arr_with_zeros = [1 0 0 2 0 0 3 0 0 6 0 0 8 0 0]

I want to replace the zeros with the last non-zero value in the array. The new array should look like this;

arr_non_zeros = [1 1 1 2 2 2 3 3 3 6 6 6 8 8 8]

This is the code I wrote.

arr_non_zeros = ValueWhen(True, arr_with_zeros, n=1);

It does not work. arr_non_zeros has the same contents as arr_with_zeros. Can someone help? Thank you.

I am using Amibroker ver6.30.5

Body:
Have a look at IIF

arr_new = iif(arr_non_zeros == 0, ref(arr_non_zeros,-1), arr_non_zeros);


问:
Python random.shuffle() on a list of lists returns a list of identical lists
In my script I need to generate a simple list of [1,2,3,4] values and then shuffle each one of those lists inside this list individually. I used random.shuffle() function which works fine on single arrays, but when I try to use it in a for loop the output is a list of shuffled arrays, but all of them identical:

[3, 1, 2, 4]

  [3, 1, 2, 4]

  [3, 1, 2, 4]

  etc...

I have tried running the script with different python versions (2.7, 3.6) but the problem persists.

Here is a simplified code that represents the issue:

```<code>import random

numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10

#shuffle every list inside list_of_lists
for i in list_of_lists:
    random.shuffle(i)

#print every list from list_of_lists
for a in list_of_lists:
    print(a)
</code>```

Running the script multiple times results in different lists, but they always consist of a repeated one array. What can I do to fix it? Is it an issue with random.shuffle() or my script? What am I doing wrong?

答:
Your problem is this line:

```<code>list_of_lists = [numbers_list]*10
</code>```

This creates a list of 10 references to the same list (numbers_list). Any change you make to any of the lists is reflected in all 10 copies - because they're the same list.

Do something like this instead:

```<code>list_of_lists = [numbers_list.copy() for _ in range(10)]
</code>```

Body:
In my script I need to generate a simple list of [1,2,3,4] values and then shuffle each one of those lists inside this list individually. I used random.shuffle() function which works fine on single arrays, but when I try to use it in a for loop the output is a list of shuffled arrays, but all of them identical:

[3, 1, 2, 4]

  [3, 1, 2, 4]

  [3, 1, 2, 4]

  etc...

I have tried running the script with different python versions (2.7, 3.6) but the problem persists.

Here is a simplified code that represents the issue:

import random

numbers_list = [1,2,3,4]
#make a list of 10 numbers_list
list_of_lists = [numbers_list]*10

#shuffle every list inside list_of_lists
for i in list_of_lists:
    random.shuffle(i)

#print every list from list_of_lists
for a in list_of_lists:
    print(a)

Running the script multiple times results in different lists, but they always consist of a repeated one array. What can I do to fix it? Is it an issue with random.shuffle() or my script? What am I doing wrong?

Body:
Your problem is this line:

list_of_lists = [numbers_list]*10

This creates a list of 10 references to the same list (numbers_list). Any change you make to any of the lists is reflected in all 10 copies - because they're the same list.

Do something like this instead:

list_of_lists = [numbers_list.copy() for _ in range(10)]


问:
how to perform coordinates affine transformation using python?
I would like to perform transformation for this example data set.

There are four known points with coordinates x, y, z in one coordinate[primary_system] system and next four known points with coordinates x, y, h that belong to another coordinate system[secondary_system].
Those points correspond; for example primary_system1 point and secondary_system1 point is exactly the same point but we have it's coordinates in two different coordinate systems.
So I have here four pairs of adjustment points and want to transform another point coordinates from primary system to secondary system according to adjustment.

```<code>primary_system1 = (3531820.440, 1174966.736, 5162268.086)
primary_system2 = (3531746.800, 1175275.159, 5162241.325)
primary_system3 = (3532510.182, 1174373.785, 5161954.920)
primary_system4 = (3532495.968, 1175507.195, 5161685.049)

secondary_system1 = (6089665.610, 3591595.470, 148.810)
secondary_system2 = (6089633.900, 3591912.090, 143.120)
secondary_system3 = (6089088.170, 3590826.470, 166.350)
secondary_system4 = (6088672.490, 3591914.630, 147.440)

#transform this point
x = 3532412.323
y = 1175511.432
z = 5161677.111<br>
</code>```

 at the moment I try to average translation for x, y and z axis using each of the four pairs of points like:

```<code>#x axis
xt1 =  secondary_system1[0] - primary_system1[0]
xt2 =  secondary_system2[0] - primary_system2[0]
xt3 =  secondary_system3[0] - primary_system3[0]
xt4 =  secondary_system4[0] - primary_system4[0]

xt = (xt1+xt2+xt3+xt4)/4    #averaging
</code>```

...and so on for y and z axis

```<code>#y axis
yt1 =  secondary_system1[1] - primary_system1[1]
yt2 =  secondary_system2[1] - primary_system2[1]
yt3 =  secondary_system3[1] - primary_system3[1]
yt4 =  secondary_system4[1] - primary_system4[1]

yt = (yt1+yt2+yt3+yt4)/4    #averaging

#z axis
zt1 =  secondary_system1[2] - primary_system1[2]
zt2 =  secondary_system2[2] - primary_system2[2]
zt3 =  secondary_system3[2] - primary_system3[2]
zt4 =  secondary_system4[2] - primary_system4[2]

zt = (zt1+zt2+zt3+zt4)/4    #averaging
</code>```

So above I attempted to calculate average translation vector for every axis

答:
The mapping you are looking for seems to be affine transformation. Four 3D points not lying in one plain is the exact number of points needed to recover the affine transformation. The latter is, loosely speaking, multiplication by matrix and adding a vector

```<code>secondary_system = A * primary_system + t
</code>```

The problem is now reduced to finding appropriate matrix A and vector t. I think, this code may help you (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input data
ins = np.array([[3531820.440, 1174966.736, 5162268.086],
                [3531746.800, 1175275.159, 5162241.325],
                [3532510.182, 1174373.785, 5161954.920],
                [3532495.968, 1175507.195, 5161685.049]]) # <- primary system
out = np.array([[6089665.610, 3591595.470, 148.810],
                [6089633.900, 3591912.090, 143.120],
                [6089088.170, 3590826.470, 166.350],
                [6088672.490, 3591914.630, 147.440]]) # <- secondary system
p = np.array([3532412.323, 1175511.432, 5161677.111]) #<- transform this point
# finding transformation
l = len(ins)
entry = lambda r,d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
M = np.array([[(-1)**i * entry(R, i) for R in out.T] for i in range(l+1)])
A, t = np.hsplit(M[1:].T/(-M[0])[:,None], [l-1])
t = np.transpose(t)[0]
# output transformation
print("Affine transformation matrix:\n", A)
print("Affine transformation translation vector:\n", t)
# unittests
print("TESTING:")
for p, P in zip(np.array(ins), np.array(out)):
  image_p = np.dot(A, p) + t
  result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
  print(p, " mapped to: ", image_p, " ; expected: ", P, result)
# calculate points
print("CALCULATION:")
P = np.dot(A, p) + t
print(p, " mapped to: ", P)
```

This code demonstrates how to recover affine transformation as matrix + vector and tests that initial points are mapped to where they should. You can test this code with Google colab, so you don't have to install anything.

Regarding theory behind this code: it is based on equation presented in "Beginner's guide to mapping simplexes affinely", matrix recovery is described in section "Recovery of canonical notation" and number of points needed to pinpoint the exact affine transformation is discussed in "How many points do we need?" section. The same authors published "Workbook on mapping simplexes affinely" that contains many practical examples of this kind.

Body:
I would like to perform transformation for this example data set.

There are four known points with coordinates x, y, z in one coordinate[primary_system] system and next four known points with coordinates x, y, h that belong to another coordinate system[secondary_system].
Those points correspond; for example primary_system1 point and secondary_system1 point is exactly the same point but we have it's coordinates in two different coordinate systems.
So I have here four pairs of adjustment points and want to transform another point coordinates from primary system to secondary system according to adjustment.

primary_system1 = (3531820.440, 1174966.736, 5162268.086)
primary_system2 = (3531746.800, 1175275.159, 5162241.325)
primary_system3 = (3532510.182, 1174373.785, 5161954.920)
primary_system4 = (3532495.968, 1175507.195, 5161685.049)

secondary_system1 = (6089665.610, 3591595.470, 148.810)
secondary_system2 = (6089633.900, 3591912.090, 143.120)
secondary_system3 = (6089088.170, 3590826.470, 166.350)
secondary_system4 = (6088672.490, 3591914.630, 147.440)

#transform this point
x = 3532412.323
y = 1175511.432
z = 5161677.111

 at the moment I try to average translation for x, y and z axis using each of the four pairs of points like:

#x axis
xt1 =  secondary_system1[0] - primary_system1[0]
xt2 =  secondary_system2[0] - primary_system2[0]
xt3 =  secondary_system3[0] - primary_system3[0]
xt4 =  secondary_system4[0] - primary_system4[0]

xt = (xt1+xt2+xt3+xt4)/4    #averaging

...and so on for y and z axis

#y axis
yt1 =  secondary_system1[1] - primary_system1[1]
yt2 =  secondary_system2[1] - primary_system2[1]
yt3 =  secondary_system3[1] - primary_system3[1]
yt4 =  secondary_system4[1] - primary_system4[1]

yt = (yt1+yt2+yt3+yt4)/4    #averaging

#z axis
zt1 =  secondary_system1[2] - primary_system1[2]
zt2 =  secondary_system2[2] - primary_system2[2]
zt3 =  secondary_system3[2] - primary_system3[2]
zt4 =  secondary_system4[2] - primary_system4[2]

zt = (zt1+zt2+zt3+zt4)/4    #averaging

So above I attempted to calculate average translation vector for every axis

Body:
The mapping you are looking for seems to be affine transformation. Four 3D points not lying in one plain is the exact number of points needed to recover the affine transformation. The latter is, loosely speaking, multiplication by matrix and adding a vector

secondary_system = A * primary_system + t

The problem is now reduced to finding appropriate matrix A and vector t. I think, this code may help you (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input data
ins = np.array([[3531820.440, 1174966.736, 5162268.086],
                [3531746.800, 1175275.159, 5162241.325],
                [3532510.182, 1174373.785, 5161954.920],
                [3532495.968, 1175507.195, 5161685.049]]) # <- primary system
out = np.array([[6089665.610, 3591595.470, 148.810],
                [6089633.900, 3591912.090, 143.120],
                [6089088.170, 3590826.470, 166.350],
                [6088672.490, 3591914.630, 147.440]]) # <- secondary system
p = np.array([3532412.323, 1175511.432, 5161677.111]) #<- transform this point
# finding transformation
l = len(ins)
entry = lambda r,d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
M = np.array([[(-1)**i * entry(R, i) for R in out.T] for i in range(l+1)])
A, t = np.hsplit(M[1:].T/(-M[0])[:,None], [l-1])
t = np.transpose(t)[0]
# output transformation
print("Affine transformation matrix:\n", A)
print("Affine transformation translation vector:\n", t)
# unittests
print("TESTING:")
for p, P in zip(np.array(ins), np.array(out)):
  image_p = np.dot(A, p) + t
  result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
  print(p, " mapped to: ", image_p, " ; expected: ", P, result)
# calculate points
print("CALCULATION:")
P = np.dot(A, p) + t
print(p, " mapped to: ", P)

This code demonstrates how to recover affine transformation as matrix + vector and tests that initial points are mapped to where they should. You can test this code with Google colab, so you don't have to install anything.

Regarding theory behind this code: it is based on equation presented in "Beginner's guide to mapping simplexes affinely", matrix recovery is described in section "Recovery of canonical notation" and number of points needed to pinpoint the exact affine transformation is discussed in "How many points do we need?" section. The same authors published "Workbook on mapping simplexes affinely" that contains many practical examples of this kind.


问:
I have created a docker image for python PyQt4 application using ubuntu 14.04 ,now when i run container i wan to access docker host ip and interfaces
I want to get docker host machine ip address and interface names i.e ifconfig of docker host machine. instead im getting docker container ip address on doing ifconfig in docker container.

It would be great if someone tell me to fetch ip address of docker host machine from a docker container.

i have tried doing ifconfig dockerhostname,
as a result i get error
dockerhostmachi: error fetching interface information: Device not found

This is my dockerfile

FROM ubuntu:14.04

Install dependencies

RUN apt-get update && apt-get install -y \
    python-dev \
    libffi-dev \
    libssl-dev \
    python-enum \
    apache2    \
    libapache2-mod-wsgi  \
    python-pip \
    python-qt4

```<code>RUN chmod -R 777 /var/log/apache2/error.log
RUN chmod -R 777 /var/log/apache2/other_vhosts_access.log
RUN chmod -R 777 /var/log/apache2/access.log
RUN chmod -R 777 /var/run/apache2/
</code>```

RUN a2enmod wsgi

i need to get ifconfig result for docker host machine from a docker container or when i run docker image.

答:
When you run docker image/container you can specify an environment variable using -e parameter. Do it maybe like:
    docker run -e ip=docker_host_ip ...

then it should be available on container side as environment variable.

https://medium.com/the-code-review/top-10-docker-run-command-options-you-cant-live-without-a-reference-d256834e86c1

Body:
I want to get docker host machine ip address and interface names i.e ifconfig of docker host machine. instead im getting docker container ip address on doing ifconfig in docker container.

It would be great if someone tell me to fetch ip address of docker host machine from a docker container.

i have tried doing ifconfig dockerhostname,
as a result i get error
dockerhostmachi: error fetching interface information: Device not found

This is my dockerfile

FROM ubuntu:14.04

Install dependencies

RUN apt-get update && apt-get install -y \
    python-dev \
    libffi-dev \
    libssl-dev \
    python-enum \
    apache2    \
    libapache2-mod-wsgi  \
    python-pip \
    python-qt4

RUN chmod -R 777 /var/log/apache2/error.log
RUN chmod -R 777 /var/log/apache2/other_vhosts_access.log
RUN chmod -R 777 /var/log/apache2/access.log
RUN chmod -R 777 /var/run/apache2/

RUN a2enmod wsgi

i need to get ifconfig result for docker host machine from a docker container or when i run docker image.