问:
How to indeed center object in a JFrame?
I have a class which extends a Jframe, and i have it centered using setLocationRelativeTo(null);. The layouManager is null aswell.

My JFrame:

```<code>mport com.sxf.protocol.chat.util.window.AbstractField;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

public class Field extends AbstractField {

    private Container cp;

    public Field() {
        super("Test");

        buildWindow();
    }

    private void buildWindow() {

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(frameWidth, frameHeight));
        setResizable(false);

        cp = getContentPane();
        cp.setLayout(null);

        initComponents();

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initComponents() {
        JLabel label = new JLabel("Test", SwingConstants.CENTER);
        JLabel border = new JLabel("");
        label.setSize(200, 30);
        label.setLocation((frameWidth - label.getWidth()) / 2, (frameHeight - label.getHeight()) / 2);
        border.setBounds(frameWidth / 2, 0, frameWidth / 2, frameHeight);
        label.setBorder(new LineBorder(new Color(0, 0, 0)));
        border.setBorder(new LineBorder(new Color(255, 0, 0)));

        cp.add(label);
        cp.add(border);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Field();
            }
        });
    }
}
</code>```

I added to border to see if its centered correctly or not.

The AbstractField (only some calculations in it):

```<code>public abstract class AbstractField extends JFrame {

    private final static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    private static final Dimension frameSize = new Dimension(screenSize.width / 4, screenSize.height / 4);
    protected static final int frameWidth;
    protected static final int frameHeight;
    protected static final int x;
    protected static final int y;

    static {
        frameWidth = frameSize.width;
        frameHeight = frameSize.height;
        x = (screenSize.width - frameWidth) / 2;
        y = (screenSize.height - frameHeight) / 2;
    }

    public AbstractField(String title) {
        super(title);
    }
}
</code>```

But when i try to center my components, e.g. the JLabel, doing

(frame.getWidth - component.getWidth) / 2, and the same for the height, it is not actually centered but a little bit to the right.

Is that due to a native moved beginning of the jframe and can i calculate that?

答:
How to indeed center object in a JFrame?

Indeed add it as the only component added to a JPanel with a GridBagLayout. Use that panel as the content pane.

Example:

```<code>import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class CenteredLabel {

    private JComponent ui = null;

    CenteredLabel() {
        initUI();
    }

    public final void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new GridBagLayout());
        ui.setBorder(new EmptyBorder(4,4,4,4));

        JLabel centeredLabel = new JLabel("Test");
        centeredLabel.setBorder(new LineBorder(Color.RED));
        ui.add(centeredLabel);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            CenteredLabel o = new CenteredLabel();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
</code>```

Body:
I have a class which extends a Jframe, and i have it centered using setLocationRelativeTo(null);. The layouManager is null aswell.

My JFrame:

mport com.sxf.protocol.chat.util.window.AbstractField;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

public class Field extends AbstractField {

    private Container cp;

    public Field() {
        super("Test");

        buildWindow();
    }

    private void buildWindow() {

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(frameWidth, frameHeight));
        setResizable(false);

        cp = getContentPane();
        cp.setLayout(null);

        initComponents();

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initComponents() {
        JLabel label = new JLabel("Test", SwingConstants.CENTER);
        JLabel border = new JLabel("");
        label.setSize(200, 30);
        label.setLocation((frameWidth - label.getWidth()) / 2, (frameHeight - label.getHeight()) / 2);
        border.setBounds(frameWidth / 2, 0, frameWidth / 2, frameHeight);
        label.setBorder(new LineBorder(new Color(0, 0, 0)));
        border.setBorder(new LineBorder(new Color(255, 0, 0)));

        cp.add(label);
        cp.add(border);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Field();
            }
        });
    }
}

I added to border to see if its centered correctly or not.

The AbstractField (only some calculations in it):

public abstract class AbstractField extends JFrame {

    private final static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    private static final Dimension frameSize = new Dimension(screenSize.width / 4, screenSize.height / 4);
    protected static final int frameWidth;
    protected static final int frameHeight;
    protected static final int x;
    protected static final int y;

    static {
        frameWidth = frameSize.width;
        frameHeight = frameSize.height;
        x = (screenSize.width - frameWidth) / 2;
        y = (screenSize.height - frameHeight) / 2;
    }

    public AbstractField(String title) {
        super(title);
    }
}

But when i try to center my components, e.g. the JLabel, doing

(frame.getWidth - component.getWidth) / 2, and the same for the height, it is not actually centered but a little bit to the right.

Is that due to a native moved beginning of the jframe and can i calculate that?

Body:
How to indeed center object in a JFrame?

Indeed add it as the only component added to a JPanel with a GridBagLayout. Use that panel as the content pane.

Example:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class CenteredLabel {

    private JComponent ui = null;

    CenteredLabel() {
        initUI();
    }

    public final void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new GridBagLayout());
        ui.setBorder(new EmptyBorder(4,4,4,4));

        JLabel centeredLabel = new JLabel("Test");
        centeredLabel.setBorder(new LineBorder(Color.RED));
        ui.add(centeredLabel);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            CenteredLabel o = new CenteredLabel();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}


来源: stackexchange

问:
How to read every Integers in a line from a file in Java?
I have file that has n lines of Integers. I want to add each int in each line and print them (so I should print 3 int at the end, each one for a line).

I tried this but it will read and add all the Integers in the first loop.

```<code>scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
    while (scan.hasNextLine()) {
         sum += scan.nextInt();
    }
    System.out.println(sum);
    sum = 0;
}
</code>```

答:
This behavior is caused by erroneous usage of loops and scans.
One of correct solutions also incorporates java 8 lambdas, with the assumption that the delimiter of the integers in the file is space(" "):</p>

```<code>    Path path = Paths.get("your path");
    try{
        Files.lines(path)
                .map( line -> line.split(" "))
                .mapToInt( numbers -> Arrays.stream(numbers)
                   .reduce(0 , (sum, num) -> sum + Integer.parseInt(num), (first, second) -> first + second ))
                .forEachOrdered(System.out::println);

    } catch (IOException e){
        e.printStackTrace();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have file that has n lines of Integers. I want to add each int in each line and print them (so I should print 3 int at the end, each one for a line).

I tried this but it will read and add all the Integers in the first loop.

scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
    while (scan.hasNextLine()) {
         sum += scan.nextInt();
    }
    System.out.println(sum);
    sum = 0;
}

Body:
This behavior is caused by erroneous usage of loops and scans.
One of correct solutions also incorporates java 8 lambdas, with the assumption that the delimiter of the integers in the file is space(" "):

    Path path = Paths.get("your path");
    try{
        Files.lines(path)
                .map( line -> line.split(" "))
                .mapToInt( numbers -> Arrays.stream(numbers)
                   .reduce(0 , (sum, num) -> sum + Integer.parseInt(num), (first, second) -> first + second ))
                .forEachOrdered(System.out::println);

    } catch (IOException e){
        e.printStackTrace();
    }


问:
Trying to insert User defined type of Vector into User defined type Vectors
I'm trying to make a vector of vectors in a spell system for a small RPG battle simulation. The main goal I'm trying to accomplish is have a vector of Spells that the player can access and select what type of Spells they want to cast: Fire, Ice, etc. and then choose the name of the spell: burn, frost, etc.

The code below is what I've declared Spell and FireSpell as. I'm trying to insert a vector of FireSpells into a vector of type vector spells, however, it does not insert.  Is there a way to make it insert?

I've tried the push_back on a FireSpell into a vector of Spells and it works fine, however, it always returns an error when I push_back a FireSpell vector into a vector of type vector Spell.

Magic.h

```<code>struct Fire
{
    int damage;
    int dps;
};

struct Spell
{
    int cost;
    string name;
};

struct FireSpell : Spell, Fire
{

};

</code>```

Magic.cpp

```<code>#include <iostream>
#include "MagicSys.h"
#include <vector>
#include <string>
#include "Magic.h"

using std::cout;
using std::vector;

FireSpell burn;
FireSpell inferno;
FireSpell volcano;

