问:
Folding expressions in C++17 - Usecase for comparison operators
According to N4295 C++17 will allow me to calculate the sum of an unknown number of arguments thus:

```<code>template<typename ... T>
int sum(T...t)
{
    return (... + t);
}
</code>```

The document further states that I could use operators such as == or > instead of +. Can anybody come up with a sensible example of when I would want to use == or > in such a construct?

(I realize that people can define == and > to do strange things to strange classes, but surely that violates good practice. Writing a > b > c > d is hardly ever a good idea, is it?)

答:
On usecase would be expression templates, for which the comparison operators (e.g. operator ==) return a class object instead of a bool.

I too struggle to come up with a useful example even here, though.

Body:
According to N4295 C++17 will allow me to calculate the sum of an unknown number of arguments thus:

template<typename ... T>
int sum(T...t)
{
    return (... + t);
}

The document further states that I could use operators such as == or > instead of +. Can anybody come up with a sensible example of when I would want to use == or > in such a construct?

(I realize that people can define == and > to do strange things to strange classes, but surely that violates good practice. Writing a > b > c > d is hardly ever a good idea, is it?)


来源: stackexchange

问:
Getting a sprite to bounce off the walls/edges in android app
Most learned friends

I have a sprite that moves around on screen but at the moment it just moves diagonally from left to right and goes off screen and then comes back on the other side.

What I would like it to do is bounce off the edges of the screen in a random fashion but, not being all that clued up on maths, I'm struggling to figure out the coordinates to do this.