int mainfunc()
{
    vector<vector<Spell>> PlayerSpells;
    vector<FireSpell> PlayerFSpells;
    PlayerFSpells.push_back(burn);
    PlayerFSpells.push_back(inferno);
    PlayerFSpells.push_back(volcano);

 /*Trying to insert FireSpell Vector into the end of the vector of Spell vectors*/

    PlayerSpells.push_back(PlayerFSpells);

    vector<vector<Spell>>::iterator it;
    for (it = PlayerSpells.begin(); it!=PlayerSpells.end(); ++it)
        cout << &it << " ";

    return 0;
}
</code>```

I expected the inner FireSpell vector to insert into the outer Spell vector on the line: PlayerSpells.push_back(PlayerFSpells); , however, it gives me the error message:

```<code>no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back
[with _Ty=std::vector<Spell, std::allocator<Spell>>,
_Alloc=std::allocator<std::vector<Spell, std::allocator<Spell>>>]"
matches the argument list
</code>```

答:
Having

```<code>vector<vector<Spell>> PlayerSpells;
vector<FireSpell> PlayerFSpells;
</code>```

you cannot do

```<code>PlayerSpells.push_back(PlayerFSpells);
</code>```

because a vector<FireSpell> is not a vector<Spell>

Body:
I'm trying to make a vector of vectors in a spell system for a small RPG battle simulation. The main goal I'm trying to accomplish is have a vector of Spells that the player can access and select what type of Spells they want to cast: Fire, Ice, etc. and then choose the name of the spell: burn, frost, etc.

The code below is what I've declared Spell and FireSpell as. I'm trying to insert a vector of FireSpells into a vector of type vector spells, however, it does not insert.  Is there a way to make it insert?

I've tried the push_back on a FireSpell into a vector of Spells and it works fine, however, it always returns an error when I push_back a FireSpell vector into a vector of type vector Spell.

Magic.h

struct Fire
{
    int damage;
    int dps;
};

struct Spell
{
    int cost;
    string name;
};

struct FireSpell : Spell, Fire
{

};

Magic.cpp

#include <iostream>
#include "MagicSys.h"
#include <vector>
#include <string>
#include "Magic.h"

using std::cout;
using std::vector;

FireSpell burn;
FireSpell inferno;
FireSpell volcano;

int mainfunc()
{
    vector<vector<Spell>> PlayerSpells;
    vector<FireSpell> PlayerFSpells;
    PlayerFSpells.push_back(burn);
    PlayerFSpells.push_back(inferno);
    PlayerFSpells.push_back(volcano);

 /*Trying to insert FireSpell Vector into the end of the vector of Spell vectors*/

    PlayerSpells.push_back(PlayerFSpells);

    vector<vector<Spell>>::iterator it;
    for (it = PlayerSpells.begin(); it!=PlayerSpells.end(); ++it)
        cout << &it << " ";

    return 0;
}

I expected the inner FireSpell vector to insert into the outer Spell vector on the line: PlayerSpells.push_back(PlayerFSpells); , however, it gives me the error message:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back
[with _Ty=std::vector<Spell, std::allocator<Spell>>,
_Alloc=std::allocator<std::vector<Spell, std::allocator<Spell>>>]"
matches the argument list

Body:
Having

vector<vector<Spell>> PlayerSpells;
vector<FireSpell> PlayerFSpells;

you cannot do

PlayerSpells.push_back(PlayerFSpells);

because a vector<FireSpell> is not a vector<Spell>


问:
What does (x:) mean in haskell
What does the x: mean in this Code

Implementation of inits using foldr

inits :: [a] -> [[a]]
inits = foldr ( \ x y -> [] : (map (x:) y) ) [[]]
```

答:
This is an effect of the infix operator sectioning [Haskell-wiki]:

(2^) (left section) is equivalent to (^) 2, or more verbosely \x -> 2 ^ x

So (x:) is short for (:) x, or \y -> x : y. The "cons" (:) :: a -> [a] -> [a] is a function that takes an element (type a) and a list (type [a]) and constructs a list with the element followed by the elements in the list.

(x:) :: [a] -> [a] is thus a function that takes a list and prepends that list with x.

We can make the fold function "point free" with:

```<code>foldr (((:) [] .) . map . (:)) [[]]
</code>```

Title: What does (x:) mean in haskell

Body:
This is an effect of the infix operator sectioning [Haskell-wiki]:

(2^) (left section) is equivalent to (^) 2, or more verbosely \x -> 2 ^ x

So (x:) is short for (:) x, or \y -> x : y. The "cons" (:) :: a -> [a] -> [a] is a function that takes an element (type a) and a list (type [a]) and constructs a list with the element followed by the elements in the list.

(x:) :: [a] -> [a] is thus a function that takes a list and prepends that list with x.

We can make the fold function "point free" with:

foldr (((:) [] .) . map . (:)) [[]]


问:
A record is saving as two or more in the database in PHP
A record is saving as two or more in the database. I couldn't find where the problem was.</p>

```<code>if(isset($_POST['send_photo'])){
  if ($_FILES["gallery_photo"]["type"]=="image/jpeg") {
      $photo_name=$_FILES["gallery_photo"]["name"];
      $photo= explode(".", $photo_name);
      $extension=$photo[1];
      $new=md5($photo[0]);
      $newname="uploads/gallery/".$new.".".$extension;
 }
  if (move_uploaded_file($_FILES["gallery_photo"]["tmp_name"],$newname)) {
         $query = $db->query("INSERT INTO gallery (student_id, first_name, last_name, photo) VALUES ( '$student_id', '$first_name', '$last_name', '$newname') ",PDO::FETCH_ASSOC);
         $query->execute(array($newname));
     }
}
</code>```

```<code> <form class="form"  method="post" action="" enctype="multipart/form-data">
                    <div class="text-center">
                        <h6>Photo...</h6>
                        <input type="file" name="gallery_photo" class="text-center center-block file-upload">
                        <button class="btn btn-lg btn-success " type="submit"  name="send_photo"><i class="glyphicon glyphicon-ok-sign"></i> Gönder</button>
                    </div>
                </form>
</code>```

答:
Simply run:

```<code>$db->query("INSERT INTO gallery (student_id, first_name, last_name, photo) VALUES ( '$student_id', '$first_name', '$last_name', '$newname')");
</code>```

and remove the execute line

Body:
A record is saving as two or more in the database. I couldn't find where the problem was.

if(isset($_POST['send_photo'])){
  if ($_FILES["gallery_photo"]["type"]=="image/jpeg") {
      $photo_name=$_FILES["gallery_photo"]["name"];
      $photo= explode(".", $photo_name);
      $extension=$photo[1];
      $new=md5($photo[0]);
      $newname="uploads/gallery/".$new.".".$extension;
 }
  if (move_uploaded_file($_FILES["gallery_photo"]["tmp_name"],$newname)) {
         $query = $db->query("INSERT INTO gallery (student_id, first_name, last_name, photo) VALUES ( '$student_id', '$first_name', '$last_name', '$newname') ",PDO::FETCH_ASSOC);
         $query->execute(array($newname));
     }
}

 <form class="form"  method="post" action="" enctype="multipart/form-data">

Photo...

                        <input type="file" name="gallery_photo" class="text-center center-block file-upload">
                        <button class="btn btn-lg btn-success " type="submit"  name="send_photo"> Gönder</button>

                </form>

Body:
Simply run:

$db->query("INSERT INTO gallery (student_id, first_name, last_name, photo) VALUES ( '$student_id', '$first_name', '$last_name', '$newname')");

and remove the execute line


问:
Is there a DAX function that can run multiple IF statements over a group of ID's?
As you can see I have a list of Id's and the time they were processed and whether it was successful.

What I need is to identify all SapBpId's where the 2ndLatest Date succeeded and the Latest Date failed.

Something Like:
Is2ndLatestDate = "2nd Latest" && IsSuccess = true
IsMaxDate = "Latest" && IsSuccess = false
return SapBpId

Even if the ID has 700 entries I only care about the last 2 date entries and only if it succedded first and then failed on the latest try.

BONUS Points for anyone who can write it in a SQL query that can be run on a Cosmosdb (that's where this data is coming from).

答:
Add the following Column to you table:

```<code>Problem =
var SapId = SAP[SapBpld]
return
COUNTROWS(FILTER(SAP;SAP[SapBpld] = SapId && ((SAP[lsMaxDate] = "Latest" && not SAP[IsSuccess]) || SAP[is2ndLatestDate] = "2nd Latest" && SAP[IsSuccess]))) =2
</code>```

The Column Problem is added and it will set a true on all id's which comply to your needs above

Body:
Add the following Column to you table:

Problem =
var SapId = SAP[SapBpld]
return
COUNTROWS(FILTER(SAP;SAP[SapBpld] = SapId && ((SAP[lsMaxDate] = "Latest" && not SAP[IsSuccess]) || SAP[is2ndLatestDate] = "2nd Latest" && SAP[IsSuccess]))) =2

The Column Problem is added and it will set a true on all id's which comply to your needs above


问:
NetworkType.UNMETERED vs NetworkType.METERED - PeriodicWork
in my application I am using work manager for periodic work. I am uploading files to server. I have one button on click of that button one dialog shown up and ask user - Which network you want to use while uploading file - 1. Wifi 2. Any

If user click on wifi I am uploading file after every 30 Min, If user click on Any I am uploading file after every 1 hr.

Following is my code for this:
1. If user select WIFI

```<code>PeriodicWorkRequest.Builder wifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 30,
                                    TimeUnit.MINUTES)
                                    .addTag("WIFIJOB1")
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).build());
                    wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("wifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);
</code>```

If User select Any:

```<code>PeriodicWorkRequest.Builder mobileDataWorkBuilder =
                                new PeriodicWorkRequest.Builder(FileUpload.class, 1,
                                        TimeUnit.HOURS)
                                        .addTag("MOBILEDATAJOB1")
                                        .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build());
                        mobileDataWork = mobileDataWorkBuilder.build();
                        WorkManager.getInstance().enqueueUniquePeriodicWork("mobileDataJob", ExistingPeriodicWorkPolicy.REPLACE, mobileDataWork);
</code>```

For any network it works perfectly and upload apk after every 1 hr. But if user select Wifi then here is problem -

If user connected to wifi of other mobile(say he is using hotspot) so here network is I guess consider as Metered network so it will not upload file. I just want to know our House or office network are by default are Unmetered network or not. If suppose its not fix (Means some are metered and some are unmetered) then using this code if user select wifi and user wifi is considered as metered then from his device file will never get uploaded.

Or should I create another task like :

```<code>PeriodicWorkRequest.Builder meteredwifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 45,
                                    TimeUnit.MINUTES)
                                    .addTag("METEREDWIFIJOB")
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.METERED).build());
                    wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("meteredwifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);
</code>```

So if user not connected to wifi file will be uploaded after every 1 hr, If connected to wifi (unmetered) file will be uploaded after every 30 min and if connected to metered wifi then file will be uploaded after every 45 min.

Is above logic make sense to create 3 sepearte task to upload file. Any suggestion will be appreciated. Thanks in advance

答: If all you care about is a presence of a network connection just use NetworkType.CONNECTED. If the file is very big, and could cost the user (as they will end up using an expensive data connection) you should use NetworkType.UNMETERED.

Body:
in my application I am using work manager for periodic work. I am uploading files to server. I have one button on click of that button one dialog shown up and ask user - Which network you want to use while uploading file - 1. Wifi 2. Any

If user click on wifi I am uploading file after every 30 Min, If user click on Any I am uploading file after every 1 hr.

Following is my code for this:
1. If user select WIFI

PeriodicWorkRequest.Builder wifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 30,
                                    TimeUnit.MINUTES)
                                    .addTag("WIFIJOB1")
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).build());
                    wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("wifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);

If User select Any:

PeriodicWorkRequest.Builder mobileDataWorkBuilder =
                                new PeriodicWorkRequest.Builder(FileUpload.class, 1,
                                        TimeUnit.HOURS)
                                        .addTag("MOBILEDATAJOB1")
                                        .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build());
                        mobileDataWork = mobileDataWorkBuilder.build();
                        WorkManager.getInstance().enqueueUniquePeriodicWork("mobileDataJob", ExistingPeriodicWorkPolicy.REPLACE, mobileDataWork);

For any network it works perfectly and upload apk after every 1 hr. But if user select Wifi then here is problem -

If user connected to wifi of other mobile(say he is using hotspot) so here network is I guess consider as Metered network so it will not upload file. I just want to know our House or office network are by default are Unmetered network or not. If suppose its not fix (Means some are metered and some are unmetered) then using this code if user select wifi and user wifi is considered as metered then from his device file will never get uploaded.

Or should I create another task like :

PeriodicWorkRequest.Builder meteredwifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 45,
                                    TimeUnit.MINUTES)
                                    .addTag("METEREDWIFIJOB")
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.METERED).build());
                    wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("meteredwifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);

So if user not connected to wifi file will be uploaded after every 1 hr, If connected to wifi (unmetered) file will be uploaded after every 30 min and if connected to metered wifi then file will be uploaded after every 45 min.

Is above logic make sense to create 3 sepearte task to upload file. Any suggestion will be appreciated. Thanks in advance


问:
How do i dynamically assign table IDs?
I am writing a PHP script which is running a for loop. I am creating multiple tables inside the loop and i want to dynamically name the tables based on the loop.

I have already tried the following code but it doesn't work:

```<code><table id="gameweek_history<? echo $i; ?>">
<script>function doCSV<? echo $i; ?>() {
    var table1 = document.getElementById("gameweek_history<? echo $i; ?>").innerHTML;
<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>
</code>```

Could you please explain to me what i need to change ?

答:
```<code><?php

$count = 3;
for($i=0; $i<$count; $i++) {

?>

    <table id ="gameweek_history<?php echo $i; ?>">

            <script>function doCSV<?php echo $i; ?>() {
            var table1 = document.getElementById("gameweek_history<?php echo $i; ?>").innerHTML;

            <button onclick="doCSV(<?php echo $i; ?>)">Export HTML Table To CSV File</button>
    </table>

<?php
}
?>
</code>```

gives output:

```<code><table id ="gameweek_history0">

            <script>function doCSV0() {
            var table1 = document.getElementById("gameweek_history0").innerHTML;

            <button onclick="doCSV(0)">Export HTML Table To CSV File</button>
    </table>

    <table id ="gameweek_history1">

            <script>function doCSV1() {
            var table1 = document.getElementById("gameweek_history1").innerHTML;

            <button onclick="doCSV(1)">Export HTML Table To CSV File</button>
    </table>

    <table id ="gameweek_history2">

            <script>function doCSV2() {
            var table1 = document.getElementById("gameweek_history2").innerHTML;

            <button onclick="doCSV(2)">Export HTML Table To CSV File</button>
    </table>
</code>```

Title: How do i dynamically assign table IDs?

Body:
I am writing a PHP script which is running a for loop. I am creating multiple tables inside the loop and i want to dynamically name the tables based on the loop.

I have already tried the following code but it doesn't work:

<table id="gameweek_history<? echo $i; ?>">

Body:
<?php

$count = 3;
for($i=0; $i<$count; $i++) {

?>

    <table id ="gameweek_history<?php echo $i; ?>">

            <script>function doCSV<?php echo $i; ?>() {
            var table1 = document.getElementById("gameweek_history<?php echo $i; ?>").innerHTML;

            <button onclick="doCSV(<?php echo $i; ?>)">Export HTML Table To CSV File</button>
    </table>

<?php
}
?>

gives output:

<table id ="gameweek_history0">

            <script>function doCSV0() {
            var table1 = document.getElementById("gameweek_history0").innerHTML;

            <button onclick="doCSV(0)">Export HTML Table To CSV File</button>
    </table>

    <table id ="gameweek_history1">

            <script>function doCSV1() {
            var table1 = document.getElementById("gameweek_history1").innerHTML;

            <button onclick="doCSV(1)">Export HTML Table To CSV File</button>
    </table>

    <table id ="gameweek_history2">

            <script>function doCSV2() {
            var table1 = document.getElementById("gameweek_history2").innerHTML;

            <button onclick="doCSV(2)">Export HTML Table To CSV File</button>
    </table>


问:
MySQL Return JSON array index based on property value
I have a table with JSON data like this:

```<code>{"a": [{"color": "blue", "value": 15}, {"color": "red", "value": 30}]}
</code>```

I need to get the "value" that is inside the same object of "blue".

I thought to use the code below:

```<code>SELECT JSON_EXTRACT(my_data, '$.a[0].value');
</code>```

The problem is that the "blue" object can be in any index of the array.

So, is there a way to retrieve the index first and then i'll query using the right index?

UPDATE

The Barmar's answer works but it needs to wrap in JSON_UNQUOTE()

答:
Here's an example of using JSON_TABLE():

```<code>select j.* from d, json_table(d.data, '$.a[*]' columns (
  color varchar(20) path '$.color',
  value int path '$.value')
) as j;
+-------+-------+
| color | value |
+-------+-------+
| blue  |    15 |
| red   |    30 |
+-------+-------+
</code>```

You can then apply conditions in the WHERE clause, as if you had stored the data in a normal table.

```<code>select j.* from d, json_table(d.data, '$.a[*]' columns (
  color varchar(20) path '$.color',
  value int path '$.value')
) as j
where j.color = 'blue';
+-------+-------+
| color | value |
+-------+-------+
| blue  |    15 |
+-------+-------+
</code>```

This requires you to write a complex query like this EVERY TIME you query the JSON data.

One wonders if it would have been easier to store the JSON in a normal table from the start.

I often recommend to MySQL users that storing data as JSON makes more work for you, if you need to make SQL expressions to reference individual fields within the JSON. I wouldn't use JSON in these cases, I'd explode the JSON array into rows, and the JSON fields into columns of a set of normal tables. Then you can write simpler queries, you can optimize with indexes, and you can use constraints and data types properly.

JSON is the most easily misused feature of the recent MySQL releases.

Body:
I have a table with JSON data like this:

{"a": [{"color": "blue", "value": 15}, {"color": "red", "value": 30}]}

I need to get the "value" that is inside the same object of "blue".

I thought to use the code below:

SELECT JSON_EXTRACT(my_data, '$.a[0].value');

The problem is that the "blue" object can be in any index of the array.

So, is there a way to retrieve the index first and then i'll query using the right index?

UPDATE

The Barmar's answer works but it needs to wrap in JSON_UNQUOTE()

Body:
Here's an example of using JSON_TABLE():

select j.* from d, json_table(d.data, '$.a[*]' columns (
  color varchar(20) path '$.color',
  value int path '$.value')
) as j;
+-------+-------+
| color | value |
+-------+-------+
| blue  |    15 |
| red   |    30 |
+-------+-------+

You can then apply conditions in the WHERE clause, as if you had stored the data in a normal table.

select j.* from d, json_table(d.data, '$.a[*]' columns (
  color varchar(20) path '$.color',
  value int path '$.value')
) as j
where j.color = 'blue';
+-------+-------+
| color | value |
+-------+-------+
| blue  |    15 |
+-------+-------+

This requires you to write a complex query like this EVERY TIME you query the JSON data.

One wonders if it would have been easier to store the JSON in a normal table from the start.

I often recommend to MySQL users that storing data as JSON makes more work for you, if you need to make SQL expressions to reference individual fields within the JSON. I wouldn't use JSON in these cases, I'd explode the JSON array into rows, and the JSON fields into columns of a set of normal tables. Then you can write simpler queries, you can optimize with indexes, and you can use constraints and data types properly.

JSON is the most easily misused feature of the recent MySQL releases.


问:
Maven local repo in a common global directory for multiple parallel execution
I have a machine in which multiple parallel maven execution happen. Each execution executes the below command in a separate workspace directory

mvn -f main/pom.xml clean package -DskipTests -T 6

Can someone let me know should I use a separate maven local repo path (-Dmaven.repo.local=$MAVEN_REPO) for each execution or I can use a common .m2 directory for all parallel runs? What is the common practice followed?

Maven Version 3.5

Java 8

答: You cannot share a local repository between executions. They are not implemented to tolerate multiple concurrent processes accessing them. You can and should run a local caching repository manager in between your processes and repositories on the internet. That can be shared.</p>


问:
How to get Age in Months using BirthDate column by MySQL query?
First I asked this question to do this and accepted answer helped me. But Now the problem is that I have to calculate age in months.

Question:

I have a BirthDate column in MySQL database table to store user's date of birth. Now I have form in html/php with two fields(1. Age From 2. Age To).

If user want to get all users where their ages are between 400 months and 600 months, Is it possible to do this with MySQL query using BirthDate column.

Thanks

答:
```
<code>
select * from [table]
where
BirthDate&gt= date_sub(curdate(),interval 600 MONTH)
and
BirthDate&lt= date_sub(curdate(),interval 400 MONTH)
</code>
```

ContentLicense: CC BY-SA 3.0


问:
How can I get %i Ruby arrays to be properly highlighted in Vim?
My Vim is not highlighting the relatively new %i syntax. Here's an example:

I included a %w example, which works properly, to show the desired effect.

How can I get Vim to highlight %i properly?

答:
If you’d type :syn ⏎ in control mode while editing any ruby file, you’ll see all the syntax definitions (or open system-wide syntax theme for ruby /usr/share/vim/vim81/syntax/ruby.vim or where is it located.)

The one responsible for %i[] would be rubySymbol.

%i[] is by no mean “relatively new,” the issue is your color theme does not highlight symbols differently. Not only literals, all the symbols. Run:

```<code>:hi rubySymbol term=bold ctermfg=Red
</code>```

and you’ll see it perfectly works. You might tune it according to your needs (see e. g. rubyString for the inspiration) and put this somewhere in your ~/.vim/syntax/ruby.vim.

Body:
If you’d type :syn ⏎ in control mode while editing any ruby file, you’ll see all the syntax definitions (or open system-wide syntax theme for ruby /usr/share/vim/vim81/syntax/ruby.vim or where is it located.)

The one responsible for %i[] would be rubySymbol.

%i[] is by no mean “relatively new,” the issue is your color theme does not highlight symbols differently. Not only literals, all the symbols. Run:

:hi rubySymbol term=bold ctermfg=Red

and you’ll see it perfectly works. You might tune it according to your needs (see e. g. rubyString for the inspiration) and put this somewhere in your ~/.vim/syntax/ruby.vim.


问:
How to return fields of both related models in a Django ManyToMany relation?
I have two models:

class P(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...

class F(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...
    p = models.ManyToManyField(P)
```

<p>I need a query like this:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT p.name, f.name
FROM f
JOIN f_p ON f.id = f_p.f_id
JOIN p ON p.id= f_p.p_id
</code>```

I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names.

In psql the query works like I need. How can I do this in Django?

答:
Try values_list docs

F.objects.values_list('name', 'p__name')
```

Body:
I have two models:

class P(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...

class F(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...
    p = models.ManyToManyField(P)

I need a query like this:

SELECT p.name, f.name
FROM f
JOIN f_p ON f.id = f_p.f_id
JOIN p ON p.id= f_p.p_id

I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names.

In psql the query works like I need. How can I do this in Django?


答:
You should remove the PHP code from your javascript. Write it this way:</p>

```<code><script>function doCSV(i) {
   var table1 = document.getElementById("gameweek_history"+i).innerHTML;
   // do something here with table1
</script>

<table id ="gameweek_history<? echo $i; ?>">
<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>
</code>```

Title: How do i dynamically assign table IDs?

Body:
You should remove the PHP code from your javascript. Write it this way:

<script>function doCSV(i) {
   var table1 = document.getElementById("gameweek_history"+i).innerHTML;
   // do something here with table1
</script>

<table id ="gameweek_history<? echo $i; ?>">
<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>


问:
Draft, Publish and versioning of resource with REST
I am developing a webservice where all the intermediate changes should be versioned(Drafts), And users can publish (Live their changes). For users to keep referring older versions (for let's say compatibility reasons.) users should be able to get older states as well.

Here is how my current design looks like

```<code>+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+
|      action      |                  request                  |                            response                          |                state of resource                |
+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+
| create a post    | post                                      | status=201 id=123 and version=v1                             | resource created with version v1                |
| update the post  | put with id=123 and version=v1            | status=200 id=123 and version=v2                             | new version of resource created with version=v2 |
| update the post  | put with id=123 and version=v2            | status=200 id=123 and version=v3                             | new version of resource created with version=v3 |
| update the post  | put with id=123 version=v1                | status=409 and body indicating user is editing stale version |                                                 |
| publish the post | put with id=123 version=v2 action=publish | status=200 id=123 version=p1 (p indicating published)        | new version created with version=p1             |
| get all versions | get list with id=123 status=all           | status=200 and v1,v2,p1 in the body                          | no change                                       |
+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+
</code>```

Does the above follow rest architecture?
The particular issues I am worried about are

Here Put is not idempotent since it ends up creating a new version every time we do it.

User has to be aware of action=Publish for publishing the article. is it ok to have this information at client side IMO in the response body of put/get/post we should tell all the operations that are supported something like this

```<code>{
  "body": {...}
  "actions": [
    {
      "type": "publish",
      "uri": "/order/123/publish"
    },
    {
      "type": "save",
      "uri": "/order/123/save"
    },
    {
      "type": "archive",
      "uri": "/order/123/archive"
    }
  ]
}
</code>```

Is there anything I am missing

Is it overly pedantic about details?

答:
Given that you're using a hateoas-style approach, I would recommend the following:

Have one uri that always represents the latest version. For instance /order/123.

Create links with relation types from RFC5829 to other versions. Examples: version-history, latest-version, predecessor-version, successor-version. Use just the link relations that you need. Different versions are simply different resources.

Instead of using an action, you can mark a resource as either public or draft using a property (for example isPublic). If set to true, that version becomes the public version. The last  'version' with that status would become the one that's really 'live'.

Solving the PUT idempotency issue

Given that PUT creates a new 'version' every time you run it, is it still idempotent? I think this becomes a little tougher to answer. Is the effect of 2 PUT requests the same as just doing 1?

Well if you consider HTTP access logs, 2 identical PUT requests will also cause 2 entries. I don't really know how to reconcile this, but my thinking is:

2 identical PUT requests still creates the intended state. An update to the main resource. There is now an extra (versioned) resource, but maybe that doesn't really matter?

You could opt to not create a new version of the resource if it hadn't actually changed, circumventing this completely.

Body:
I am developing a webservice where all the intermediate changes should be versioned(Drafts), And users can publish (Live their changes). For users to keep referring older versions (for let's say compatibility reasons.) users should be able to get older states as well.

Here is how my current design looks like

+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+
|      action      |                  request                  |                            response                          |                state of resource                |
+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+
| create a post    | post                                      | status=201 id=123 and version=v1                             | resource created with version v1                |
| update the post  | put with id=123 and version=v1            | status=200 id=123 and version=v2                             | new version of resource created with version=v2 |
| update the post  | put with id=123 and version=v2            | status=200 id=123 and version=v3                             | new version of resource created with version=v3 |
| update the post  | put with id=123 version=v1                | status=409 and body indicating user is editing stale version |                                                 |
| publish the post | put with id=123 version=v2 action=publish | status=200 id=123 version=p1 (p indicating published)        | new version created with version=p1             |
| get all versions | get list with id=123 status=all           | status=200 and v1,v2,p1 in the body                          | no change                                       |
+------------------+-------------------------------------------+--------------------------------------------------------------+-------------------------------------------------+

Does the above follow rest architecture?
The particular issues I am worried about are

Here Put is not idempotent since it ends up creating a new version every time we do it.

User has to be aware of action=Publish for publishing the article. is it ok to have this information at client side IMO in the response body of put/get/post we should tell all the operations that are supported something like this

{
  "body": {...}
  "actions": [
    {
      "type": "publish",
      "uri": "/order/123/publish"
    },
    {
      "type": "save",
      "uri": "/order/123/save"
    },
    {
      "type": "archive",
      "uri": "/order/123/archive"
    }
  ]
}

Is there anything I am missing

Is it overly pedantic about details?


问:
Including a lightbox slideshow on a Drupal Views Page
I'm creating a page which consists of pieces of Equipment.  Each equipment has 2-5 images uploaded.  I'm making a listing of all of these and would like to display it as follows:

```<code>Title 1
Overview
Slider of image thumbnails -- click to see full sized image
---
Title 2
Overview
Slider of image thumbnails -- click to see full sized image
</code>```

etc.

I assumed Lightbox/Views/Imagecache/CCK would make this easy, but I have not been able to pull this off.  I'm also having trouble coming up with the right search terms.

Seems easy.  Thanks much for any help.

答:
Create a CCK field in equipment called (field_equip_images). In number of values in the settings, select 'Unlimited'

In the view filter by type equipment. Select the fields Title, Overview and Images(field_equip_images).

In the settings of Images(field_equip_images) from the format at the bottom select Lightbox2: thumbnail->full_sized_image

Body:
I'm creating a page which consists of pieces of Equipment.  Each equipment has 2-5 images uploaded.  I'm making a listing of all of these and would like to display it as follows:

Title 1
Overview
Slider of image thumbnails -- click to see full sized image
---
Title 2
Overview
Slider of image thumbnails -- click to see full sized image

etc.

I assumed Lightbox/Views/Imagecache/CCK would make this easy, but I have not been able to pull this off.  I'm also having trouble coming up with the right search terms.

Seems easy.  Thanks much for any help.


问:
Mongo $lookup $pipeline with several $expr parameters not returning correct data in $lookup results
I have two mongo collections one containing appointment reminders and the other containing notifications. I'm attempting to return results with all archive: false reminders in a given branchId / clinic_id and include their acknowledged: false notifications. Also, I want to make sure the appointments show up in the results regardless if they have notifications or not.

I need to 'join' the collections by branchId aka clinic_id and then create an array of any unacknowledged notifications for each resulting appointment reminder.

I'm returning correct appointments, but the notif array is not getting filtered by matching patientId / patient_id. Each reminder seems to contain the exact same notif array. Other than this everything else seems to be correct. So, my question is how can I ensure the notif array only contains a patientId that matches the patient_id value of the reminder?

Truncated Appointment Reminder Schema:

```<code>      {
      time: {
        type: Date,
        required: true
      },
  patient_id: {
    type: String,
    required: true
  },
      status: {
        type: String,
        default: 'unconfirmed'
      },
      archive: {
        type: Boolean,
        default: false
      },
      branch: [
    // Incorrectly setup as an array rather than an object.
    // Can $unwind as there is only ever one item in the array
        {
          name: {
            type: String,
            required: true
          },
          clinic_id: { // aka branchId
            type: String,
            required: true
          }
        }
      ]
    }
</code>```

Notification Schema:

```<code>{
  branchId: { type: String, required: true }, // aka clinic_id
  patientId: { type: String, required: true },
  acknowledged: { type: Boolean, default: false },
  date: { type: Date, default: Date.now }
}
</code>```

Aggregation Query:

```<code>[
  { $match: { 'branch.0.clinic_id': '1', archive: false } },
  { $unwind: '$branch' },
  {
    $lookup: {
      from: 'notifications',
      let: { clinic_id: '1', patient_id: '$patientId' }, //<-- issue with patient_id?
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
               { $eq: ["$patientId", "$$patientId"] }, <-- errors $$patientId unknown value. $$patient_id returns 0 results.
                { $eq: ['$branchId', '$$clinic_id'] },
                { $eq: ['$acknowledged', false] }
              ]
            }
          }
        }
      ],
      as: 'notif'
    }
  }
]
</code>```

Example Output with comments on desired output and incorrect output I've experienced:

```<code>  {
  patient_id: '1',
  time: '2019-05-29T11:00:00.000Z',
  status: 'unconfirmed',
  archive: false,
  branch: [
    {
      name: 'Example location',
      clinic_id: '100',
    }
  ],
  notif: [
  {
    // This is correct
    branchId: '100', // branchId matches clinic_id
    patientId: '1',  // patientId matches contacts patient_id
    acknowledged: false, // notification is unacknowledged
    date: '2019-05-18T16:18:05.480Z'
  },
  {
   // This is not correct
    branchId: '100',
    patientId: '2', // PatientId does not match patient_id of reminder
    acknowledged: false,
    date: '2019-05-20T16:18:05.480Z'
  }
  ]
}
</code>```

答:
With the help of tom slabbaert, this solved the issue:</p>

```<code>[
        { $match: { 'branch.clinic_id': '1', archive: false } },
        { $unwind: '$branch' },
        {
          $lookup: {
            from: 'notifications',
            let: { clinic_id: '1', patient_id: '$patient_id' }, // <-- changed here
            pipeline: [
              {
                $match: {
                  $expr: {
                    $and: [
                      { $eq: ["$$patient_id", "$patientId"]}, // <-- changed here
                      { $eq: ['$branchId', '$$clinic_id'] },
                      { $eq: ['$acknowledged', false] }
                    ]
                  }
                }
              }
            ],
            as: 'notif'
          }
        }
      ]
</code>```

Body:
I have two mongo collections one containing appointment reminders and the other containing notifications. I'm attempting to return results with all archive: false reminders in a given branchId / clinic_id and include their acknowledged: false notifications. Also, I want to make sure the appointments show up in the results regardless if they have notifications or not.

I need to 'join' the collections by branchId aka clinic_id and then create an array of any unacknowledged notifications for each resulting appointment reminder.

I'm returning correct appointments, but the notif array is not getting filtered by matching patientId / patient_id. Each reminder seems to contain the exact same notif array. Other than this everything else seems to be correct. So, my question is how can I ensure the notif array only contains a patientId that matches the patient_id value of the reminder?

Truncated Appointment Reminder Schema:

      {
      time: {
        type: Date,
        required: true
      },
  patient_id: {
    type: String,
    required: true
  },
      status: {
        type: String,
        default: 'unconfirmed'
      },
      archive: {
        type: Boolean,
        default: false
      },
      branch: [
    // Incorrectly setup as an array rather than an object.
    // Can $unwind as there is only ever one item in the array
        {
          name: {
            type: String,
            required: true
          },
          clinic_id: { // aka branchId
            type: String,
            required: true
          }
        }
      ]
    }

Notification Schema:

{
  branchId: { type: String, required: true }, // aka clinic_id
  patientId: { type: String, required: true },
  acknowledged: { type: Boolean, default: false },
  date: { type: Date, default: Date.now }
}

Aggregation Query:

[
  { $match: { 'branch.0.clinic_id': '1', archive: false } },
  { $unwind: '$branch' },
  {
    $lookup: {
      from: 'notifications',
      let: { clinic_id: '1', patient_id: '$patientId' }, //<-- issue with patient_id?
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
               { $eq: ["$patientId", "$$patientId"] }, <-- errors $$patientId unknown value. $$patient_id returns 0 results.
                { $eq: ['$branchId', '$$clinic_id'] },
                { $eq: ['$acknowledged', false] }
              ]
            }
          }
        }
      ],
      as: 'notif'
    }
  }
]

Example Output with comments on desired output and incorrect output I've experienced:

  {
  patient_id: '1',
  time: '2019-05-29T11:00:00.000Z',
  status: 'unconfirmed',
  archive: false,
  branch: [
    {
      name: 'Example location',
      clinic_id: '100',
    }
  ],
  notif: [
  {
    // This is correct
    branchId: '100', // branchId matches clinic_id
    patientId: '1',  // patientId matches contacts patient_id
    acknowledged: false, // notification is unacknowledged
    date: '2019-05-18T16:18:05.480Z'
  },
  {
   // This is not correct
    branchId: '100',
    patientId: '2', // PatientId does not match patient_id of reminder
    acknowledged: false,
    date: '2019-05-20T16:18:05.480Z'
  }
  ]
}

Body:
With the help of tom slabbaert, this solved the issue:

[
        { $match: { 'branch.clinic_id': '1', archive: false } },
        { $unwind: '$branch' },
        {
          $lookup: {
            from: 'notifications',
            let: { clinic_id: '1', patient_id: '$patient_id' }, // <-- changed here
            pipeline: [
              {
                $match: {
                  $expr: {
                    $and: [
                      { $eq: ["$$patient_id", "$patientId"]}, // <-- changed here
                      { $eq: ['$branchId', '$$clinic_id'] },
                      { $eq: ['$acknowledged', false] }
                    ]
                  }
                }
              }
            ],
            as: 'notif'
          }
        }
      ]


问:
[Vue warn]: Unknown custom element: <network> - did you register the component correctly? vue-social-share
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

```<code>import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
</code>```

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

```

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

答:
This is how you register component globally:

```<code>const SocialSharing = require('vue-social-sharing');
Vue.component('social-sharing', SocialSharing)
</code>```

vue docs

Body:
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

Body:
This is how you register component globally:

const SocialSharing = require('vue-social-sharing');
Vue.component('social-sharing', SocialSharing)

vue docs


问:
pygame on MacOs won't show any surfaces
I'm following a very basic pygame tutorial, which I've done before. I'm suspecting there's a version issue, though I'm at a loss how to move forward.

```<code>macOS 10.14.4
Python 3.7.2
pip 18.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
</code>```

code:

```<code>import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800,600))

surf = pygame.Surface((75,25))
surf.fill((125,125,125))
# What does this rect do?
rect = surf.get_rect()

running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False
    screen.blit(surf, (400,300))
    pygame.display.flip()
</code>```

The only question I have there is what is that rect assignment for? I can't blit the rect, so it appears to have no purpose.

I've gone through a couple other tutorials, copy-pasted code and I get the same result with each one: a white screen with no rectangles. It's as if the display code works, but any other surface just don't appear.

No errors in the console. I'm really not sure how to debug at this point.

答:
There is nothing to debug here. rect = surf.get_rect() is not used, maybe like martineau said in the comment will be used later in the tutorial.

What the code is doing is to draw a small gray rectangle on a gray surface (that's why you do not see anything).

```<code>surf = pygame.Surface((75,25))
</code>```

This creates a small gray surface, which is blit later in the main loop at coordinates (top-left corner) 400, 300:

```<code>screen.blit(surf, (400,300))
</code>```

As I said, the reason you do not see it is because surf il filled with gray (this line):

```<code>surf.fill((125,125,125))
</code>```

and your background is gray too. I do not know if this is system dependent, on my linux the background is black and the rectangle is clearly visible.

So try to change the color of the rectangle to something clearer or darker, or fill the display surface with black before the main loop by doing:

```<code>screen.fill((0, 0, 0))
</code>```

Title: pygame on MacOs won't show any surfaces

Body:
I'm following a very basic pygame tutorial, which I've done before. I'm suspecting there's a version issue, though I'm at a loss how to move forward.

macOS 10.14.4
Python 3.7.2
pip 18.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

code:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800,600))

surf = pygame.Surface((75,25))
surf.fill((125,125,125))
# What does this rect do?
rect = surf.get_rect()

running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False
    screen.blit(surf, (400,300))
    pygame.display.flip()

The only question I have there is what is that rect assignment for? I can't blit the rect, so it appears to have no purpose.

I've gone through a couple other tutorials, copy-pasted code and I get the same result with each one: a white screen with no rectangles. It's as if the display code works, but any other surface just don't appear.

No errors in the console. I'm really not sure how to debug at this point.

Body:
There is nothing to debug here. rect = surf.get_rect() is not used, maybe like martineau said in the comment will be used later in the tutorial.

What the code is doing is to draw a small gray rectangle on a gray surface (that's why you do not see anything).

surf = pygame.Surface((75,25))

This creates a small gray surface, which is blit later in the main loop at coordinates (top-left corner) 400, 300:

screen.blit(surf, (400,300))

As I said, the reason you do not see it is because surf il filled with gray (this line):

surf.fill((125,125,125))

and your background is gray too. I do not know if this is system dependent, on my linux the background is black and the rectangle is clearly visible.

So try to change the color of the rectangle to something clearer or darker, or fill the display surface with black before the main loop by doing:

screen.fill((0, 0, 0))


问:
Is there a way to draw a rectangle into a PdfPCell in iText (the Java version)?
I found some tutorials about how to draw forms in iText, but I need to insert it into a cell, and I don´t know how.
Thank you for your consideration of this matter.</p>

答:
Since google is not giving any good responses for a complete code example of this and I spent a lot of time trying to figure out how to do this (even if Jes explanation now seems pretty clear...) I figured I'll post an example so further seekers can have a complete code example.</p>

```<code>PdfPTable table = new PdfPTable(1);
table.setTotalWidth(450);

PdfTemplate template = cb.createTemplate(30, 30);
template .setLineWidth(0.5f);
template .rectangle(0, 0, 17f, 17f);
template .stroke();

Image img = Image.getInstance(template);
Chunk chunk = new Chunk(img, 1f, 1f);

PdfPCell cell = new PdfPCell();
cell.addElement(chunk);
table.addCell(cell);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Since google is not giving any good responses for a complete code example of this and I spent a lot of time trying to figure out how to do this (even if Jes explanation now seems pretty clear...) I figured I'll post an example so further seekers can have a complete code example.

PdfPTable table = new PdfPTable(1);
table.setTotalWidth(450);

PdfTemplate template = cb.createTemplate(30, 30);
template .setLineWidth(0.5f);
template .rectangle(0, 0, 17f, 17f);
template .stroke();

Image img = Image.getInstance(template);
Chunk chunk = new Chunk(img, 1f, 1f);

PdfPCell cell = new PdfPCell();
cell.addElement(chunk);
table.addCell(cell);


问:
Why does TypeScript force me to explicitly pass undefined for an argument that's typed as undefined in my function signature?
I'm a junior dev and I need help. I've tried googling the problem, but I'm having a hard time phrasing it the right way. Sorry in advance if the question is misleading.

Can someone please help me understand why TypeScript is forcing me to pass undefined as an argument to a function when I have the parameter typed as undefined in the function signature?

Here's what I'm trying to do. I want to create a function that returns action-creator functions, which then return action objects:

```<code>interface IAction<T, P> {
    type: T;
    payload?: P;
}

const createActionCreator = <T extends string, P = undefined>(type: T) => (payload: P): IAction<T, P> => ({
    type,
    payload,
});

const THIS_IS_MY_ACTION_TYPE = '@PREFIXED/THIS_IS_MY_ACTION_TYPE';

const createTestAction1 = createActionCreator<typeof THIS_IS_MY_ACTION_TYPE, string>(THIS_IS_MY_ACTION_TYPE);

const createTestAction2 = createActionCreator<typeof THIS_IS_MY_ACTION_TYPE>(THIS_IS_MY_ACTION_TYPE);

const testAction1 = createTestAction1('some string');
// works fine

const testAction2 = createTestAction2();
// TypeScript complains that an argument was expected
</code>```

When I invoke createActionCreator providing both the T and P types, TypeScript forces me to invoke createTestAction1 with an argument that matches the P type. This is what I expect.

When I invoke createActionCreator without providing the P, or even if I provide the P as undefined explicitly, TypeScript forces me to invoke createTestAction2 with undefined as an argument. I would expect to be able to invoke it without an argument.

I would appreciate it if someone could help me understand why it behaves this way and how to fix it. Thanks in advance.

答:
I was able to achieve what I wanted with function signature overloading and a payloadRequired argument in the first invocation, to determine whether to return the inner function with or without a payload parameter:</p>

```<code>export interface IAction<T extends IActionConstant, P = undefined> {
    type: T;
    payload?: P;
}

export function createActionCreator<T extends IActionConstant, P = 'Please provide a type definition for the payload'>(
    type: T,
    config: { withPayload: true }
): (payload: P) => IAction<T, P>;
export function createActionCreator<T extends IActionConstant>(
    type: T,
    config: { withPayload: false }
): () => IAction<T>;
export function createActionCreator<T extends IActionConstant, P>(type: T, config: { withPayload: boolean }) {
    if (config.withPayload) {
        return function createAction(payload: P) {
            return {
                type,
                payload,
            };
        };
    }
    return function createAction() {
        return {
            type,
        };
    };
}
</code>```

Body:
I'm a junior dev and I need help. I've tried googling the problem, but I'm having a hard time phrasing it the right way. Sorry in advance if the question is misleading.

Can someone please help me understand why TypeScript is forcing me to pass undefined as an argument to a function when I have the parameter typed as undefined in the function signature?

Here's what I'm trying to do. I want to create a function that returns action-creator functions, which then return action objects:

interface IAction<T, P> {
    type: T;
    payload?: P;
}

const createActionCreator = <T extends string, P = undefined>(type: T) => (payload: P): IAction<T, P> => ({
    type,
    payload,
});

const THIS_IS_MY_ACTION_TYPE = '@PREFIXED/THIS_IS_MY_ACTION_TYPE';

const createTestAction1 = createActionCreator<typeof THIS_IS_MY_ACTION_TYPE, string>(THIS_IS_MY_ACTION_TYPE);

const createTestAction2 = createActionCreator<typeof THIS_IS_MY_ACTION_TYPE>(THIS_IS_MY_ACTION_TYPE);

const testAction1 = createTestAction1('some string');
// works fine

const testAction2 = createTestAction2();
// TypeScript complains that an argument was expected

When I invoke createActionCreator providing both the T and P types, TypeScript forces me to invoke createTestAction1 with an argument that matches the P type. This is what I expect.

When I invoke createActionCreator without providing the P, or even if I provide the P as undefined explicitly, TypeScript forces me to invoke createTestAction2 with undefined as an argument. I would expect to be able to invoke it without an argument.

I would appreciate it if someone could help me understand why it behaves this way and how to fix it. Thanks in advance.

Body:
I was able to achieve what I wanted with function signature overloading and a payloadRequired argument in the first invocation, to determine whether to return the inner function with or without a payload parameter:

export interface IAction<T extends IActionConstant, P = undefined> {
    type: T;
    payload?: P;
}

export function createActionCreator<T extends IActionConstant, P = 'Please provide a type definition for the payload'>(
    type: T,
    config: { withPayload: true }
): (payload: P) => IAction<T, P>;
export function createActionCreator<T extends IActionConstant>(
    type: T,
    config: { withPayload: false }
): () => IAction<T>;
export function createActionCreator<T extends IActionConstant, P>(type: T, config: { withPayload: boolean }) {
    if (config.withPayload) {
        return function createAction(payload: P) {
            return {
                type,
                payload,
            };
        };
    }
    return function createAction() {
        return {
            type,
        };
    };
}


问:
Angular 7 parameter route is overriding non parameter route
I am using modular structure for my project.

Parent route is

```<code> { path: 'questions', loadChildren: '../questions/questions.module#QuestionsModule'}
</code>```

and in child I have :

```<code>const routes: Routes = [
{
path: '',
component: QuestionComponent,
children: [
  {
     path: ':id',
     component: ViewComponent,
  },

  {
    path: 'ask',
    component: AskComponent,
    pathMatch: 'full'
  },
  {
    path: '',
    redirectTo:'/:id',
    pathMatch:'full'
 },
]}];
</code>```

for both http://localhost:4200/questions/123 and http://localhost:4200/questions/ask routes ,
ViewComponent is loading.

Here is my folder structure with routing: https://stackblitz.com/edit/angular-sjd9u9

答:
Considering the routes in your Questions routing module:

```<code>const routes: Routes = [
{
path: '',
component: QuestionComponent,
children: [
  {
     path: ':id',
     component: ViewComponent,
  },

  {
    path: 'ask',
    component: AskComponent,
    pathMatch: 'full'
  },
  {
    path: '',
    redirectTo:'/:id',
    pathMatch:'full'
 },
]}];
</code>```

:id is just a slot in the path to hold a route parameter.

When you navigate to http://localhost:4200/questions/ask, you end up with the following situation:

:id === 'ask'

Now, looking at the first path:

```<code>{
  path: ':id',
  component: ViewComponent,
}
</code>```

The router finds a match using :id === 'ask' and therefore renders ViewComponent.

To fix this, you can change your routes to the following:

```<code>const routes: Routes = [
  {
    path: '',
    component: QuestionComponent,
    children: [
      { path: 'ask', component: AskComponent },
      { path: ':id', component: ViewComponent },
      { path: '', redirectTo: '/questions/:id', pathMatch: 'full' }
 }
]}];
</code>```

Body:
I am using modular structure for my project.

Parent route is

 { path: 'questions', loadChildren: '../questions/questions.module#QuestionsModule'}

and in child I have :

const routes: Routes = [
{
path: '',
component: QuestionComponent,
children: [
  {
     path: ':id',
     component: ViewComponent,
  },

  {
    path: 'ask',
    component: AskComponent,
    pathMatch: 'full'
  },
  {
    path: '',
    redirectTo:'/:id',
    pathMatch:'full'
 },
]}];

for both http://localhost:4200/questions/123 and http://localhost:4200/questions/ask routes ,
ViewComponent is loading.

Here is my folder structure with routing: https://stackblitz.com/edit/angular-sjd9u9

Body:
Considering the routes in your Questions routing module:

const routes: Routes = [
{
path: '',
component: QuestionComponent,
children: [
  {
     path: ':id',
     component: ViewComponent,
  },

  {
    path: 'ask',
    component: AskComponent,
    pathMatch: 'full'
  },
  {
    path: '',
    redirectTo:'/:id',
    pathMatch:'full'
 },
]}];

:id is just a slot in the path to hold a route parameter.

When you navigate to http://localhost:4200/questions/ask, you end up with the following situation:

:id === 'ask'

Now, looking at the first path:

{
  path: ':id',
  component: ViewComponent,
}

The router finds a match using :id === 'ask' and therefore renders ViewComponent.

To fix this, you can change your routes to the following:

const routes: Routes = [
  {
    path: '',
    component: QuestionComponent,
    children: [
      { path: 'ask', component: AskComponent },
      { path: ':id', component: ViewComponent },
      { path: '', redirectTo: '/questions/:id', pathMatch: 'full' }
 }
]}];


问:
libGDX: Change the color of a PNG according to user's input
i hope you can help me.
I have a game where transparent textures are loaded and should be colored according to the user's choice (HEX code) at the beginning of the game.

My game has tiles where the gameFigures will be placed (centered).
Tiles are 50x50 are so is my png. it has a transparent background and the vector of my Figure has transparent stuff that should be colored.
It looks something like this:

I am using libGDX engine, and i am really frustrated because of this problem.
Any help is appreciated!

Thanks alot!

答:
To change colors programmatically in LibGDX you need to use an image (png or jpg) with white pixels you can achieve this effect splitting your image in 2 parts, one for the part that you don't want the color to be changed and one for the parts that you do.
Here's an example:

Code:

```<code>public class ExampleGame extends InputAdapter {

    SpriteBatch batch;
    Color crownColor;

    public ExampleGame() {
        batch = new SpriteBatch();
        crownColor = Color.WHITE;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        crownColor = Color.RED;
        return false;
    }

    public void render(TextureRegion player, TextureRegion crown) {
        batch.begin();
        batch.setColor(Color.WHITE); // Else player will be affected by crownColor too
        batch.draw(player, 0, 0);
        batch.setColor(crownColor);
        batch.draw(crown, 0, 0);
        batch.end();
    }
}
</code>```

Body:
To change colors programmatically in LibGDX you need to use an image (png or jpg) with white pixels you can achieve this effect splitting your image in 2 parts, one for the part that you don't want the color to be changed and one for the parts that you do.
Here's an example:

Code:

public class ExampleGame extends InputAdapter {

    SpriteBatch batch;
    Color crownColor;

    public ExampleGame() {
        batch = new SpriteBatch();
        crownColor = Color.WHITE;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        crownColor = Color.RED;
        return false;
    }

    public void render(TextureRegion player, TextureRegion crown) {
        batch.begin();
        batch.setColor(Color.WHITE); // Else player will be affected by crownColor too
        batch.draw(player, 0, 0);
        batch.setColor(crownColor);
        batch.draw(crown, 0, 0);
        batch.end();
    }
}


问:
how to update a table with specific value from other table with condition from third table
I am trying to update my company data
I have a three tables with large data

Table Name: Accounts

```<code>id    |    balance    |    currency_id
1          7000            7
2          100             7
3          6000            6
</code>```

Table Name: Members

```<code>id    |    email
1          ted@gmail.com
2          tom@gmail.com
</code>```

Table Name: Fund

```<code>email          |    balance
ted@gmail.com       7000
tom@gmail.com       8000
</code>```

how to update Accounts.balance with values from Fund.balance  where the currency_id =7 and  Members.email =  Fund.email

as explained above

how to update accounts.balance from 100 to balance  new value 8000 from Fund table for this email "tom@gmail.com"  as an example ?.

the issue I have is that there is no ID  in Fund table only email which is same as in members tables, so we have to check using the emails instead of id.

答:
You can use INNER JOIN to update value in Accounts table from Fund. Make sure related data is available in table Member and Fund.

Note: Try script with test data first.

```<code>UPDATE Accounts AS A
INNER JOIN Members AS M ON A.ID = M.ID
INNER JOIN Fund AS F ON M.email = F.email
SET A.balance = F.balance
WHERE  A.currency_id =7
</code>```

If there are possibilities of having no data in Fund table for Currency_id = 7 and if you want to keep the old value that case, you can use case as below-

```<code>SET A.balance = CASE WHEN F.balance IS NULL THEN A.balance ELSE F.balance END
</code>```

Body:
I am trying to update my company data
I have a three tables with large data

Table Name: Accounts

id    |    balance    |    currency_id
1          7000            7
2          100             7
3          6000            6

Table Name: Members

id    |    email
1          ted@gmail.com
2          tom@gmail.com

Table Name: Fund

email          |    balance
ted@gmail.com       7000
tom@gmail.com       8000

how to update Accounts.balance with values from Fund.balance  where the currency_id =7 and  Members.email =  Fund.email

as explained above

how to update accounts.balance from 100 to balance  new value 8000 from Fund table for this email "tom@gmail.com"  as an example ?.

the issue I have is that there is no ID  in Fund table only email which is same as in members tables, so we have to check using the emails instead of id.

Body:
You can use INNER JOIN to update value in Accounts table from Fund. Make sure related data is available in table Member and Fund.

Note: Try script with test data first.

UPDATE Accounts AS A
INNER JOIN Members AS M ON A.ID = M.ID
INNER JOIN Fund AS F ON M.email = F.email
SET A.balance = F.balance
WHERE  A.currency_id =7

If there are possibilities of having no data in Fund table for Currency_id = 7 and if you want to keep the old value that case, you can use case as below-

SET A.balance = CASE WHEN F.balance IS NULL THEN A.balance ELSE F.balance END


问:
The use of WorkManagerTestInitHelper prevents the WorkManager from completing the retry of the work
When I use:

```<code>    WorkManagerTestInitHelper.initializeTestWorkManager(context);
    WorkManager workManager =  WorkManager.getInstance();
</code>```

to get the WorkManager instance, the WorkManager fail to achieve retry.
I will present the simplest test:

```<code>public class WorkManagerTest {

   Context context;

@Before
public void setUp() throws Exception {

    context = InstrumentationRegistry.getTargetContext();

}

@Test
public   void testWorker1(){
    Constraints constraints = new Constraints.Builder()
                .build();
    OneTimeWorkRequest.Builder updateorderworkerBuilder =
            new OneTimeWorkRequest.Builder(TestWorker1.class)
                    .setConstraints(constraints)
                    //MIN_BACKOFF_MILLIS == 10000
                    .setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);

    OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
    WorkManager workManager =  WorkManager.getInstance();
    workManager.enqueue(workRequest);

    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

@Test
public   void testWorker2(){
    Constraints constraints = new Constraints.Builder()
                           .build();
    OneTimeWorkRequest.Builder updateorderworkerBuilder =
            new OneTimeWorkRequest.Builder(TestWorker2.class)
                    .setConstraints(constraints)
                    //MIN_BACKOFF_MILLIS == 10000
                    .setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);

    OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
    WorkManagerTestInitHelper.initializeTestWorkManager(context);
    WorkManager workManager =  WorkManager.getInstance();
    workManager.enqueue(workRequest);

    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

public static class TestWorker1 extends Worker {

    /**
     * Override this method to do your actual background processing.
     *
     * @return The result of the work, corresponding to a {@link Result} value.  If a
     * different value is returned, the result shall be defaulted to
     * {@link Result#FAILURE}.
     */
    @NonNull
    @Override
    public Result doWork() {
        Log.d("TEST_WORKER", "inside doWork()1");
        return Result.RETRY;
    }
}

public static class TestWorker2 extends Worker {

    /**
     * Override this method to do your actual background processing.
     *
     * @return The result of the work, corresponding to a {@link Result} value.  If a
     * different value is returned, the result shall be defaulted to
     * {@link Result#FAILURE}.
     */
    @NonNull
    @Override
    public Result doWork() {
        Log.d("TEST_WORKER", "inside doWork()2");
        return Result.RETRY;
    }
}
</code>```

}

In the Logcat I see:

```<code>07-22 23:34:25.184 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:30.178 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:40.238 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:00.300 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:15.130 5346-5372/com.billst.app.debug D/TEST_WORKER: inside doWork()2
</code>```

I take the same results even when I execute the 2 tests independently. We see that the use of  WorkManagerTestInitHelper prevents the WorkManager from completing the retry of the work.

Do I use WorkManagerTestInitHelper correctly?

答:
You cannot simulate retries in test mode. This is intentional because you should be testing your Worker and not testing WorkManager. You cannot use WorkManagerTestInitHelper for this. If you want to test that your Worker returns a Result.retry() then you could also use the new TestWorkerBuilder<> and the TestListenableWorkerBuilder APIs.

Here is an example.
https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/work/workmanager-testing/src/androidTest/java/androidx/work/testing/TestWorkerBuilderTest.kt

Body:
When I use:

    WorkManagerTestInitHelper.initializeTestWorkManager(context);
    WorkManager workManager =  WorkManager.getInstance();

to get the WorkManager instance, the WorkManager fail to achieve retry.
I will present the simplest test:

public class WorkManagerTest {

   Context context;

@Before
public void setUp() throws Exception {

    context = InstrumentationRegistry.getTargetContext();

}

@Test
public   void testWorker1(){
    Constraints constraints = new Constraints.Builder()
                .build();
    OneTimeWorkRequest.Builder updateorderworkerBuilder =
            new OneTimeWorkRequest.Builder(TestWorker1.class)
                    .setConstraints(constraints)
                    //MIN_BACKOFF_MILLIS == 10000
                    .setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);

    OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
    WorkManager workManager =  WorkManager.getInstance();
    workManager.enqueue(workRequest);

    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

@Test
public   void testWorker2(){
    Constraints constraints = new Constraints.Builder()
                           .build();
    OneTimeWorkRequest.Builder updateorderworkerBuilder =
            new OneTimeWorkRequest.Builder(TestWorker2.class)
                    .setConstraints(constraints)
                    //MIN_BACKOFF_MILLIS == 10000
                    .setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);

    OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
    WorkManagerTestInitHelper.initializeTestWorkManager(context);
    WorkManager workManager =  WorkManager.getInstance();
    workManager.enqueue(workRequest);

    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

public static class TestWorker1 extends Worker {

    /**
     * Override this method to do your actual background processing.
     *
     * @return The result of the work, corresponding to a {@link Result} value.  If a
     * different value is returned, the result shall be defaulted to
     * {@link Result#FAILURE}.
     */
    @NonNull
    @Override
    public Result doWork() {
        Log.d("TEST_WORKER", "inside doWork()1");
        return Result.RETRY;
    }
}

public static class TestWorker2 extends Worker {

    /**
     * Override this method to do your actual background processing.
     *
     * @return The result of the work, corresponding to a {@link Result} value.  If a
     * different value is returned, the result shall be defaulted to
     * {@link Result#FAILURE}.
     */
    @NonNull
    @Override
    public Result doWork() {
        Log.d("TEST_WORKER", "inside doWork()2");
        return Result.RETRY;
    }
}

}

In the Logcat I see:

07-22 23:34:25.184 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:30.178 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:40.238 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:00.300 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:15.130 5346-5372/com.billst.app.debug D/TEST_WORKER: inside doWork()2

I take the same results even when I execute the 2 tests independently. We see that the use of  WorkManagerTestInitHelper prevents the WorkManager from completing the retry of the work.

Do I use WorkManagerTestInitHelper correctly?


问:
Can I add and remove features manually from CountVectorizer?
I'm doing text classificaiton, and using naive bayes with CountVectorizer. I'm looking for away to add and remove features manually. maybe I can remove features through stop_words(is that the best way?) but I couldn't find a way to add features. if I used 'vocabulary' parameter, then there will be no feature extracted from the text other than the ones present in the vocabulary. and that's a problem</p>

答:
Yes, removing features using stop_words is the best possible way to keep the results consistent. You can also do a traversal and remove data manually but that will be same as removing them using stop_words. To add elements to the stop_word in sklearn, do this.</p>

```<code>from sklearn.feature_extraction import text
stop_words = text.ENGLISH_STOP_WORDS.union(additional_stop_words)
</code>```

Body:
Yes, removing features using stop_words is the best possible way to keep the results consistent. You can also do a traversal and remove data manually but that will be same as removing them using stop_words. To add elements to the stop_word in sklearn, do this.

from sklearn.feature_extraction import text
stop_words = text.ENGLISH_STOP_WORDS.union(additional_stop_words)


问:
Format Repeating Decimal as a Fraction
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

```<code>string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}
</code>```

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

答: Here's an recipe that converts a float to the closest fraction given a limit for the denominator: http://code.activestate.com/recipes/52317/</p>

OwnerDisplayName: Tim Lentine

Title: Format Repeating Decimal as a Fraction

Body:
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

OwnerDisplayName: Miles


问:
Why can't Webdriver find an element through xpath?
My code can't find a registration link with XPath. Same problem using CSSSelector.

```<code>driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.goldtoe.com/state/landing");
var LoginLink = driver.FindElement(By.XPath("//li[@class='hidden-xs myAccountMenu']//a[contains(text(),'Sign In/Register')] "));
LoginLink.Click();
</code>```

Message:

```<code>> OpenQA.Selenium.NoSuchElementException : no such element: Unable to
> locate element: {"method":"xpath","selector":"//li[@class='hidden-xs
> myAccountMenu']//a[contains(text(),'Sign In/Register')] "}   (Session
> info: chrome=74.0.3729.169)   (Driver info: chromedriver=74.0.3729.6
> (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows
> NT 10.0.17763 x86_64)
</code>```

答: I think you need an escape character for 'Sign In/Register' string, specifically for '/' special character. So, try 'Sign In\/Register' instead. Use '\' as the escape character.</p>

Body:
My code can't find a registration link with XPath. Same problem using CSSSelector.

driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.goldtoe.com/state/landing");
var LoginLink = driver.FindElement(By.XPath("//li[@class='hidden-xs myAccountMenu']//a[contains(text(),'Sign In/Register')] "));
LoginLink.Click();

Message:

> OpenQA.Selenium.NoSuchElementException : no such element: Unable to
> locate element: {"method":"xpath","selector":"//li[@class='hidden-xs
> myAccountMenu']//a[contains(text(),'Sign In/Register')] "}   (Session
> info: chrome=74.0.3729.169)   (Driver info: chromedriver=74.0.3729.6
> (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows
> NT 10.0.17763 x86_64)


问:
"Error in mutate_impl(.data, dots)" when using purrr::accumulate, "column can't be converted from numeric to list"
I want to add a column valueList to my data frame. Grouped by id, it should show the cumulative vector of value up to that point. See example below:

```<code>library(dplyr)
library(purrr)
df <- data.frame(id=c(1,2,3,4,5,6,7,8,1,2,3,3,2,3,5,6),
                 value=c(58,61,59,49,36,35,39,23,75,73,43,43,13,54,23,12))

df <- df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=purrr::accumulate(value,c)) %>%
  ungroup()
</code>```

However when I use this with certain other values, I get an error as per the question title. See below:

```<code>df <- data.frame(id=c(56612,32323,96953,93074,15964,38483,11020,91474,62432,70463,89016,29826,85076,46258,18339,89016),
                 value=c(58,61,59,49,36,35,30,23,75,73,43,0,46,45,43,42))

df <- df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=purrr::accumulate(value,c)) %>%
  ungroup()
</code>```

Error in mutate_impl(.data, dots) :
Column valueList can't be converted from numeric to list

Why is this happening?

答:
What akrun probably meant was that you should wrap accumulate to make sure that it always returns a list,
because if you execute it on a single element,
it simply returns that element:

```<code>accumulate(c(1), c)
# [1] 1
accumulate(c(1, 2), c)
# [[1]]
# [1] 1

# [[2]]
# [1] 1 2
</code>```

You can do that with:

```<code>df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=as.list(purrr::accumulate(value, c))) %>%
  ungroup()