Below is what I have so far: (this is an updated code for the Sprite class:

```<code>   public class Sprite {

    //x,y position of sprite - initial position (0,50)
   // int [] DIRECTION_TO_ANIMATION_MAP = {3, 1, 0, 2};
private static final int BMP_ROWS = 3;
private static final int BMP_COLUMNS = 4;
private int x = 0;
private int y = 0;
private int xSpeed = 5;//Horizontal increment of position (speed)
private int ySpeed;// Vertical increment of position (speed)
private int currentFrame = 0;
private GameView gameView;
private Bitmap spritebmp;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
//private Random random = new Random();

public Sprite(GameView gameView) {
    this.gameView = gameView;
    spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
            R.drawable.running_ninja_sprite);
    this.bmp_width = spritebmp.getWidth() / BMP_COLUMNS;
    this.bmp_height = spritebmp.getHeight() / BMP_ROWS;
    /*Random rnd = new Random(System.currentTimeMillis());
    xSpeed = rnd.nextInt(45)-5;
    ySpeed = rnd.nextInt(25)-5;*/
}

//update the position of the sprite
public void update() {

    //if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
    //if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}
    if (x > gameView.getWidth() - bmp_width - xSpeed || x + xSpeed < 0) {
        xSpeed = -xSpeed;
    }
    x = x + xSpeed;
    if (y > gameView.getHeight() - bmp_height - ySpeed || y + ySpeed < 0) {
        ySpeed = -ySpeed;
    }
    y = y + xSpeed;
    currentFrame = ++currentFrame % BMP_COLUMNS;
    //y = random.nextInt(gameView.getWidth());
    //wrapAround(); //Adjust motion of sprite.
}

public void draw(Canvas canvas) {
    update();
    int srcX = currentFrame * bmp_width;
    int srcY = 1 * bmp_height; //getAnimationRow()
    Rect src = new Rect(srcX, srcY, srcX + bmp_width, srcY + bmp_height);
    Rect dst = new Rect(x, y, x + bmp_width, y + bmp_height);
    //Draw sprite image
    canvas.drawBitmap(spritebmp, x, y, null);

}

/*private int getAnimationRow() {
    double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
    int direction = (int) Math.round(dirDouble) % BMP_ROWS;
    return DIRECTION_TO_ANIMATION_MAP[direction];
}*/

public void wrapAround() {
    //Code to wrap around
    if (x < 0) x = x + gameView.getWidth(); //increment x whilst not off screen
    if (x >= gameView.getWidth()) { //if gone of the right sides of screen
        x = x - gameView.getWidth(); //Reset x
    }
    if (y < 0) y = y + gameView.getHeight();//increment y whilst not off screen
    if (y >= gameView.getHeight()) {//if gone of the bottom of screen
        y -= gameView.getHeight();//Reset y
    }
}

    // Checks if the sprite was touched

public boolean wasItTouched(float ex, float ey) {
    boolean touched = false;
    if ((x <= ex) && (ex < x + bmp_width) &&
            (y <= ey) && (ey < y + bmp_height)) {
        touched = true;
    }
    return touched;
    }
    }
</code>```

It now does bounce off the edge but from top left, diagonally to the right and back up in the same direction and continues to do this back and forth.  I'd like it to be random in its direction after hitting the edge.  Any suggestions?  As you can see from the code I have tried a lot of things but the sprite just keeps on doing this continuous back and forth diagonal motion and I'm at a loss as to what I can do.

Thanks

答:
Just negate your speed every time you hit a wall

```<code>if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}
</code>```

/////////////////////////////// Edit

It will fit something like this. You can also remove your wrap function as it is no longer applicable

```<code>//update the position of the sprite
public void update() {

    x = x + xSpeed;
    y = y + xSpeed;
    bounce();

}

private void bounce(){
    if (x <= 0 || x >= gameView.getWidth() ){ xSpeed = xSpeed * -1;}
    if (y <= 0 || y >= gameView.getHeight() ){ ySpeed = ySpeed * -1;}

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Most learned friends

I have a sprite that moves around on screen but at the moment it just moves diagonally from left to right and goes off screen and then comes back on the other side.

What I would like it to do is bounce off the edges of the screen in a random fashion but, not being all that clued up on maths, I'm struggling to figure out the coordinates to do this.

Below is what I have so far: (this is an updated code for the Sprite class:

   public class Sprite {

    //x,y position of sprite - initial position (0,50)
   // int [] DIRECTION_TO_ANIMATION_MAP = {3, 1, 0, 2};
private static final int BMP_ROWS = 3;
private static final int BMP_COLUMNS = 4;
private int x = 0;
private int y = 0;
private int xSpeed = 5;//Horizontal increment of position (speed)
private int ySpeed;// Vertical increment of position (speed)
private int currentFrame = 0;
private GameView gameView;
private Bitmap spritebmp;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
//private Random random = new Random();

public Sprite(GameView gameView) {
    this.gameView = gameView;
    spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
            R.drawable.running_ninja_sprite);
    this.bmp_width = spritebmp.getWidth() / BMP_COLUMNS;
    this.bmp_height = spritebmp.getHeight() / BMP_ROWS;
    /*Random rnd = new Random(System.currentTimeMillis());
    xSpeed = rnd.nextInt(45)-5;
    ySpeed = rnd.nextInt(25)-5;*/
}

//update the position of the sprite
public void update() {

    //if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
    //if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}
    if (x > gameView.getWidth() - bmp_width - xSpeed || x + xSpeed < 0) {
        xSpeed = -xSpeed;
    }
    x = x + xSpeed;
    if (y > gameView.getHeight() - bmp_height - ySpeed || y + ySpeed < 0) {
        ySpeed = -ySpeed;
    }
    y = y + xSpeed;
    currentFrame = ++currentFrame % BMP_COLUMNS;
    //y = random.nextInt(gameView.getWidth());
    //wrapAround(); //Adjust motion of sprite.
}

public void draw(Canvas canvas) {
    update();
    int srcX = currentFrame * bmp_width;
    int srcY = 1 * bmp_height; //getAnimationRow()
    Rect src = new Rect(srcX, srcY, srcX + bmp_width, srcY + bmp_height);
    Rect dst = new Rect(x, y, x + bmp_width, y + bmp_height);
    //Draw sprite image
    canvas.drawBitmap(spritebmp, x, y, null);

}

/*private int getAnimationRow() {
    double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
    int direction = (int) Math.round(dirDouble) % BMP_ROWS;
    return DIRECTION_TO_ANIMATION_MAP[direction];
}*/

public void wrapAround() {
    //Code to wrap around
    if (x < 0) x = x + gameView.getWidth(); //increment x whilst not off screen
    if (x >= gameView.getWidth()) { //if gone of the right sides of screen
        x = x - gameView.getWidth(); //Reset x
    }
    if (y < 0) y = y + gameView.getHeight();//increment y whilst not off screen
    if (y >= gameView.getHeight()) {//if gone of the bottom of screen
        y -= gameView.getHeight();//Reset y
    }
}

    // Checks if the sprite was touched

public boolean wasItTouched(float ex, float ey) {
    boolean touched = false;
    if ((x <= ex) && (ex < x + bmp_width) &&
            (y <= ey) && (ey < y + bmp_height)) {
        touched = true;
    }
    return touched;
    }
    }

It now does bounce off the edge but from top left, diagonally to the right and back up in the same direction and continues to do this back and forth.  I'd like it to be random in its direction after hitting the edge.  Any suggestions?  As you can see from the code I have tried a lot of things but the sprite just keeps on doing this continuous back and forth diagonal motion and I'm at a loss as to what I can do.

Thanks

Body:
Just negate your speed every time you hit a wall

if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}

/////////////////////////////// Edit

It will fit something like this. You can also remove your wrap function as it is no longer applicable

//update the position of the sprite
public void update() {

    x = x + xSpeed;
    y = y + xSpeed;
    bounce();

}

private void bounce(){
    if (x <= 0 || x >= gameView.getWidth() ){ xSpeed = xSpeed * -1;}
    if (y <= 0 || y >= gameView.getHeight() ){ ySpeed = ySpeed * -1;}

}


问:
VBA Loop from another sheet
I'm having trouble with my loop not running throughout my entire sheet 1.  If the value in Sheet 1 "tests" exist in sheet 2 "cancer".  Then i want the value in sheet 2 "cancer" to be placed into sheet 1 "Tests".  The code works except for the loop. Currently it only applies to the first record in my first sheet then stops.  </p>

```<code>Sub Testing()

Dim x As Long
Dim y As Long

x = 2
y = 2

Do While Sheets("Cancer").Cells(y, 1).Value <> ""
     If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
           If Sheets("Tests").Cells(x, 4).Value = "" Then
                 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
                 x = x + 1
           End If
     End If
     y = y + 1
Loop

End Sub
</code>```

答:
You've almost qualified all of your ranges. You missed one. Try changing the line:

```<code>Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
</code>```

to

```<code>Sheets("Tests").Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
</code>```

Title: VBA Loop from another sheet

Body:
I'm having trouble with my loop not running throughout my entire sheet 1.  If the value in Sheet 1 "tests" exist in sheet 2 "cancer".  Then i want the value in sheet 2 "cancer" to be placed into sheet 1 "Tests".  The code works except for the loop. Currently it only applies to the first record in my first sheet then stops.

Sub Testing()

Dim x As Long
Dim y As Long

x = 2
y = 2

Do While Sheets("Cancer").Cells(y, 1).Value <> ""
     If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
           If Sheets("Tests").Cells(x, 4).Value = "" Then
                 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
                 x = x + 1
           End If
     End If
     y = y + 1
Loop

End Sub

Body:
You've almost qualified all of your ranges. You missed one. Try changing the line:

Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))

to

Sheets("Tests").Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))


问:
Pandas: How do you group data together by date and apply multiple functions to the grouped data?
In my code i have a pandas dataframe with a column for the day and a column called value. I would like to group the dataframe by day and find the minimum and maximum value for that day, average the min and max and then subtract that average from the value column in the dataframe.

The closest thing i have been able to do has been:

```<code>temp_max = var.groupby(['day']).max()
temp_min = var.groupby(['day']).min()

answer = var.groupby(['day'])['value'].apply(lambda x : x - (temp_max['value'] - temp_min['value']) / 2 )
</code>```

input:

```<code>    Unnamed: 0  hrs                   vt                   rt      value
0       119899    1  2017-03-01 07:00:00  2017-03-01 06:00:00  67.910011
1       119900    2  2017-03-01 08:00:00  2017-03-01 06:00:00  52.970033
2       119901    3  2017-03-01 09:00:00  2017-03-01 06:00:00  49.010011
3       119902    4  2017-03-01 10:00:00  2017-03-01 06:00:00  47.030000
4       119903    5  2017-03-01 11:00:00  2017-03-01 06:00:00  45.949989
5       119904    6  2017-03-01 12:00:00  2017-03-01 06:00:00  45.949989
</code>```

output:

```<code>1    0           NaN
 1     41.540022
 2     31.549989
 3     29.570005
 4     36.949989
 5     38.030000
 6     40.010011
 7     33.980000
 8     47.030000
 9           NaN
 10          NaN
 11          NaN
 12          NaN
 13          NaN
 14          NaN
 15          NaN
 16          NaN
2    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     17          NaN
     18          NaN
     19          NaN
     20          NaN
     21          NaN
             ...
6    4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     53          NaN
     54          NaN
     55          NaN
     56          NaN
7    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     57          NaN
     58          NaN
     59          NaN
     60          NaN
8    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     61          NaN
</code>```

The values appear to be correct but i was hoping to keep my original dataframe and just update the values in place. Is there a different way i should be approaching this? Thx in advance!

答:
How about something like this?

```<code>new_frame = pd.DataFrame(columns=var.columns)

for day,frame in var.groupby('day'):

    frame.loc[:,'value'] = frame['value'].apply(lambda x: x - (frame.value.max() + frame.value.min())/2)

    new_frame = new_frame.append(frame)
</code>```

You could do it in one line using a list comprehension and groupby but it looks a bit ugly

```<code>var.loc[:,'value'] = pd.concat([frm.value.apply(lambda x:x-(frm.value.min() + frm.value.max())/2) for d,frm in var.groupby('day')])
</code>```

I believe that would accomplish what you're trying to do, albeit not being particularly readable!

Body:
In my code i have a pandas dataframe with a column for the day and a column called value. I would like to group the dataframe by day and find the minimum and maximum value for that day, average the min and max and then subtract that average from the value column in the dataframe.

The closest thing i have been able to do has been:

temp_max = var.groupby(['day']).max()
temp_min = var.groupby(['day']).min()

answer = var.groupby(['day'])['value'].apply(lambda x : x - (temp_max['value'] - temp_min['value']) / 2 )

input:

    Unnamed: 0  hrs                   vt                   rt      value
0       119899    1  2017-03-01 07:00:00  2017-03-01 06:00:00  67.910011
1       119900    2  2017-03-01 08:00:00  2017-03-01 06:00:00  52.970033
2       119901    3  2017-03-01 09:00:00  2017-03-01 06:00:00  49.010011
3       119902    4  2017-03-01 10:00:00  2017-03-01 06:00:00  47.030000
4       119903    5  2017-03-01 11:00:00  2017-03-01 06:00:00  45.949989
5       119904    6  2017-03-01 12:00:00  2017-03-01 06:00:00  45.949989

output:

1    0           NaN
 1     41.540022
 2     31.549989
 3     29.570005
 4     36.949989
 5     38.030000
 6     40.010011
 7     33.980000
 8     47.030000
 9           NaN
 10          NaN
 11          NaN
 12          NaN
 13          NaN
 14          NaN
 15          NaN
 16          NaN
2    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     17          NaN
     18          NaN
     19          NaN
     20          NaN
     21          NaN
             ...
6    4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     53          NaN
     54          NaN
     55          NaN
     56          NaN
7    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     57          NaN
     58          NaN
     59          NaN
     60          NaN
8    1           NaN
     2           NaN
     3           NaN
     4           NaN
     5           NaN
     6           NaN
     7           NaN
     8           NaN
     61          NaN

The values appear to be correct but i was hoping to keep my original dataframe and just update the values in place. Is there a different way i should be approaching this? Thx in advance!

Body:
How about something like this?

new_frame = pd.DataFrame(columns=var.columns)

for day,frame in var.groupby('day'):

    frame.loc[:,'value'] = frame['value'].apply(lambda x: x - (frame.value.max() + frame.value.min())/2)

    new_frame = new_frame.append(frame)

You could do it in one line using a list comprehension and groupby but it looks a bit ugly

var.loc[:,'value'] = pd.concat([frm.value.apply(lambda x:x-(frm.value.min() + frm.value.max())/2) for d,frm in var.groupby('day')])

I believe that would accomplish what you're trying to do, albeit not being particularly readable!


问:
Javascript convert stringified array of objects into array of objects
I have the following variable (given to me through a HTTP response, hence the string):

```<code>var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'
</code>```

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

```<code>[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n
</code>```

How can I parse this string into an array of javascript objects?

答:
This is not valid JSON. In order for it to be valid JSON, you would need to have quotes around the keys ("name")

```<code>[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]
</code>```

The error occurs because the parser does not hit a " and instead hits the n.

Body:
I have the following variable (given to me through a HTTP response, hence the string):

var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n

How can I parse this string into an array of javascript objects?

Body:
This is not valid JSON. In order for it to be valid JSON, you would need to have quotes around the keys ("name")

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]

The error occurs because the parser does not hit a " and instead hits the n.


问:
visual studio 12 windows phone application development
I am new for windows phone application development. when start a new windows phone application and press ok i get error as 'no windows phone version supported'.
my os is windows 7 and i use visual studio 12.
- how start a windows phone application in visual studio 12 with windows 7 os.
- how add windows sdk error messagefor the visual studio.

start a project

答:
Hi at first I also had that problem, you have to upgrade to windows 8, it is not possible to run wp8 on windows 7.
Hope it has helped.</p>


问:
Fluent NHibernate Upgrade to NH3.0 alpha
Hy
We want to use the latest alpha version of NHibernate. Unfortunately the latest fluent nhibernate release is built for 2.1 GA. When do you plan to upgrade to latest NH? Is there a source tree which I can fork to build the latest version from?

Daniel

答: Get the latest source code for fluent nhibernate and change the references from 2.1.2 to 3.0 and recompile the fluent nhibernate code.</p>

ContentLicense: CC BY-SA 2.5


问:
Notepad++ find string in parantheses
I try to fetch the string modlgn_username inside the paranthesis from the following string:

$this->webDriver->findElement(WebDriverBy::id("modlgn_username"))->click();

This is my regular expression:

```<code>\$this->webDriver->findElement\(WebDriverBy::id\("([A-z0-9]+)"\)\)->click\(\);
</code>```

However I get Find: Can't find text \$this->webDriver->findElement(WebDriverBy::id("([A-Za-z0-9])"))->click();

It works in online regex tester though:

https://regex101.com/r/6oDry3/1

答:
Your regex will be like this

```<code>(?<=\(\")\w+_\w+(?=\"\))
</code>```

it checks that from left side of the string will be (" and from right side will be ").

It mach the string you need. Have a look

Title: Notepad++ find string in parantheses

Body:
I try to fetch the string modlgn_username inside the paranthesis from the following string:

$this->webDriver->findElement(WebDriverBy::id("modlgn_username"))->click();

This is my regular expression:

\$this->webDriver->findElement\(WebDriverBy::id\("([A-z0-9]+)"\)\)->click\(\);

However I get Find: Can't find text \$this->webDriver->findElement(WebDriverBy::id("([A-Za-z0-9])"))->click();

It works in online regex tester though:

https://regex101.com/r/6oDry3/1

Body:
Your regex will be like this

(?<=\(\")\w+_\w+(?=\"\))

it checks that from left side of the string will be (" and from right side will be ").

It mach the string you need. Have a look


问:
How can I test lambda in local using python?
Is there any way that I can test aws lambda in local? I know there is a package which name is 'localstack' but seems like there is not many people who tried it.</p>

答:
You can run your Lambda functions in the same way you would run any python script e.g.

```<code>if __name__ == "__main__":
    event = []
    context = []
    lambda_handler(event, context)
</code>```

If you use virtual environments, this helps ensure you have all the required dependencies installed for your lambda function alongside the correct python version.

Is there any additional services you need that are present in 'localstack' that you don't have locally?

Body:
You can run your Lambda functions in the same way you would run any python script e.g.

if __name__ == "__main__":
    event = []
    context = []
    lambda_handler(event, context)

If you use virtual environments, this helps ensure you have all the required dependencies installed for your lambda function alongside the correct python version.

Is there any additional services you need that are present in 'localstack' that you don't have locally?


问:
How Qt::UniqueConnection works?
I don't quite understand how the Qt::UniqueConnection 'flag' works.

The Qt::UniqueConnection is a constant from the enum Qt::ConnectionType that "describes the types of connection that can be used between signals and slots".

As explained in the documentation, the Qt::UniqueConnection constant is:

Same as AutoConnection, but the connection is made only if it does not
  duplicate an existing connection. i.e., if the same signal is already
  connected to the same slot for the same pair of objects, then the
  connection will fail. This connection type was introduced in Qt 4.6.

Based on the following example:

```<code>  for (int index = 0; index < 2; ++index)
  {
      QPushButton *myButton = new QPushButton("Button", this);
      connect(myButton, SIGNAL(clicked()), this, SLOT(doSomething()), Qt::UniqueConnection);
  }
</code>```

Will it create 2 unique connections (one for each button), based on the button memory address (I suppose)?

Or will it create only one connection (the second one will fail), based on the object type (QPushButton) and the signals and slots used?

答:
If you don't put this flag, it means that you can do the same connection: viz. same sender object, same receiver object, same signal and same Slot more than once.

The slot will be called as many number of times as you made this connection.

But you shouldn't abuse of this flag when it is not necessary because it will do a verification to see if your connection already exists, which mean the code will be slower.

Note: Qt::UniqueConnection do not work for lambdas, non-member functions and functors; they only apply to connecting to member functions.

Title: How Qt::UniqueConnection works?

Body:
I don't quite understand how the Qt::UniqueConnection 'flag' works.

The Qt::UniqueConnection is a constant from the enum Qt::ConnectionType that "describes the types of connection that can be used between signals and slots".

As explained in the documentation, the Qt::UniqueConnection constant is:

Same as AutoConnection, but the connection is made only if it does not
  duplicate an existing connection. i.e., if the same signal is already
  connected to the same slot for the same pair of objects, then the
  connection will fail. This connection type was introduced in Qt 4.6.

Based on the following example:

  for (int index = 0; index < 2; ++index)
  {
      QPushButton *myButton = new QPushButton("Button", this);
      connect(myButton, SIGNAL(clicked()), this, SLOT(doSomething()), Qt::UniqueConnection);
  }

Will it create 2 unique connections (one for each button), based on the button memory address (I suppose)?

Or will it create only one connection (the second one will fail), based on the object type (QPushButton) and the signals and slots used?

ContentLicense: CC BY-SA 4.0


问:
String validation with multiple levels required using CMD command
I have three requirements I need to meet when validating a password.  I have figure out with the help of others how to verify that the password is at least seven characters long and the user name is not part of the password.

My last requirement is to check to see if a string contains characters from three of the following four groups:

English uppercase characters (A through Z)

English lowercase characters (a through z)

Base 10 digits (0 through 9)

Non-alphabetic characters (for example, !, $, #, %)

For example (Hou$e or House1) would pass but (House, house or hou$e) would fail

The call to ":checkRequirement3" is where I would like to make this finial check.  The password is valid if all three requirements are meet.

```<code>@echo off
setlocal
set /p userName=Username:
set /p userPassword=Password:
call :strlen result userPassword
call :checkRequirement1
call :checkRequirement2
call :checkRequirement3

ECHO Finished
Pause
:strlen <resultVar> <stringVar>
REM THIS DETERMINES THE LENGTH OF THE PASSWORD
(
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" (
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)

(
    endlocal
    set "%~1=%len%"
    exit /b
)

:checkRequirement1
REM THIS CHECKS IF PASSWORD IS AT LEAST 7 CHARACTERS LONG
(
    if %result% GEQ 7 (
    exit /b
    )else (
    GOTO passwordFail
    )

:checkRequirement2
REM THIS CHECKS IF THE USER NAME IS INCLUDED IN THE PASSWORD
setlocal enabledelayedexpansion
set replacedUsername=!userPassword:%userName%=!
if not !replacedUsername!==%userPassword% (
GOTO passwordFail
)else (
exit /b
)

:checkRequirement3
REM THIS CHECKS IF THE PASSWORD CONTAINS CHARACTERS FROM 3 OF THE FOLLOWING GROUPS
REM English uppercase characters (A through Z)
REM English lowercase characters (a through z)
REM Base 10 digits (0 through 9)
REM Non-alphabetic characters (for example, !, $, #, %)

ECHO This Requirement not finished
Pause
exit /b

:passwordFail
ECHO Password Failed Requirement
PAUSE
exit /b
)
</code>```

答:
@ECHO OFF
SETLOCAL

FOR %%t IN (Hou$e House1 House, house hou$e hou%%%%se hou^^se) DO CALL :test "%%t"

GOTO :EOF

:test
SET /a count=0
>"q43120516.txt" ECHO %~1
TYPE "q43120516.txt"
FOR %%s IN ("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]"
            "[abcdefghijklmnopqrstuvwxyz]"
        "[!@#&$%%^]"
        "[0123456789]") DO FINDSTR /r %%s "q43120516.txt">nul&IF NOT ERRORLEVEL 1 SET /a count+=1
ECHO found %count% groups IN %~1
DEL "q43120516.txt"
GOTO :EOF
```

naturally, the name of the temporary file "q43120516.txt" is irrelevant.

A few little things to note here:

Certain characters, like % and ^ which have a special meaning to cmd need to be doubled - sometimes quadrupled.

Yes, I'm aware that in theory you could use echo %~1|. Try it.

Yes, I'm aware that in theory you could use [A-Z]. Try it.

Body:
I have three requirements I need to meet when validating a password.  I have figure out with the help of others how to verify that the password is at least seven characters long and the user name is not part of the password.

My last requirement is to check to see if a string contains characters from three of the following four groups:

English uppercase characters (A through Z)

English lowercase characters (a through z)

Base 10 digits (0 through 9)

Non-alphabetic characters (for example, !, $, #, %)

For example (Hou$e or House1) would pass but (House, house or hou$e) would fail

The call to ":checkRequirement3" is where I would like to make this finial check.  The password is valid if all three requirements are meet.

@echo off
setlocal
set /p userName=Username:
set /p userPassword=Password:
call :strlen result userPassword
call :checkRequirement1
call :checkRequirement2
call :checkRequirement3

ECHO Finished
Pause
:strlen <resultVar> <stringVar>
REM THIS DETERMINES THE LENGTH OF THE PASSWORD
(
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" (
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)

(
    endlocal
    set "%~1=%len%"
    exit /b
)

:checkRequirement1
REM THIS CHECKS IF PASSWORD IS AT LEAST 7 CHARACTERS LONG
(
    if %result% GEQ 7 (
    exit /b
    )else (
    GOTO passwordFail
    )

:checkRequirement2
REM THIS CHECKS IF THE USER NAME IS INCLUDED IN THE PASSWORD
setlocal enabledelayedexpansion
set replacedUsername=!userPassword:%userName%=!
if not !replacedUsername!==%userPassword% (
GOTO passwordFail
)else (
exit /b
)

:checkRequirement3
REM THIS CHECKS IF THE PASSWORD CONTAINS CHARACTERS FROM 3 OF THE FOLLOWING GROUPS
REM English uppercase characters (A through Z)
REM English lowercase characters (a through z)
REM Base 10 digits (0 through 9)
REM Non-alphabetic characters (for example, !, $, #, %)

ECHO This Requirement not finished
Pause
exit /b

:passwordFail
ECHO Password Failed Requirement
PAUSE
exit /b
)

Body:
@ECHO OFF
SETLOCAL

FOR %%t IN (Hou$e House1 House, house hou$e hou%%%%se hou^^se) DO CALL :test "%%t"

GOTO :EOF

:test
SET /a count=0
>"q43120516.txt" ECHO %~1
TYPE "q43120516.txt"
FOR %%s IN ("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]"
            "[abcdefghijklmnopqrstuvwxyz]"
        "[!@#&$%%^]"
        "[0123456789]") DO FINDSTR /r %%s "q43120516.txt">nul&IF NOT ERRORLEVEL 1 SET /a count+=1
ECHO found %count% groups IN %~1
DEL "q43120516.txt"
GOTO :EOF

naturally, the name of the temporary file "q43120516.txt" is irrelevant.

A few little things to note here:

Certain characters, like % and ^ which have a special meaning to cmd need to be doubled - sometimes quadrupled.

Yes, I'm aware that in theory you could use echo %~1|. Try it.

Yes, I'm aware that in theory you could use [A-Z]. Try it.


问:
Google Cloud App Engine app.yaml for multiple environments
I currently have my app up and running, the app.yaml and dispatch.yaml are in the root of the application and I deploy through Google Cloud CLI.

This works well for the moment, though as I move to having a dev, staging and prod environment I can see that it's no longer viable.

The main issue I see is that I have to edit the variables in the app.yaml file so they are appropriate for environment (for example I use env_variables to store mysql credentials...).

I can't find anything in the docs that points to the correct way to manage this, any ideas?

Also... When deploying from a GIT repo it seems that the app.yaml needs to be in the repo, is this correct? It doesn't seem right to me... There must be a better way!

答:
Note: assuming you use a different application to implement each environment, not different services/module of the same application, which IMHO would be an unnecessary complication. See How to deploy one app engine app to multiple projects

Personally I use a different git branch for each environment.

Granted I only have 2 environments: a development/staging one and the production one, but the same principle applies:

The branch structure reflects the flow through environments:

the master branch is used for the dev environment

the staging branch is pulled off the master branch

the production branch is pulled off the staging branch

To propagate code changes from one environment to another you'd merge the respective child branch to the newer parent branch version (which contains the changes you want to pick up) and deploy the merged child branch code to the corresponding environment.

Each branch has its own version of the app.yaml file. You'll have to keep an eye on conflicts in this file which may pop up whenever changes to it are propagated from one branch to another.

See also Environment Specific Variables In Google App Engine Java (and maybe its linked/related posts).


问:
Definition of Multi-threading
Not really programming related this question, but I still hope it fits somehow here :).
I wrote the following sentence in my work:

```<code>Mulitthreading refers to the ability of an OS to subdivide an application into
threads, where each of the them are capable to execute independently.
</code>```

I was told, that this definition of thread is too narrow. I am not really sure why this is the case, could somebody be so kind to explain me what I missed?

Thank you

答: Usually, it is the application that decides when to create threads, not the OS.  Also, you may want to mention that threads share address space, while each process has its own.</p>

Title: Definition of Multi-threading

Body:
Not really programming related this question, but I still hope it fits somehow here :).
I wrote the following sentence in my work:

Mulitthreading refers to the ability of an OS to subdivide an application into
threads, where each of the them are capable to execute independently.

I was told, that this definition of thread is too narrow. I am not really sure why this is the case, could somebody be so kind to explain me what I missed?

Thank you


问:
Using subqueries in Eloquent/Laravel
Here's the query in raw SQL:

```<code>SELECT *
FROM (
    SELECT `characters`.`id`,`characters`.`refreshToken`,
           `characters`.`name`,max(`balances`.`created_at`) as `refreshDate`
        FROM `characters`
        INNER JOIN `balances` ON `characters`.`id` = `balances`.`character`
        WHERE `characters`.`refreshToken` IS NOT NULL
        GROUP BY `characters`.`id`
) AS `t1`
WHERE `refreshDate` < '2017-03-29';
</code>```

I've tested this in phpMyAdmin and it returns the expected results.  However I'm using the Eloquent and Laravel libraries in my PHP app and I'm not sure how to approach this.  How exactly do subqueries work in this case?

答:
You can use subqueries in Eloquent by specifying them as a closure to the where method. For example:

```<code>$characters = Character::where(function ($query) {
    // subqueries goes here
    $query->where(...
          ...
          ->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();
</code>```

You have to chain your methods to the $query variable that is passed to the closure in the above example.

If you want to pass any variable to the subquery you need the use keyword as:

```<code>$characterName = 'Gandalf';

$characters = Character::where(function ($query) use ($characterName) {
    // subqueries goes here
    $query->where('name', $characterName)
          ...
          ->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();
</code>```

Title: Using subqueries in Eloquent/Laravel

Body:
Here's the query in raw SQL:

SELECT *
FROM (
    SELECT `characters`.`id`,`characters`.`refreshToken`,
           `characters`.`name`,max(`balances`.`created_at`) as `refreshDate`
        FROM `characters`
        INNER JOIN `balances` ON `characters`.`id` = `balances`.`character`
        WHERE `characters`.`refreshToken` IS NOT NULL
        GROUP BY `characters`.`id`
) AS `t1`
WHERE `refreshDate` < '2017-03-29';

I've tested this in phpMyAdmin and it returns the expected results.  However I'm using the Eloquent and Laravel libraries in my PHP app and I'm not sure how to approach this.  How exactly do subqueries work in this case?

Body:
You can use subqueries in Eloquent by specifying them as a closure to the where method. For example:

$characters = Character::where(function ($query) {
    // subqueries goes here
    $query->where(...
          ...
          ->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();

You have to chain your methods to the $query variable that is passed to the closure in the above example.

If you want to pass any variable to the subquery you need the use keyword as:

$characterName = 'Gandalf';

$characters = Character::where(function ($query) use ($characterName) {
    // subqueries goes here
    $query->where('name', $characterName)
          ...
          ->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();


问:
SQL Update a column in a table using Trigger to a Function
I am trying to auto generate a document reference number when a new document is added to an sql table - the reference number is a concatonation of some of the other fields in that table.

Looking online i can see one method is to use the dbid function to generate a uid and then create a function to concatonate and then a trigger on the table on insert to populate the column, but ive spent numerous hours and i cant get it to work.

The table has the following columns:-

```<code>Table:-     dbo.codeallocations21322

Columns :-
Dbid
Projectcode
Type
Discipline]
Hdlreference
</code>```

So the hdlreference column would be populated with :-

```<code>[projectcode]-[type]-[discipline]-[bdid]
</code>```

With the [bdid] set to 6 characters'.

Eg 21322-rfq-mech-000001
Any help would be much appreciated / advise a better way ?

Many thanks in advance.

答:
You can use a computed column</p>

```<code>alter table codeallocations21322
  add hdlreference
      as ( projectcode  + '-' + type + '-' + discipline + '-' + dbid);
</code>```

Body:
I am trying to auto generate a document reference number when a new document is added to an sql table - the reference number is a concatonation of some of the other fields in that table.

Looking online i can see one method is to use the dbid function to generate a uid and then create a function to concatonate and then a trigger on the table on insert to populate the column, but ive spent numerous hours and i cant get it to work.

The table has the following columns:-

Table:-     dbo.codeallocations21322

Columns :-
Dbid
Projectcode
Type
Discipline]
Hdlreference

So the hdlreference column would be populated with :-

[projectcode]-[type]-[discipline]-[bdid]

With the [bdid] set to 6 characters'.

Eg 21322-rfq-mech-000001
Any help would be much appreciated / advise a better way ?

Many thanks in advance.

Body:
You can use a computed column

alter table codeallocations21322
  add hdlreference
      as ( projectcode  + '-' + type + '-' + discipline + '-' + dbid);


问:
Save multiple values in table
Given:

a user defined function that receives a string and returns multiple (5) values

a dataframe with one string column

I read every column from the dataframe, and call the function with the column as parameter.

The output should be saved as a table.
How can I achieve this?

答:
If function return values of the same type, in Scala:

```<code>// functions
val mySplit = (value: String) => Array(value.split(","))
val mySplitUDF = udf(mySplit(_: String))

// data
val intialDF = sparkContext.parallelize(List("First,Second,Third")).toDF("initialColumn")

// transformations
val arrayDF = intialDF.select(mySplitUDF(col("initialColumn")).as("arrayColumn"))
val expodedDF = arrayDF.select(explode(col("arrayColumn")).as("explodedCol"))

val resultDF = expodedDF.select(
  col("explodedCol").getItem(0).as("Col1"),
  col("explodedCol").getItem(1).as("Col2"),
  col("explodedCol").getItem(2).as("Col3")
)
resultDF.show(false)
</code>```

Result is:

```<code>+-----+------+-----+
|Col1 |Col2  |Col3 |
+-----+------+-----+
|First|Second|Third|
+-----+------+-----+
</code>```

On Python can be implemented in similar way

Title: Save multiple values in table

Body:
If function return values of the same type, in Scala:

// functions
val mySplit = (value: String) => Array(value.split(","))
val mySplitUDF = udf(mySplit(_: String))

// data
val intialDF = sparkContext.parallelize(List("First,Second,Third")).toDF("initialColumn")

// transformations
val arrayDF = intialDF.select(mySplitUDF(col("initialColumn")).as("arrayColumn"))
val expodedDF = arrayDF.select(explode(col("arrayColumn")).as("explodedCol"))

val resultDF = expodedDF.select(
  col("explodedCol").getItem(0).as("Col1"),
  col("explodedCol").getItem(1).as("Col2"),
  col("explodedCol").getItem(2).as("Col3")
)
resultDF.show(false)

Result is:

+-----+------+-----+
|Col1 |Col2  |Col3 |
+-----+------+-----+
|First|Second|Third|
+-----+------+-----+

On Python can be implemented in similar way


问:
How to create ManyToOne relationship using JPA Hibernate annotation?
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

```<code>// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;
</code>```

Team POJO

```<code>@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();
</code>```

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

```<code>  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+
</code>```

The Team Table

```<code> +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+
</code>```

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.

答:
I discovered that you have defined @Column at the one to many association property (tasks), I assume it was a type error. </p>

<p>For bi-directional one to many association, updates one side of the relationship, the other side should also get updated, and be in sync. Below shown how the make both entity in sync: </p>

```<code>@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long taskId;

    //Mapping To Team
    @ManyToOne
    @JoinColumn(name="teamId")
    private Team team;

    public void setTeam(Team team) {
        this.team = team;
        if (!team.getTasks().contains(this)) {
            team.getTasks().add(this);
        }
    }

}

@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long teamId;
    @Column(nullable = false)

    @OneToMany(mappedBy="team")
    private List<Task> tasks = new ArrayList<Task>();

    public void addTask(Task task) {
        this.tasks.add(task);
        if (task.getTeam() != this) {
            task.setTeam(this);
        }
    }
}
</code>```

Body:
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;

Team POJO

@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+

The Team Table

 +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.

Body:
I discovered that you have defined @Column at the one to many association property (tasks), I assume it was a type error.

For bi-directional one to many association, updates one side of the relationship, the other side should also get updated, and be in sync. Below shown how the make both entity in sync:

@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long taskId;

    //Mapping To Team
    @ManyToOne
    @JoinColumn(name="teamId")
    private Team team;

    public void setTeam(Team team) {
        this.team = team;
        if (!team.getTasks().contains(this)) {
            team.getTasks().add(this);
        }
    }

}

@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long teamId;
    @Column(nullable = false)

    @OneToMany(mappedBy="team")
    private List<Task> tasks = new ArrayList<Task>();

    public void addTask(Task task) {
        this.tasks.add(task);
        if (task.getTeam() != this) {
            task.setTeam(this);
        }
    }
}


问:
Incorrect responsive images aspect ratio in bootstrap 4
I want to put a text between two images in bootstrap grid. But images in row sections change their aspect ratio(original is 1:1) and do not resize correctly.</p>

<p>(Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100)   </p>

```<code><div class="container">
  <div class="row">
    <img class="img-fluid rounded-circle col-lg-3 col-md-3 col-sm-12" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
    <p class="text-center col-lg-6 col-md-6 col-sm-12">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <img class="img-fluid rounded-circle col-lg-3 col-md-3 col-sm-12" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective2">
  </div>
</div>
</code>```

答:
Don't put the grid column classes on the img and p tags. Rather wrap those in div elements with the desired bootstrap classes. The reason for this is that bootstraps col-* classes need to use width and max-width properties so they are going override your css on img-fluid class. If you for example use col-md-6 then that element's width needs to be 50% of its parent - it cannot be both 50% and 100% at the same time. So you want to make your img elements children of those.

```<code><div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-3 col-lg-3">
      <img class="img-fluid rounded-circle" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
    </div>
    <div class="col-lg-6 col-md-6 col-md-6 ">
      <p class="text-center ">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
    <div class="col-sm-12 col-md-3 col-lg-3">
      <img class="img-fluid rounded-circle" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective1">
    </div>
  </div>
</div>
</code>```

Also for your img-fluid class change the css to:

```<code>.img-fluid {
  width: 100%;
  height: auto;
}
</code>```

Body:
I want to put a text between two images in bootstrap grid. But images in row sections change their aspect ratio(original is 1:1) and do not resize correctly.

(Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100)

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
Don't put the grid column classes on the img and p tags. Rather wrap those in div elements with the desired bootstrap classes. The reason for this is that bootstraps col-* classes need to use width and max-width properties so they are going override your css on img-fluid class. If you for example use col-md-6 then that element's width needs to be 50% of its parent - it cannot be both 50% and 100% at the same time. So you want to make your img elements children of those.

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-3 col-lg-3">
      <img class="img-fluid rounded-circle" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
    </div>
    <div class="col-lg-6 col-md-6 col-md-6 ">
      <p class="text-center ">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
    <div class="col-sm-12 col-md-3 col-lg-3">
      <img class="img-fluid rounded-circle" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective1">
    </div>
  </div>
</div>

Also for your img-fluid class change the css to:

.img-fluid {
  width: 100%;
  height: auto;
}


问:
Fill div with image without stretching
I have an image with high resolution (width: 5540px, height: 2680px), and I need
this image to cover an entire div (this div goes full width and 80% of height). This image is displayed on screens with resolutions of 768px till 1600px.

When I use background-size: cover, the image goes full width but the bottom part is cut off.

When I use background-size: contain, the image is resized to fit the height but the width isn't entirely filled.

When I user background-size: 100%, the image fill the entire div, but gets stretch out.

Is there any way to do that or do I need to resize the image (for example, resize image to 1600px (width) because this image is only displayed on screens with width from 768px to 1600px)?

答:
This is tested and working solution.

What you need is:

Parent div to be:

```<code>position: relative; overflow: hidden;
</code>```

And image:

```<code>img {
  bottom: -5000px;
  left: -5000px;
  margin: auto;
  min-height: 100%;
  min-width: 100%;
  position: absolute;
  right: -5000px;
  top: -5000px;
}
</code>```

This will center the image no matter what and keep its proportions. And please please please do not use image which is width: 5540px, height: 2680px, unless this is the size of your container where you putting it. It will add substantially to your page load and its considered bad practice. Better resize the image to needed size.

Title: Fill div with image without stretching

Body:
This is tested and working solution.

What you need is:

Parent div to be:

position: relative; overflow: hidden;

And image:

img {
  bottom: -5000px;
  left: -5000px;
  margin: auto;
  min-height: 100%;
  min-width: 100%;
  position: absolute;
  right: -5000px;
  top: -5000px;
}

This will center the image no matter what and keep its proportions. And please please please do not use image which is width: 5540px, height: 2680px, unless this is the size of your container where you putting it. It will add substantially to your page load and its considered bad practice. Better resize the image to needed size.


问:
Rails Feed Parsing Model and Params
goddesses and demi-gods of StackOverflow,

I have been trying to figure out this little problem for 1 week, 3 days, 17 hours, 19 minutes and 59 potatoes.

I am new to Rails and I'm trying to create an app that takes in multiple RSS Feeds. I need each feed to belong to the respective News Outlet it came from. How can I do this while also populating the Feed Entries database?

Here is what I've gotten up to...

FeedEntry model

```<code>class FeedEntry < ApplicationRecord
    belongs_to :news_outlet
    def self.update_from_feed(feed_url)
        feed = Feedjira::Feed.fetch_and_parse(feed_url)
        feed.entries.each do |entry|
            unless exists? :guid => entry.id
                create!(
                    :name           => entry.title,
                    :summary        => entry.summary,
                    :url            => entry.url,
                    :published_at   => entry.published,
                    :guid           => entry.id

                )
            end
        end
    end
end
</code>```

NewsOutlet Model

```<code> class NewsOutlet < ApplicationRecord
    has_many :feed_entries
end
</code>```

NewsOutlet Controller

```<code>class NewsOutletsController < ApplicationController
    before_action :authenticate_user!, except: [:index, :show]
  before_filter :configure_permitted_parameters, if: :devise_controller?
  before_filter :verify_is_admin, except: [:index, :show]

  def index
    @news_outlets = NewsOutlet.all
  end

  def new
    @news_outlet = NewsOutlet.new
  end

  def create
    @news_outlet = NewsOutlet.new(news_outlet_params)

    @news_outlet.save
    redirect_to @news_outlet
  end

  def show
    @news_outlet = NewsOutlet.find(params[:id])
  end

  def edit
    @news_outlet = NewsOutlet.find(params[:id])
  end

  def update
    @news_outlet = NewsOutlet.find(params[:id])
    if @news_outlet.update news_outlet_params
      redirect_to @news_outlet
    else
      render 'edit'
    end
  end

  def delete
  end

  def destroy
    @news_outlet = NewsOutlet.find(params[:id])
    @news_outlet.destroy
    redirect_to news_outlets_path
  end

  private

  def news_outlet_params
    params.require(:news_outlet).permit(:name, :url)
  end
end
</code>```

And my NewsOutlet#Index just in case, which is where I'd like to call upon the FeedEntry DB to populate it with the news headlines.

```<code><h1>Blah</h1>
 <% if @news_outlets.present? %>
        <% @news_outlets.each do |news_outlet| %>
            <% entries = FeedEntry.update_from_feed(news_outlet.url) %>
            <p><%= link_to "#{news_outlet.name}", news_outlet.url %></p>

            <% entries.first(5).each do |entry| %>
                <%= link_to "#{entry.title}", entry.url %><br>
            <% end %>
            <p><%= link_to "Show", news_outlet_path(news_outlet) %></p>
            <hr>
        <% end %>
    <% else %>
        <p>No news outlets yet...</p>
    <% end %>
</code>```

May you have many potatoes in the apocalypse. Any help is much appreciated <3

答:
I haven't test it myself but I think this should work:

NewsOutlet Model

```<code>class NewsOutlet < ApplicationRecord
  has_many :feed_entries

  def update_from_feed
    entries = Feedjira::Feed.fetch_and_parse(self.url)

    entries.each do |entry|
      feed_entries.where(guid: entry.id).first_or_create! do |fe|
        fe.name = entry.title
        fe.summary = entry.summary
        fe.url = entry.url
        fe.published_at = entry.published
      end
    end

    entries.first(5)
  end

end
</code>```

FeedEntry model

```<code>class FeedEntry < ApplicationRecord
  belongs_to :news_outlet
end
</code>```

View

```<code><% @news_outlets.each do |news_outlet| %>
  <p><%= link_to "#{news_outlet.name}", news_outlet.url %></p>
  <% news_outlet.update_from_feed.each do |entry| %>
    <%= link_to "#{entry.title}", entry.url %><br>
  <% end %>
  <p><%= link_to "Show", news_outlet_path(news_outlet) %></p>
  <hr>
<% end %>
</code>```

Title: Rails Feed Parsing Model and Params

Body:
goddesses and demi-gods of StackOverflow,

I have been trying to figure out this little problem for 1 week, 3 days, 17 hours, 19 minutes and 59 potatoes.

I am new to Rails and I'm trying to create an app that takes in multiple RSS Feeds. I need each feed to belong to the respective News Outlet it came from. How can I do this while also populating the Feed Entries database?

Here is what I've gotten up to...

FeedEntry model

class FeedEntry < ApplicationRecord
    belongs_to :news_outlet
    def self.update_from_feed(feed_url)
        feed = Feedjira::Feed.fetch_and_parse(feed_url)
        feed.entries.each do |entry|
            unless exists? :guid => entry.id
                create!(
                    :name           => entry.title,
                    :summary        => entry.summary,
                    :url            => entry.url,
                    :published_at   => entry.published,
                    :guid           => entry.id

                )
            end
        end
    end
end

NewsOutlet Model

 class NewsOutlet < ApplicationRecord
    has_many :feed_entries
end

NewsOutlet Controller

class NewsOutletsController < ApplicationController
    before_action :authenticate_user!, except: [:index, :show]
  before_filter :configure_permitted_parameters, if: :devise_controller?
  before_filter :verify_is_admin, except: [:index, :show]

  def index
    @news_outlets = NewsOutlet.all
  end

  def new
    @news_outlet = NewsOutlet.new
  end

  def create
    @news_outlet = NewsOutlet.new(news_outlet_params)

    @news_outlet.save
    redirect_to @news_outlet
  end

  def show
    @news_outlet = NewsOutlet.find(params[:id])
  end

  def edit
    @news_outlet = NewsOutlet.find(params[:id])
  end

  def update
    @news_outlet = NewsOutlet.find(params[:id])
    if @news_outlet.update news_outlet_params
      redirect_to @news_outlet
    else
      render 'edit'
    end
  end

  def delete
  end

  def destroy
    @news_outlet = NewsOutlet.find(params[:id])
    @news_outlet.destroy
    redirect_to news_outlets_path
  end

  private

  def news_outlet_params
    params.require(:news_outlet).permit(:name, :url)
  end
end

And my NewsOutlet#Index just in case, which is where I'd like to call upon the FeedEntry DB to populate it with the news headlines.

Blah

 <% if @news_outlets.present? %>
        <% @news_outlets.each do |news_outlet| %>
            <% entries = FeedEntry.update_from_feed(news_outlet.url) %>

<%= link_to "#{news_outlet.name}", news_outlet.url %>

            <% entries.first(5).each do |entry| %>
                <%= link_to "#{entry.title}", entry.url %>

            <% end %>

<%= link_to "Show", news_outlet_path(news_outlet) %>

        <% end %>
    <% else %>

No news outlets yet...

    <% end %>

May you have many potatoes in the apocalypse. Any help is much appreciated <3

Body:
I haven't test it myself but I think this should work:

NewsOutlet Model

class NewsOutlet < ApplicationRecord
  has_many :feed_entries

  def update_from_feed
    entries = Feedjira::Feed.fetch_and_parse(self.url)

    entries.each do |entry|
      feed_entries.where(guid: entry.id).first_or_create! do |fe|
        fe.name = entry.title
        fe.summary = entry.summary
        fe.url = entry.url
        fe.published_at = entry.published
      end
    end

    entries.first(5)
  end

end

FeedEntry model

class FeedEntry < ApplicationRecord
  belongs_to :news_outlet
end

View

<% @news_outlets.each do |news_outlet| %>
  <p><%= link_to "#{news_outlet.name}", news_outlet.url %></p>
  <% news_outlet.update_from_feed.each do |entry| %>
    <%= link_to "#{entry.title}", entry.url %><br>
  <% end %>
  <p><%= link_to "Show", news_outlet_path(news_outlet) %></p>
  <hr>
<% end %>


问:
get current line through custom.js in jupyter
I would like to insert text on the line where the cursor stands in a jupyter cell through custom.js . Is there something like a Jupyter.notebook.get_current_line() method? I would search the documentation but I can't find an overview of all the callable methods on Jupyter.notebook.

答:
Jupyter uses CodeMirror for the text editor, so you'll have better luck looking in the CodeMirror API.

So, you can use Jupyter.notebook.get_selected_cell().code_mirror to get the current cell's CodeMirror instance.

Then you could use CodeMirror's getCursor function to return the position of the cursor. It returns both the line number and how many characters into the line the cursor is (in the format {line: 0, ch: 0} for the first line first character)

Finally, you can use replaceRange to insert text. Simply save the current cursor position and use replaceRange("Your text here",cursor,cursor)

So, the final code would look something like

```<code>var cm = Jupyter.notebook.get_selected_cell().code_mirror;
var cursor = cm.getCursor();
cm.replaceRange("Your text here",cursor,cursor);
</code>```

Body:
Jupyter uses CodeMirror for the text editor, so you'll have better luck looking in the CodeMirror API.

So, you can use Jupyter.notebook.get_selected_cell().code_mirror to get the current cell's CodeMirror instance.

Then you could use CodeMirror's getCursor function to return the position of the cursor. It returns both the line number and how many characters into the line the cursor is (in the format {line: 0, ch: 0} for the first line first character)

Finally, you can use replaceRange to insert text. Simply save the current cursor position and use replaceRange("Your text here",cursor,cursor)

So, the final code would look something like

var cm = Jupyter.notebook.get_selected_cell().code_mirror;
var cursor = cm.getCursor();
cm.replaceRange("Your text here",cursor,cursor);


问:
.NET object size limit
It seems there is a 2 GB size limit for objects in .NET: How to run Fsi.exe in 64 Bits?

Is there a work around this? I would like to load a very large float array (10 GB) in memory and then do some work.

答:
.NET limits any object to max 2 GB even on 64 bit platforms. You can create your own data type, that uses multiple objects to store more data, thus getting around the 2 GB limit of a single object. For instance a List<float[]> would allow you to store more than 2 GB, but you would have to write the necessary plumbing code to make it behave similar to a single, large array.

You may also want to check this question.

Title: .NET object size limit


问:
Mysql-how to update the "domain.com" in "address@domain.com"
In my database I have a lot of users who've misspelled their e-mail address. This in turn causes my postfix to bounce a lot of mails when sending the newsletter.

Forms include (but are not limited to) "yaho.com", "yahho .com" etc.

Very annoying!

So i have been trying to update those record to the correct value.

After executing select email from users where email like '%@yaho%' and email not like '%yahoo%'; and getting the list, I'm stuck because I do not know how to update only the yaho part. I need the username to be left intact.

So I thought I would just dump the database and use vim to replace, but I cannot escape the @ symbol..

BTW, how do I select all email addresses written in CAPS? select upper(email) from users; would just transform everything into CAPS, whereas I just needed to find out the already-written-in-CAPS mails.

答:
```<code>UPDATE contacts SET email = REPLACE(email, SUBSTRING_INDEX(email, '@', -1), 'domain.com')
</code>```


问:
From data frame to dataframe with lists and unique id
Lets say I have following data frame:

```<code>df <- data.frame(id = c(1,1,1,2,2,3),
                 content = c("red", "yellow", "blue", "red", "black", "white"),
                 content2 = c("cat", "dog", "horse", "cat", "dog", "horse"))
</code>```

I would like to make a dataframe in whch there is as many rows as number of unique id values with other columns collapsed in list.

The output should look like this:

```<code>output <- data.frame(id = c(1,2,3),
                     content = I(list(c("red", "yellow", "blue"), c("red", "black"), c("white", "black"))),
                     content2 = I(list(c("cat", "dog", "horse"), c("cat", "dog"), c("horse", "duck"))))
</code>```

I would also like to know how to go other way again, From output to df.

答:
We can use summarise_each

```<code>library(dplyr)
res <- df %>%
         group_by(id) %>%
         summarise_each(funs(list(.)))
</code>```

To go back to the original dataset

```<code>library(tidyr)
unnest(res)
</code>```

Body:
Lets say I have following data frame:

df <- data.frame(id = c(1,1,1,2,2,3),
                 content = c("red", "yellow", "blue", "red", "black", "white"),
                 content2 = c("cat", "dog", "horse", "cat", "dog", "horse"))

I would like to make a dataframe in whch there is as many rows as number of unique id values with other columns collapsed in list.

The output should look like this:

output <- data.frame(id = c(1,2,3),
                     content = I(list(c("red", "yellow", "blue"), c("red", "black"), c("white", "black"))),
                     content2 = I(list(c("cat", "dog", "horse"), c("cat", "dog"), c("horse", "duck"))))

I would also like to know how to go other way again, From output to df.

Body:
We can use summarise_each

library(dplyr)
res <- df %>%
         group_by(id) %>%
         summarise_each(funs(list(.)))

To go back to the original dataset

library(tidyr)
unnest(res)


问:
Remove first element of a Stream in Java 8
I have generated a Stream in Java 8 with Files.walk() method from java.nio library. The problem is that the method includes by default the root path but I do not want this element. I have solved in this case with this code using filter() method:

```<code>public void listFiles(String directoryPath) {
    try {
        Path root = Paths.get(directoryPath);
        Files.walk(root,1)
            .filter(x -> !x.equals(root))
            .forEach(System.out::println);
    } catch (IOException ex) {
        System.err.println("Error reading file: " + directoryPath);
    }
}
</code>```

My question is if there is a way more elegant to remove the first element of a Stream than this. For example working with a index in the Stream or with a tail() method as others functional languages.

答:
Stream#skip

Use skip(1) to ignore the first element.

Don't use it with parallel streams without reading the disclaimer in the javadoc.

Body:
I have generated a Stream in Java 8 with Files.walk() method from java.nio library. The problem is that the method includes by default the root path but I do not want this element. I have solved in this case with this code using filter() method:

public void listFiles(String directoryPath) {
    try {
        Path root = Paths.get(directoryPath);
        Files.walk(root,1)
            .filter(x -> !x.equals(root))
            .forEach(System.out::println);
    } catch (IOException ex) {
        System.err.println("Error reading file: " + directoryPath);
    }
}

My question is if there is a way more elegant to remove the first element of a Stream than this. For example working with a index in the Stream or with a tail() method as others functional languages.


问:
Error while trying upload Artifact to Nexus
What i try to upload is this jar:
https://mvnrepository.com/artifact/org.apache.maven.plugin-tools/maven-plugin-annotations/3.4

with GAV Parameters taken from here (see screen below):

```<code><groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.4</version>
</code>```

Currently i don't have this version in my 3rd party:

what i get is this error:

The error says:

```<code>Artifact upload failed.
Could not store item to repository "3rd party" [id=thirdparty], path ResourceStoreRequest{requestPath='/org/apache/maven/plugin-tools/maven-plugin-annotations/3.4/maven-plugin-annotations-3.4.pom', requestContext=RequestContext{this=org.sonatype.nexus.proxy.RequestContext@101f160e, parent=RequestContext{this=org.sonatype.nexus.proxy.RequestContext@68e0f966, parent=null}}, pathStack=[], processedRepositories=[thirdparty], appliedMappings={}}(GAVCE=org.apache.maven.plugin-tools:maven-plugin-annotations:3.4:c=null:e=pom, for "3rd party" [id=thirdparty])
</code>```

Nexus configuration:

Repository Policy: Release

Deployment Policy : Allow Redeploy

Before i added many artifacts successfully with my account.

Log file:
http://wklej.org/id/3074345/

How can i successfully upload this artifact?

答:
After diagnosing log file: wklej.org/id/3074345
I found out that some files in /opt/nexus/sonatype-work/nexus/storage/thirdparty/ had been added by root
so i changed them to user nexus with command:
chown -R nexus:nexus maven

Body:
What i try to upload is this jar:
https://mvnrepository.com/artifact/org.apache.maven.plugin-tools/maven-plugin-annotations/3.4

with GAV Parameters taken from here (see screen below):

<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.4</version>

Currently i don't have this version in my 3rd party:

what i get is this error:

The error says:

Artifact upload failed.
Could not store item to repository "3rd party" [id=thirdparty], path ResourceStoreRequest{requestPath='/org/apache/maven/plugin-tools/maven-plugin-annotations/3.4/maven-plugin-annotations-3.4.pom', requestContext=RequestContext{this=org.sonatype.nexus.proxy.RequestContext@101f160e, parent=RequestContext{this=org.sonatype.nexus.proxy.RequestContext@68e0f966, parent=null}}, pathStack=[], processedRepositories=[thirdparty], appliedMappings={}}(GAVCE=org.apache.maven.plugin-tools:maven-plugin-annotations:3.4:c=null:e=pom, for "3rd party" [id=thirdparty])

Nexus configuration:

Repository Policy: Release

Deployment Policy : Allow Redeploy

Before i added many artifacts successfully with my account.

Log file:
http://wklej.org/id/3074345/

How can i successfully upload this artifact?


问:
liferay 6.2 to liferay 7 Calendar API migrated to OSGi
i have liferay 6.2 GA4, and im trying to migrate to liferay 7
im using the code upgrade tool

the error im getting is Calendar's API migrated to OSGi

but i cant find how to do this, how do i change the portlet to OSGi? how do i import the calendar module to my portlet? the upgrade tool only says "#Legacy" in the documentation change, so i dont know what to do next... i have a lot of this "#Legacy" errors, how do i correct them?

this question is a duplicate from the liferay forums, but i havent got an answer yet

edit

i dont know the best way to migrate, but i do have a portlet (many portlets actually), i want to use it (them) in a liferay 7 instalation... the portlet im trying to migrate first (the simpler one) uses the calendar API of liferay 6.2 im guessing i just have to add the calendar module, so i can use its classes, i just dont know how... i use calendar API in both the controller and the jsps

the text in the migration tool only says "#Legacy"... that it! thats why im so confused... in eclipse the error says "Calendar API migrated to OSGi" and thats it too... thats why i imagine i just need to add the calendar module...

thank you!

答:
What is the text from the error/change message?

Regarding "Calendar API", is it that you want to use the Calendar API from Liferay's Calendar app?

Note, you should first get your existing portlet running on 7.0 before modularizing it. The updated tutorial Planning Plugin Upgrades and Optimizations has a table of Upgrade Paths for each plugin type and feature.

Jim


问:
Using a custom JSON encoder for SQLAlchemy's PostgreSQL JSONB implementation
I am using SQLAlchemy's core library to access some PostgreSQL database. Consider I have the following table:

```<code>create table foo (j jsonb);
</code>```

And the following python code:

```<code>from decimal import *
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, DateTime
from sqlalchemy.dialects.postgresql import JSONB
metadata = MetaData(schema="public")
foo = Table('foo', metadata,Column('f', JSONB))
d = Decimal(2)
ins = foo.insert().values(j = {'d': d})
# assuming engine is a valid sqlalchemy's connection
engine.execute(ins)
</code>```

This last sentence fails with the following error:

```<code>StatementError("(builtins.TypeError) Decimal('2') is not JSON serializable",)
</code>```

Which is why I am asking this question: Is there a way to specify a custom encoder for SQLAchemy to use when encoding json data into PostgreSQL dialect?

答:
If you're using Flask, you already have an extended JSONEncoder defined in flask.json which handles UUID, but not Decimal. It can be mapped into the SqlAlchemy engine with the json_serializer param as in @univerio's answer:

```<code>from flask import json

engine = create_engine(
    app.config['SQLALCHEMY_DATABASE_URI'],
    convert_unicode=True,
    json_serializer=json.dumps,
)
</code>```

You can further extend the Flask JSONEncoder to support decimal.Decimal with the following:

```<code>import decimal

from flask import json

class CustomJSONEncoder(json.JSONEncoder):
    """
    Override Flask's `JSONEncoder.default`, which is called
    when the encoder doesn't handle a type.
    """
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        else:
            # raises TypeError: o not JSON serializable
            return json.JSONEncoder.default(self, o)

def init_json(app):
    """
    Use custom JSON encoder with Flask
    """
    app.json_encoder = CustomJSONEncoder
</code>```

Body:
I am using SQLAlchemy's core library to access some PostgreSQL database. Consider I have the following table:

create table foo (j jsonb);

And the following python code:

from decimal import *
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, DateTime
from sqlalchemy.dialects.postgresql import JSONB
metadata = MetaData(schema="public")
foo = Table('foo', metadata,Column('f', JSONB))
d = Decimal(2)
ins = foo.insert().values(j = {'d': d})
# assuming engine is a valid sqlalchemy's connection
engine.execute(ins)

This last sentence fails with the following error:

StatementError("(builtins.TypeError) Decimal('2') is not JSON serializable",)

Which is why I am asking this question: Is there a way to specify a custom encoder for SQLAchemy to use when encoding json data into PostgreSQL dialect?

Body:
If you're using Flask, you already have an extended JSONEncoder defined in flask.json which handles UUID, but not Decimal. It can be mapped into the SqlAlchemy engine with the json_serializer param as in @univerio's answer:

from flask import json

engine = create_engine(
    app.config['SQLALCHEMY_DATABASE_URI'],
    convert_unicode=True,
    json_serializer=json.dumps,
)

You can further extend the Flask JSONEncoder to support decimal.Decimal with the following:

import decimal

from flask import json

class CustomJSONEncoder(json.JSONEncoder):
    """
    Override Flask's `JSONEncoder.default`, which is called
    when the encoder doesn't handle a type.
    """
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        else:
            # raises TypeError: o not JSON serializable
            return json.JSONEncoder.default(self, o)

def init_json(app):
    """
    Use custom JSON encoder with Flask
    """
    app.json_encoder = CustomJSONEncoder


问:
VBA Loop from another sheet
I'm having trouble with my loop not running throughout my entire sheet 1.  If the value in Sheet 1 "tests" exist in sheet 2 "cancer".  Then i want the value in sheet 2 "cancer" to be placed into sheet 1 "Tests".  The code works except for the loop. Currently it only applies to the first record in my first sheet then stops.  </p>

```<code>Sub Testing()

Dim x As Long
Dim y As Long

x = 2
y = 2

Do While Sheets("Cancer").Cells(y, 1).Value <> ""
     If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
           If Sheets("Tests").Cells(x, 4).Value = "" Then
                 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
                 x = x + 1
           End If
     End If
     y = y + 1
Loop

End Sub
</code>```

答:
I would use two for loops

```<code>for y = 2 to 10000 'the range your values are found
  if Sheets("Cancer").Cells(y, 1).Value <> "" then
    for x = 2 to 10000 'the range your values are in
      If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = "" Then
            Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
      End If
    next
  end if
next
</code>```

The reason for the loop not running throughout the entire sheet 1 is because of these two lines:
If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = ""
If these conditionals aren't both true, then x will never loop to its next iteration, and you'll have gone through looping through each value of Sheet2 "Cancer" while checking only the same record of Sheet1 "Tests".

Title: VBA Loop from another sheet

Body:
I'm having trouble with my loop not running throughout my entire sheet 1.  If the value in Sheet 1 "tests" exist in sheet 2 "cancer".  Then i want the value in sheet 2 "cancer" to be placed into sheet 1 "Tests".  The code works except for the loop. Currently it only applies to the first record in my first sheet then stops.

Sub Testing()

Dim x As Long
Dim y As Long

x = 2
y = 2

Do While Sheets("Cancer").Cells(y, 1).Value <> ""
     If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
           If Sheets("Tests").Cells(x, 4).Value = "" Then
                 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
                 x = x + 1
           End If
     End If
     y = y + 1
Loop

End Sub

Body:
I would use two for loops

for y = 2 to 10000 'the range your values are found
  if Sheets("Cancer").Cells(y, 1).Value <> "" then
    for x = 2 to 10000 'the range your values are in
      If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = "" Then
            Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
      End If
    next
  end if
next

The reason for the loop not running throughout the entire sheet 1 is because of these two lines:
If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = ""
If these conditionals aren't both true, then x will never loop to its next iteration, and you'll have gone through looping through each value of Sheet2 "Cancer" while checking only the same record of Sheet1 "Tests".


问:
Ajax Post returning "Object XMLHttpReqest" error
Can someone offer some help with my problem please?

I have the following code:

```<code>        function InsertNewMeeting(tripID, contact1ID, contact2ID) {
        $.ajax({
            type: "POST",
            url: "RetrieveSites.aspx/InsertNewMeeting",
            data: "{'tripID': '" + tripID + "','contact1ID: '" + contact1ID + "','contact2ID', '" + contact2ID + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (msg) { alert('ok'); },
            error: function (msg) {alert(msg);}
        });
    }
</code>```

This is meant to call a WebService to post 3 integer values.  The WebService works 100%.

However, when I'm calling the function from the web page, all I get is a "Object XMLHttpRequest" error.

I've examined all parameters that are passed, they are 100% ok.

Is there anything obvious that I'm missing or should be doing?

答:
You could do this to send a proper json object to the server:

```
<code>
function InsertNewMeeting(tripID, contact1ID, contact2ID) {
    var data = {'tripID': tripID, 'contact1ID': contact1ID, 'contact2ID': contact2ID};
    $.ajax({
        type: "POST",
        url: "RetrieveSites.aspx/InsertNewMeeting",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        success: function (msg) {
            alert('ok');
        },
        error: function (msg) {
            alert(msg);
        }
    });
}
</code>```

Mind you that you would need JSON2 to get JSON.stringify() in browsers that doesn't have support for it.

Another thing is that you'd need to enclose properties in double quotes, as it's not JSON if it's just single quotes. Try running your JSON-string through JSONLint to see if it validates.

Body:
Can someone offer some help with my problem please?

I have the following code:

        function InsertNewMeeting(tripID, contact1ID, contact2ID) {
        $.ajax({
            type: "POST",
            url: "RetrieveSites.aspx/InsertNewMeeting",
            data: "{'tripID': '" + tripID + "','contact1ID: '" + contact1ID + "','contact2ID', '" + contact2ID + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (msg) { alert('ok'); },
            error: function (msg) {alert(msg);}
        });
    }

This is meant to call a WebService to post 3 integer values.  The WebService works 100%.

However, when I'm calling the function from the web page, all I get is a "Object XMLHttpRequest" error.

I've examined all parameters that are passed, they are 100% ok.

Is there anything obvious that I'm missing or should be doing?

Body:
You could do this to send a proper json object to the server:

function InsertNewMeeting(tripID, contact1ID, contact2ID) {
    var data = {'tripID': tripID, 'contact1ID': contact1ID, 'contact2ID': contact2ID};
    $.ajax({
        type: "POST",
        url: "RetrieveSites.aspx/InsertNewMeeting",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        success: function (msg) {
            alert('ok');
        },
        error: function (msg) {
            alert(msg);
        }
    });
}

Mind you that you would need JSON2 to get JSON.stringify() in browsers that doesn't have support for it.

Another thing is that you'd need to enclose properties in double quotes, as it's not JSON if it's just single quotes. Try running your JSON-string through JSONLint to see if it validates.


问:
get auth0 user metadata as part of user information
I don't find how to get the user_metadata from the Auth0 Authentication api:

```<code>$auth0Api = new Authentication($domain, $clientId, $clientSecret);

$tokenInfo = $auth0Api->login([
    'username' => $username,
    'password' => $password,
    'realm' => 'Username-Password-Authentication',
]);
$accessToken = $tokenInfo["access_token"];

$info = $auth0Api->userinfo($accessToken);
</code>```

The final $info array only contains the main user information, no meta_data at all. I tried creating a rule from the Auth0 side to add stuff to the user itself (doing user.customtag = 'helloworld' for example) and the customization does not show either.

User info retrieved:

```<code>{
  "sub":"auth0|XXXX",
  "name":"XXXX@XXXX.com",
  "nickname":"XXXX",
  "picture":"XXXX.png",
  "updated_at":"2017-03-31T08:50:59.819Z",
  "email":"XXXX@XXXX.com",
  "email_verified":true
}
</code>```

The "Raw Json" tab of that user shows something much more complete:

```<code>{
    "email": "XXXX@XXXX.com",
    "email_verified": true,
    "user_id": "auth0|XXXX",
    "picture": "XXXX.png",
    "nickname": "XXXX",
    "identities": [
        {
            "user_id": "XXXX",
            "provider": "auth0",
            "connection": "Username-Password-Authentication",
            "isSocial": false
        }
    ],
    "updated_at": "2017-03-31T08:50:59.819Z",
    "created_at": "2017-03-23T16:03:47.075Z",
    "name": "XXXX",
    "user_metadata": {
        "languageCode": "EN"
    },
    "last_ip": "XXXX",
    "last_login": "XXXX",
    "logins_count": XXXX,
    "blocked_for": [],
    "guardian_enrollments": []
}
</code>```

How is it supposed to work?

Environment:

composer: "auth0/auth0-php": "~5.0"

php 7.1

Auth0 Free account

答:
Try starting up your application locally, then update the following URL with your own settings and paste it into a web browser:

```<code>https://YOUR_TENANT.auth0.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&scope=openid profile&redirect_uri=YOUR_REDIRECT_URI&nonce=12345
</code>```

This should at least ensure you are making a request with right scopes etc. You should also ensure you have a User Profile with some "metadata" assigned if you are expecting to read that data post authentication of course ;)

Body:
I don't find how to get the user_metadata from the Auth0 Authentication api:

$auth0Api = new Authentication($domain, $clientId, $clientSecret);

$tokenInfo = $auth0Api->login([
    'username' => $username,
    'password' => $password,
    'realm' => 'Username-Password-Authentication',
]);
$accessToken = $tokenInfo["access_token"];

$info = $auth0Api->userinfo($accessToken);

The final $info array only contains the main user information, no meta_data at all. I tried creating a rule from the Auth0 side to add stuff to the user itself (doing user.customtag = 'helloworld' for example) and the customization does not show either.

User info retrieved:

{
  "sub":"auth0|XXXX",
  "name":"XXXX@XXXX.com",
  "nickname":"XXXX",
  "picture":"XXXX.png",
  "updated_at":"2017-03-31T08:50:59.819Z",
  "email":"XXXX@XXXX.com",
  "email_verified":true
}

The "Raw Json" tab of that user shows something much more complete:

{
    "email": "XXXX@XXXX.com",
    "email_verified": true,
    "user_id": "auth0|XXXX",
    "picture": "XXXX.png",
    "nickname": "XXXX",
    "identities": [
        {
            "user_id": "XXXX",
            "provider": "auth0",
            "connection": "Username-Password-Authentication",
            "isSocial": false
        }
    ],
    "updated_at": "2017-03-31T08:50:59.819Z",
    "created_at": "2017-03-23T16:03:47.075Z",
    "name": "XXXX",
    "user_metadata": {
        "languageCode": "EN"
    },
    "last_ip": "XXXX",
    "last_login": "XXXX",
    "logins_count": XXXX,
    "blocked_for": [],
    "guardian_enrollments": []
}

How is it supposed to work?

Environment:

composer: "auth0/auth0-php": "~5.0"

php 7.1

Auth0 Free account

Body:
Try starting up your application locally, then update the following URL with your own settings and paste it into a web browser:

https://YOUR_TENANT.auth0.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&scope=openid profile&redirect_uri=YOUR_REDIRECT_URI&nonce=12345

This should at least ensure you are making a request with right scopes etc. You should also ensure you have a User Profile with some "metadata" assigned if you are expecting to read that data post authentication of course ;)


问:
Vaadin, slow generation of results
I have to generate results of searching i Vaadin.
Probably the fastest way to do it is to put results into table, but I need some custom layout and the FormLayout for every row would be the best.
Unfortunately if I put rows formatted by FormLayout into table - the generation of the results takes about 15-20 seconds.
If i put just some labels/buttons without putting it in a layout the generation takes about a second - and that's fine.

I've read the vaadin manual about optimising UI and I still don't know what to do to shorten the time needed to generate the results.

How do you generate results in Vaadin if it can't be presented as a table?

答:
Ok, the solution is... use CssLayout inside a table. Although CssLayout still consists of 3 div's it's much faster than FormLayout.
I think that using a FlowPanel from GWT would be even better but I didn't have enough time to check it.
And don't forget about setPageLength method of a Table - the lazy loading is the main reason to use a Table :).</p>

Title: Vaadin, slow generation of results


问:
Shorter way to test range for a certain string
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

```<code>Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub
</code>```

答:
There is a way to find exactly that with just a line of code however it will work only the if you search on 1 column. For your case I think it will work because usually the product name will be in a column. The code is as follows:

```<code>Dim test As Variant
Product = "ProductX"
' Set search_range as desired search range
search_range = Application.WorksheetFunction.Transpose(Sheets(1).Range("A53:A56"))
If UBound(Filter(search_range, Product)) > -1 Then
    file_path = Some_path_A
Else
    file_path = Some_path_B
End If
</code>```

You can give it a try and let me know if this works for you. If not I will try to find a way to do it with multiple columns and improve the answer

Body:
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub

Body:
There is a way to find exactly that with just a line of code however it will work only the if you search on 1 column. For your case I think it will work because usually the product name will be in a column. The code is as follows:

Dim test As Variant
Product = "ProductX"
' Set search_range as desired search range
search_range = Application.WorksheetFunction.Transpose(Sheets(1).Range("A53:A56"))
If UBound(Filter(search_range, Product)) > -1 Then
    file_path = Some_path_A
Else
    file_path = Some_path_B
End If

You can give it a try and let me know if this works for you. If not I will try to find a way to do it with multiple columns and improve the answer


问:
How to pass a file to an API from Azure Logic App
I have a simple Logic App. The trigger is on New file (ex: Dropbox, OneNote, etc.)
I want to pass the filename and the fileContent to a API APP (web Api).
But I got error, or worse the content is null once in the API!

The API is in C#.

How do you pass a file (ex: pdf, png) to and API from Logic App

UPDATE:

In Logic App here my action code:

```<code>"UploadNewFile": {
"inputs": {
    "method": "post",
    "queries": {
        "filedata": {
            "fileName":"@triggerOutputs()['headers']['x-ms-file-name']",
            "fileContent":"@base64(triggerBody())"
        }
    },
    "uri": "https://smartuseconnapiapp.azurewebsites.net/api/UploadNewFile"
},
"metadata": {
    "apiDefinitionUrl": "https://smartuseconnapiapp.azurewebsites.net/swagger/docs/v1",
    "swaggerSource": "website"
},
"runAfter": {},
"type": "Http"
</code>```

}

In my API App, If the function is declared like this filedata is null

```<code>[Route("api/UploadNewFile")]
[HttpPost]
public HttpStatusCode UploadNewFile([FromBody] string filedata)
</code>```

And if I don't add the [FromBody] like that I got an error.

```<code>[Route("api/UploadNewFile")]
[HttpPost]
public HttpStatusCode UploadNewFile(string filedata)
</code>```

答:
I found how to to it.

I needed to pass the filename in the querystring and the file in the body of the HTTP Request. Today, it's not possible to do it using the design view so you need to go in code view.

In the Logic App code

```<code>"queries": {
    "fileName": "@{triggerOutputs()['headers']['x-ms-file-name']}"
    },
"body": "@triggerBody()"
</code>```

In the API App code

```<code>public HttpResponseMessage UploadNewFile([FromUri] string fileName)
{
   var filebytes = Request.Content.ReadAsByteArrayAsync();

   [...]
}
</code>```

A more detailed explanation can be found in this blog post:
http://www.frankysnotes.com/2017/03/passing-file-from-azure-logic-app-to.html

Body:
I have a simple Logic App. The trigger is on New file (ex: Dropbox, OneNote, etc.)
I want to pass the filename and the fileContent to a API APP (web Api).
But I got error, or worse the content is null once in the API!

The API is in C#.

How do you pass a file (ex: pdf, png) to and API from Logic App

UPDATE:

In Logic App here my action code:

"UploadNewFile": {
"inputs": {
    "method": "post",
    "queries": {
        "filedata": {
            "fileName":"@triggerOutputs()['headers']['x-ms-file-name']",
            "fileContent":"@base64(triggerBody())"
        }
    },
    "uri": "https://smartuseconnapiapp.azurewebsites.net/api/UploadNewFile"
},
"metadata": {
    "apiDefinitionUrl": "https://smartuseconnapiapp.azurewebsites.net/swagger/docs/v1",
    "swaggerSource": "website"
},
"runAfter": {},
"type": "Http"

}

In my API App, If the function is declared like this filedata is null

[Route("api/UploadNewFile")]
[HttpPost]
public HttpStatusCode UploadNewFile([FromBody] string filedata)

And if I don't add the [FromBody] like that I got an error.

[Route("api/UploadNewFile")]
[HttpPost]
public HttpStatusCode UploadNewFile(string filedata)

Body:
I found how to to it.

I needed to pass the filename in the querystring and the file in the body of the HTTP Request. Today, it's not possible to do it using the design view so you need to go in code view.

In the Logic App code

"queries": {
    "fileName": "@{triggerOutputs()['headers']['x-ms-file-name']}"
    },
"body": "@triggerBody()"

In the API App code

public HttpResponseMessage UploadNewFile([FromUri] string fileName)
{
   var filebytes = Request.Content.ReadAsByteArrayAsync();

   [...]
}

A more detailed explanation can be found in this blog post:
http://www.frankysnotes.com/2017/03/passing-file-from-azure-logic-app-to.html