</code>```

I assume that this happens because dplyr probably expects the result's structure to be compatible across all groups,
check for example:

```<code>bind_rows(tibble(a=list(1)),
          tibble(a=2))
# Error: Column `a` can't be converted from list to numeric
bind_rows(tibble(a=2),
          tibble(a=list(1)))
# Error: Column `a` can't be converted from numeric to list
</code>```

But I'm not sure why it correctly handled your first example.

Body:
I want to add a column valueList to my data frame. Grouped by id, it should show the cumulative vector of value up to that point. See example below:

library(dplyr)
library(purrr)
df <- data.frame(id=c(1,2,3,4,5,6,7,8,1,2,3,3,2,3,5,6),
                 value=c(58,61,59,49,36,35,39,23,75,73,43,43,13,54,23,12))

df <- df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=purrr::accumulate(value,c)) %>%
  ungroup()

However when I use this with certain other values, I get an error as per the question title. See below:

df <- data.frame(id=c(56612,32323,96953,93074,15964,38483,11020,91474,62432,70463,89016,29826,85076,46258,18339,89016),
                 value=c(58,61,59,49,36,35,30,23,75,73,43,0,46,45,43,42))

df <- df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=purrr::accumulate(value,c)) %>%
  ungroup()

Error in mutate_impl(.data, dots) :
Column valueList can't be converted from numeric to list

Why is this happening?

Body:
What akrun probably meant was that you should wrap accumulate to make sure that it always returns a list,
because if you execute it on a single element,
it simply returns that element:

accumulate(c(1), c)
# [1] 1
accumulate(c(1, 2), c)
# [[1]]
# [1] 1

# [[2]]
# [1] 1 2

You can do that with:

df %>%
  dplyr::group_by(id) %>%
  dplyr::mutate(valueList=as.list(purrr::accumulate(value, c))) %>%
  ungroup()

I assume that this happens because dplyr probably expects the result's structure to be compatible across all groups,
check for example:

bind_rows(tibble(a=list(1)),
          tibble(a=2))
# Error: Column `a` can't be converted from list to numeric
bind_rows(tibble(a=2),
          tibble(a=list(1)))
# Error: Column `a` can't be converted from numeric to list

But I'm not sure why it correctly handled your first example.


问:
How is an XML document stored in SQL (SQL:2003)?

SQL:2003

When storing XML data (e.g. using the XML data type) how does SQL store this data?

Are separate columns used? Is it stored as a string-type blob? Is it stored as files? How does work with parsing? How is an update performed on XML in SQL?

答:
The XML datatype is not substantially different than any other datatype in SQL. It can be used in any place you would ordinarily use any SQL datatype. There are few limitations:

XML types cannot convert to text or ntext data types.

No data type other than one of the string types can be cast to XML.

XML columns cannot be used in GROUP BY statements.

Distributed partitioned views or materialized views cannot contain XML data types.

Use of the sql_variant instances cannot include XML as a subtype.

XML columns cannot be part of a primary or foreign key.

XML columns cannot be designated as unique.

Collation (COLLATE clause) cannot be used on XML columns.

XML columns cannot participate in rules.

useful resource xml sql


问:
does (SQL) JOINING on TABLES ALWAYS create Cartesian products of those tables?
does JOINING on TABLES ALWAYS create Cartesian products of those tables ?

if a problem can be solved by sub-query and Joining which should i prefer ?

which one is fast and memory saving ?

All the questions are tightly coupled, so please dont tell to open another thread :(

MySQL 5

答:
Yes, joining always creates a Cartesian product. That's why you usually add a condition to be met:
JOIN a, b ON key_a = key_b. If the key_b is a UNIQUE KEY in table b, you will have at most one row from b for each row of a.

In most cases, joins are faster, but there are exceptions (WHERE x IN ANY (subquery))

See 2.