问:
LOOPBACK Modify another model inside a hook
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3</p>

```<code> module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};
</code>```

答:
If you have an Event model with a function to insert newData. Just reference the model. For ex:

```<code>var eventModel = require('pathtoEventModel');

module.exports = function(Transaction) {
Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
       eventModel.saveNewData(ctxBeingNewData,function(response,next){
       //manipulate as per your wish.
       })
    }
</code>```

});
};

Body:
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3

 module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};

Body:
If you have an Event model with a function to insert newData. Just reference the model. For ex:

var eventModel = require('pathtoEventModel');

module.exports = function(Transaction) {
Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
       eventModel.saveNewData(ctxBeingNewData,function(response,next){
       //manipulate as per your wish.
       })
    }

});
};


来源: stackexchange

问:
Replace spaces with an underscore in PHP while uploading file
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

```<code><?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?

答:
It is because you replaced it after you upload, you should replace before you upload.</p>

```<code><?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    $target_file = str_replace(' ', '_', $target_file);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?

Body:
It is because you replaced it after you upload, you should replace before you upload.

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    $target_file = str_replace(' ', '_', $target_file);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}


问:
Immutable event handling
I have implemented an immutable system in Java. Pretty much every class is immutable and it's worked out much better than I expected.

My problem is trying to send events. Normally you'd have an event source and an event listener. The source simply holds a reference to the listener and sends the event when it happens.

But with immutables the event listener reference changes when you modify a field and create a new object. So the event source is sending to some old reference that's been garbage collected.

So all my GUI classes are mutable for that reason, because they naturally use a lot of events. But i'd like to find an elegant way to handle events so I can make those immutable as well.

Edit: Example code as requested:

```<code>public final class ImmutableButton {
    public final String text;

    public ImmutableButton(String text) {
        this.text = text;
    }

    protected void onClick() {
        // notify listeners somehow, hoping they haven't changed
    }
}

public final class ImmutableWindow {
    public final ImmutableButton button;

    public ImmutableWindow(ImmutableButton button) {
        this.button = button;
    }

    protected void listenForButtonClick() {
        // somehow register with button and receive events, despite this object
        // being entirely recreated whenever a field changes
    }
}
</code>```

答:
Yes, the conflict in your design is you cant register listeners against objects which get replaced when you rebuild the immutable data model.  My solution below is to remove the listeners from the model all together.  Even thought most of your objects are immutable, you'll need at least 1 mutable variable at the base to hold the created / recreated Window.  Here I'v used inner classes as listeners which you register once. They then dispatch doStuff() calls against the objects in the model, but they get looked up against the single base mutable window reference.  eg. window.getButton1().doStuff();

I don't claim this is a great solution but it's the simplest and cleanest I could come up with for your requirements.  The listeners don't become invalid and everything from Window down can be immutable.

```<code>public final MutableBase {
    private ImmutableWindow window;  // single mutable variable

    public MutableBase() {
        Magic.registerClickListener(new WindowClickEvent());
        Magic.registerClickListener(new Button1ClickEvent());
        rebuildWindow();
    }

    public void rebuildWindow() {
        // rebuild here when needed - change single mutable variable
        this.window = new ImmutableWindow(new ImmutableButton("text"));
    }

    class WindowClickEvent implements ClickListener {
        public void onClick() {
            this.window.doStuff();
        }
    }

    class Button1ClickEvent implements ClickListener {
        public void onClick() {
            this.window.getButton1().doStuff();
        }
    }
}
</code>```

Title: Immutable event handling

Body:
I have implemented an immutable system in Java. Pretty much every class is immutable and it's worked out much better than I expected.

My problem is trying to send events. Normally you'd have an event source and an event listener. The source simply holds a reference to the listener and sends the event when it happens.

But with immutables the event listener reference changes when you modify a field and create a new object. So the event source is sending to some old reference that's been garbage collected.

So all my GUI classes are mutable for that reason, because they naturally use a lot of events. But i'd like to find an elegant way to handle events so I can make those immutable as well.

Edit: Example code as requested:

public final class ImmutableButton {
    public final String text;

    public ImmutableButton(String text) {
        this.text = text;
    }

    protected void onClick() {
        // notify listeners somehow, hoping they haven't changed
    }
}

public final class ImmutableWindow {
    public final ImmutableButton button;

    public ImmutableWindow(ImmutableButton button) {
        this.button = button;
    }

    protected void listenForButtonClick() {
        // somehow register with button and receive events, despite this object
        // being entirely recreated whenever a field changes
    }
}

Body:
Yes, the conflict in your design is you cant register listeners against objects which get replaced when you rebuild the immutable data model.  My solution below is to remove the listeners from the model all together.  Even thought most of your objects are immutable, you'll need at least 1 mutable variable at the base to hold the created / recreated Window.  Here I'v used inner classes as listeners which you register once. They then dispatch doStuff() calls against the objects in the model, but they get looked up against the single base mutable window reference.  eg. window.getButton1().doStuff();

I don't claim this is a great solution but it's the simplest and cleanest I could come up with for your requirements.  The listeners don't become invalid and everything from Window down can be immutable.

public final MutableBase {
    private ImmutableWindow window;  // single mutable variable

    public MutableBase() {
        Magic.registerClickListener(new WindowClickEvent());
        Magic.registerClickListener(new Button1ClickEvent());
        rebuildWindow();
    }

    public void rebuildWindow() {
        // rebuild here when needed - change single mutable variable
        this.window = new ImmutableWindow(new ImmutableButton("text"));
    }

    class WindowClickEvent implements ClickListener {
        public void onClick() {
            this.window.doStuff();
        }
    }

    class Button1ClickEvent implements ClickListener {
        public void onClick() {
            this.window.getButton1().doStuff();
        }
    }
}


问:
Best way to compress animated GIFs using ImageMagick, without using Gifsicle
So my web host won't install gifsicle on their shared servers, so I'm stuck with ImageMagick. I want to compress the images like it is here: https://pornel.net/lossygif how can I do that without using gifsicle; using only ImageMagick?

Right now my exec() command goes like:

```<code>exec("convert $animation -coalesce -gravity SouthWest  -geometry +0+0 null: $watermark -layers composite -layers optimize $animation");
</code>```

and the watermarked GIF barely compresses, and sometimes it even gets larger.
How could I solve this issue?

答:
I had success with ImageMagick's Mogrify:
https://www.imagemagick.org/script/mogrify.php

After you generate a large gif, you can make it smaller.

My command looked like:

```<code>mogrify -layers 'optimize' -fuzz 7% mygif.gif
</code>```

The -layers option optimized any layers in your gif

The biggest space savings comes from the -fuzz option, which specifies that colors within a certain tolerance can be considered the same color.

My several second gifs went from 3 MB to a few hundred kb.

Body:
So my web host won't install gifsicle on their shared servers, so I'm stuck with ImageMagick. I want to compress the images like it is here: https://pornel.net/lossygif how can I do that without using gifsicle; using only ImageMagick?

Right now my exec() command goes like:

exec("convert $animation -coalesce -gravity SouthWest  -geometry +0+0 null: $watermark -layers composite -layers optimize $animation");

and the watermarked GIF barely compresses, and sometimes it even gets larger.
How could I solve this issue?

Body:
I had success with ImageMagick's Mogrify:
https://www.imagemagick.org/script/mogrify.php

After you generate a large gif, you can make it smaller.

My command looked like:

mogrify -layers 'optimize' -fuzz 7% mygif.gif

The -layers option optimized any layers in your gif

The biggest space savings comes from the -fuzz option, which specifies that colors within a certain tolerance can be considered the same color.

My several second gifs went from 3 MB to a few hundred kb.


问:
JAVA Match a Username with a Password for Login Program
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

```<code>import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}
</code>```

答:
I assume that you use only single login but stored on 2 files Password.txt and Username.txt.

Below is my 10 min codes, so you might need to modified if got typo or error.

```<code>import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class PassCodeA {

    public static void main(String[] args)
    {
        Scanner usernameFile = null;
        try {
            usernameFile = new Scanner(new FileReader("Username.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Username File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
            return;
        }

        Scanner passwordFile = null;
        try {
            passwordFile = new Scanner(new FileReader("Password.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Password File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
            return;
        }

        String usernameInput = JOptionPane.showInputDialog(null,"Please Enter Username", "Username", JOptionPane.OK_CANCEL_OPTION);
        String passwordInput = JOptionPane.showInputDialog(null,"Please Enter Password", "Username", JOptionPane.OK_CANCEL_OPTION);
        System.out.println(usernameInput);

        boolean usernameFound = false;
        while(usernameFile.hasNextLine()){
            final String lineFromFile = usernameFile.nextLine();
            if(lineFromFile.equals(usernameInput)){
                usernameFound = true;
                break;
            }
        }
        if (usernameFound == false) {
            JOptionPane.showMessageDialog(null, "Username not found", "Username Not Found", JOptionPane.CLOSED_OPTION);
            return;
        }

        boolean passwordFound = false;
        while(passwordFile.hasNextLine()){
            final String lineFromFile = passwordFile.nextLine();
            if(lineFromFile.equals(passwordInput)){
                passwordFound = true;
                break;
            }
        }

        if (passwordFound == false) {
            JOptionPane.showMessageDialog(null, "Password not found", "Password Not Found", JOptionPane.CLOSED_OPTION);
            return;
        }

        JOptionPane.showMessageDialog(null, "Thank you for login", "Success", JOptionPane.CLOSED_OPTION);

    }

}
</code>```

If you had multiple login credential in that both files. You should use LineNumberReader instead of scanner. So that you can match with line number on both files.

Body:
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}

Body:
I assume that you use only single login but stored on 2 files Password.txt and Username.txt.

Below is my 10 min codes, so you might need to modified if got typo or error.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class PassCodeA {

    public static void main(String[] args)
    {
        Scanner usernameFile = null;
        try {
            usernameFile = new Scanner(new FileReader("Username.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Username File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
            return;
        }

        Scanner passwordFile = null;
        try {
            passwordFile = new Scanner(new FileReader("Password.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Password File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
            return;
        }

        String usernameInput = JOptionPane.showInputDialog(null,"Please Enter Username", "Username", JOptionPane.OK_CANCEL_OPTION);
        String passwordInput = JOptionPane.showInputDialog(null,"Please Enter Password", "Username", JOptionPane.OK_CANCEL_OPTION);
        System.out.println(usernameInput);

        boolean usernameFound = false;
        while(usernameFile.hasNextLine()){
            final String lineFromFile = usernameFile.nextLine();
            if(lineFromFile.equals(usernameInput)){
                usernameFound = true;
                break;
            }
        }
        if (usernameFound == false) {
            JOptionPane.showMessageDialog(null, "Username not found", "Username Not Found", JOptionPane.CLOSED_OPTION);
            return;
        }

        boolean passwordFound = false;
        while(passwordFile.hasNextLine()){
            final String lineFromFile = passwordFile.nextLine();
            if(lineFromFile.equals(passwordInput)){
                passwordFound = true;
                break;
            }
        }

        if (passwordFound == false) {
            JOptionPane.showMessageDialog(null, "Password not found", "Password Not Found", JOptionPane.CLOSED_OPTION);
            return;
        }

        JOptionPane.showMessageDialog(null, "Thank you for login", "Success", JOptionPane.CLOSED_OPTION);

    }

}

If you had multiple login credential in that both files. You should use LineNumberReader instead of scanner. So that you can match with line number on both files.


问:
Count vowels in a string with ruby
My objective is to return the number of vowels in a given string. I've tried this code:

```<code>def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end
</code>```

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

答:
take_while is the wrong method here. It starts at the beginning, and "takes" elements as long as the block returns a truthy value. It stops the first time you encounter a letter that isn't a vowel.

You want select which selects all the elements for which the block returns a truthy value.

Title: Count vowels in a string with ruby

Body:
My objective is to return the number of vowels in a given string. I've tried this code:

def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?


问:
Dynamic query based on value of query params in java
I want to write a dynamic query based on value of query params. I have string query like this

```<code>String strSQL = "select tb_r_orderdata.customerid,\n" +
                            "REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','') as paydate,\n" +
                            "tb_r_orderdata.amount,\n" +
                            "tb_r_orderdata.acquirementid,\n" +
                            "tb_r_orderdata.tracking_ref,\n" +
                            "tb_m_biller_product.billerdesc, \n" +
                            "tb_m_biller_product.productdesc, \n" +
                            "tb_r_orderdata.hpno, \n" +
                            "tb_r_orderdata.email, \n" +
                            "tb_r_orderdata.rc, \n" +
                            "tb_r_orderdata.rcdesc, \n" +
                            "tb_r_orderdata.additionaldata_pay \n" +
                            "from tb_r_orderdata JOIN tb_m_biller_product ON tb_r_orderdata.productid=tb_m_biller_product.productid AND tb_r_orderdata.billerid=tb_m_biller_product.billerid \n" +
                            "where status='SUCCESS';";
</code>```

The result like this, if there is value or not in query params, the string query will added based on the condition.

Here is my condition

```<code>String newstrSQL = strSQL;
PreparedStatement pst=null;

if (period != null) {
   newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')>=?";
}

if (tanggal != null) {
    newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')<=?";
}

if (billerid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.billerid  = ?";
}

if (productid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.productid  = ?";
}

if (custom != null) {
    newstrSQL = strSQL + "and" + searchby + " = ?";
}

pst = con.prepareStatement(newstrSQL);
pst.setString(1, period);
pst.setString(2, tanggal);
pst.setString(3, billerid);
pst.setString(4, productid);
pst.setString(5, custom);

rs = pst.executeQuery();
</code>```

I have test it, but the result always zero and there is not syntax error. Thank you, sorry for bad English

答:
You have given semicolon in string where status='SUCCESS';, It means your query ends here and the remaining you appending after it will not execute as you are trying here strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')>=?";.

Don't end strSql with semicolon and try.

Body:
I want to write a dynamic query based on value of query params. I have string query like this

String strSQL = "select tb_r_orderdata.customerid,\n" +
                            "REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','') as paydate,\n" +
                            "tb_r_orderdata.amount,\n" +
                            "tb_r_orderdata.acquirementid,\n" +
                            "tb_r_orderdata.tracking_ref,\n" +
                            "tb_m_biller_product.billerdesc, \n" +
                            "tb_m_biller_product.productdesc, \n" +
                            "tb_r_orderdata.hpno, \n" +
                            "tb_r_orderdata.email, \n" +
                            "tb_r_orderdata.rc, \n" +
                            "tb_r_orderdata.rcdesc, \n" +
                            "tb_r_orderdata.additionaldata_pay \n" +
                            "from tb_r_orderdata JOIN tb_m_biller_product ON tb_r_orderdata.productid=tb_m_biller_product.productid AND tb_r_orderdata.billerid=tb_m_biller_product.billerid \n" +
                            "where status='SUCCESS';";

The result like this, if there is value or not in query params, the string query will added based on the condition.

Here is my condition

String newstrSQL = strSQL;
PreparedStatement pst=null;

if (period != null) {
   newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')>=?";
}

if (tanggal != null) {
    newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')<=?";
}

if (billerid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.billerid  = ?";
}

if (productid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.productid  = ?";
}

if (custom != null) {
    newstrSQL = strSQL + "and" + searchby + " = ?";
}

pst = con.prepareStatement(newstrSQL);
pst.setString(1, period);
pst.setString(2, tanggal);
pst.setString(3, billerid);
pst.setString(4, productid);
pst.setString(5, custom);

rs = pst.executeQuery();

I have test it, but the result always zero and there is not syntax error. Thank you, sorry for bad English


问:
Using Jquery and Bootstrap with Es6 Import for React App
Hello I am trying to include jquery and bootstrap into a Reactjs project, but I am using es6 imports to do so. I've included the imports as shown below in my index.js file. But upon page load it gives error saying that Bootstrap's Javascript requires jquery. I've already npm installed all the required packages. How can I get jquery into my bundled and minified final script file?</p>

```<code>import $ from 'jquery';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../node_modules/bootstrap/dist/js/bootstrap.min.js';
</code>```

答:
After import all style css file add the below code in your index.js file</p>

```<code>window.jQuery = window.$ = require('jquery/dist/jquery.min.js');
require('bootstrap/dist/js/bootstrap.min.js');
</code>```

Body:
Hello I am trying to include jquery and bootstrap into a Reactjs project, but I am using es6 imports to do so. I've included the imports as shown below in my index.js file. But upon page load it gives error saying that Bootstrap's Javascript requires jquery. I've already npm installed all the required packages. How can I get jquery into my bundled and minified final script file?

import $ from 'jquery';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../node_modules/bootstrap/dist/js/bootstrap.min.js';

Body:
After import all style css file add the below code in your index.js file

window.jQuery = window.$ = require('jquery/dist/jquery.min.js');
require('bootstrap/dist/js/bootstrap.min.js');


问:
Showing full response on query on sqlcl query
I'm trying to use sqlcl on a remote server to retrieve the table definition of the tables in given oracle database.

Since I have to use the cli there, I can't simply use SQLDeveloper and get the table definitions out of there (can't connect to DB from outside of the server).

The idea is to use

```<code>select dbms_metadata.get_ddl('TABLE', table_name)
from user_tables where table_name = 'RESULTS';
</code>```

in order to get the table DDL for the table I need.

However, when I run this query in the sqlcl tool, the output looks like this:

```<code> CREATE TABLE "AP29_QUDB"."RESULTS"
 (  "LOCATION_RESULT_UID" RAW(16) NOT NU
</code>```

That's it, no more information.

Does someone know how I get the full result of that query to be displayed?

(Or alternatively simply pipe it to a file for me to copy it out of there)

Thank you very much

- Tim

答:
Looks like sqlcl copied the LONG setting from SQL*Plus.  By default it only shows the first 80 characters of a CLOB.  That size can be changed with set long [some large number]'.

```<code>SQL> select dbms_metadata.get_ddl('TABLE', 'DUAL', 'SYS') from dual;

DBMS_METADATA.GET_DDL('TABLE','DUAL','SYS')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."DUAL" SHARING=METADATA
   (    "DUMMY" VARCHAR2(1)
   ) PCT

SQL> set long 10000000
SQL> /

DBMS_METADATA.GET_DDL('TABLE','DUAL','SYS')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."DUAL" SHARING=METADATA
   (    "DUMMY" VARCHAR2(1)
   ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 16384 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "SYSTEM"

SQL>
</code>```

Body:
I'm trying to use sqlcl on a remote server to retrieve the table definition of the tables in given oracle database.

Since I have to use the cli there, I can't simply use SQLDeveloper and get the table definitions out of there (can't connect to DB from outside of the server).

The idea is to use

select dbms_metadata.get_ddl('TABLE', table_name)
from user_tables where table_name = 'RESULTS';

in order to get the table DDL for the table I need.

However, when I run this query in the sqlcl tool, the output looks like this:

 CREATE TABLE "AP29_QUDB"."RESULTS"
 (  "LOCATION_RESULT_UID" RAW(16) NOT NU

That's it, no more information.

Does someone know how I get the full result of that query to be displayed?

(Or alternatively simply pipe it to a file for me to copy it out of there)

Thank you very much

- Tim

Body:
Looks like sqlcl copied the LONG setting from SQL*Plus.  By default it only shows the first 80 characters of a CLOB.  That size can be changed with set long [some large number]'.

SQL> select dbms_metadata.get_ddl('TABLE', 'DUAL', 'SYS') from dual;

DBMS_METADATA.GET_DDL('TABLE','DUAL','SYS')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."DUAL" SHARING=METADATA
   (    "DUMMY" VARCHAR2(1)
   ) PCT

SQL> set long 10000000
SQL> /

DBMS_METADATA.GET_DDL('TABLE','DUAL','SYS')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."DUAL" SHARING=METADATA
   (    "DUMMY" VARCHAR2(1)
   ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 16384 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "SYSTEM"

SQL>


问:
Criteria builder for Two tables
I am a beginner with JPA.
My query is,
Select a,b,c FROM Table1 one, Table2 two where one.a=two.a;
How can i perform this with Criteria builder?

答:
Assume there is a department table which contains some number of people .Below is a join example of CriteriaBuilder.</p>

```<code> CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Person> query = cb.createQuery(Person.class);
    Root<Department> department= query.from(Department.class);
    Join<Department, Person> people= departent.join("people");
    query.select(people).where(cb.equal(person.get("name"), "Michael"));
</code>```

Title: Criteria builder for Two tables

Body:
Assume there is a department table which contains some number of people .Below is a join example of CriteriaBuilder.

 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Person> query = cb.createQuery(Person.class);
    Root<Department> department= query.from(Department.class);
    Join<Department, Person> people= departent.join("people");
    query.select(people).where(cb.equal(person.get("name"), "Michael"));


问:
How to find where a specific sequence of numbers in a list starts?
I couldn't find an answer for this, I'm a novice programmer so sorry about this dumb question!

Say in python I want to find where the first time the sequence [69, 69] appears in the list [34,34,34,50,39,69,69,54]. Is there a list notation for this? I feel like there is, but I haven't been able to find it. I'm not looking to make a function, I want to learn list/for methods.

so if a = [34,34,34,50,39,69,69,54] how would I find where [69,69] starts? (as a general statement) If I assume that [69,69] is in fact in a?

答:
```<code>[x for x in enumerate(a) if x[1] == 69]
</code>```

Body: [x for x in enumerate(a) if x[1] == 69]


问:
Generate unique url slug with PHP
I'm developing a small CMS system. Currently brain dead while trying to generate a unique url. I generate the url from the title of the page. Got a nice script to make this happen but I can't resolve the issue of duplicates.

Similar question here but getting the exact output.

I manage to make the following;

```<code>this-is-the-slug
this-is-the-slug-2
</code>```

But if I create the same post the third time, it would just duplicate: this-is-the-slug-2

```<code>$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}
</code>```

I can't get around it, would be thankful for assistance.

```<code>if(isset($_POST['save'])) {
    $title = mysqli_real_escape_string($db, $_POST['title']);
    $url = toAscii($title);
    // check url
    $content = $_POST['content'];
    $author = $_SESSION['thelab_username'];
    $type = $_POST['type'];
    $showtitle = $_POST['showtitle'];
    $saveas = $_POST['status'];

    $insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
    VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");

    if($insert === TRUE) {
        echo '<div id="success">Page added. <button id="close">Close</button></div>';
    }

    else {
        echo '<div id="error">Failed. Try again. <button id="failed">Close</button></div>';
        printf("Errormessage: %s\n", $db->error);
    }
}

function toAscii($str, $replace=array(), $delimiter='-') {
 if( !empty($replace) ) {
  $str = str_replace((array)$replace, ' ', $str);
 }

 $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
 $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
 $clean = strtolower(trim($clean, '-'));
 $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

 return $clean;
}
</code>```

答:
I had problems with permalinks too. Especially when I wanted to remove russian, chinese and any other characters than English from the url. Try the function bellow. I used PDO but it is not a big difference.

```<code>        function FilterPermalink($link){
            $db = new Connect;
            $link = strtolower(trim($link));
            $link = preg_replace('/[^a-z0-9-]/', '-', $link);
            $link = preg_replace('/-+/', "-", $link);
            $link = rtrim($link, '-');
            $link = preg_replace('/\s+/', '-', $link);
            if(strlen($link) > 30)
                $link = substr($link, 0, 30);
            $existing_lnk = $db->prepare("SELECT id FROM posts WHERE permalink = :permalink");
            $existing_lnk->execute(array('permalink' => $link));
            $num = $existing_lnk->fetchAll(PDO::FETCH_COLUMN);
            $first_total = count($num);
            for($i=0;$first_total != 0;$i++){
                if($i == 0){
                    $new_number = $first_total + 1;
                    $newlink = $link."-".$new_number;
                }
                $check_lnk = $db->prepare("SELECT id FROM posts WHERE permalink = :permalink");
                $check_lnk->execute(array('permalink' => $newlink));
                $other = $check_lnk->fetchAll(PDO::FETCH_COLUMN);
                $other_total = count($other);
                if($other_total != 0){
                    $first_total = $first_total + $other_total;
                    $new_number = $first_total;
                    $newlink = $link."-".$new_number;
                }elseif($other_total == 0){
                    $first_total = 0;
                }
            }
            if($i > 0)
                return $newlink;
            else
                return $link;
        }
</code>```

It works well for me.

Title: Generate unique url slug with PHP

Body:
I'm developing a small CMS system. Currently brain dead while trying to generate a unique url. I generate the url from the title of the page. Got a nice script to make this happen but I can't resolve the issue of duplicates.

Similar question here but getting the exact output.

I manage to make the following;

this-is-the-slug
this-is-the-slug-2

But if I create the same post the third time, it would just duplicate: this-is-the-slug-2

$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}

I can't get around it, would be thankful for assistance.

if(isset($_POST['save'])) {
    $title = mysqli_real_escape_string($db, $_POST['title']);
    $url = toAscii($title);
    // check url
    $content = $_POST['content'];
    $author = $_SESSION['thelab_username'];
    $type = $_POST['type'];
    $showtitle = $_POST['showtitle'];
    $saveas = $_POST['status'];

    $insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
    VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");

    if($insert === TRUE) {
        echo '
Page added. <button id="close">Close</button>
';
    }

    else {
        echo '
Failed. Try again. <button id="failed">Close</button>
';
        printf("Errormessage: %s\n", $db->error);
    }
}

function toAscii($str, $replace=array(), $delimiter='-') {
 if( !empty($replace) ) {
  $str = str_replace((array)$replace, ' ', $str);
 }

 $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
 $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
 $clean = strtolower(trim($clean, '-'));
 $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

 return $clean;
}

Body:
I had problems with permalinks too. Especially when I wanted to remove russian, chinese and any other characters than English from the url. Try the function bellow. I used PDO but it is not a big difference.

        function FilterPermalink($link){
            $db = new Connect;
            $link = strtolower(trim($link));
            $link = preg_replace('/[^a-z0-9-]/', '-', $link);
            $link = preg_replace('/-+/', "-", $link);
            $link = rtrim($link, '-');
            $link = preg_replace('/\s+/', '-', $link);
            if(strlen($link) > 30)
                $link = substr($link, 0, 30);
            $existing_lnk = $db->prepare("SELECT id FROM posts WHERE permalink = :permalink");
            $existing_lnk->execute(array('permalink' => $link));
            $num = $existing_lnk->fetchAll(PDO::FETCH_COLUMN);
            $first_total = count($num);
            for($i=0;$first_total != 0;$i++){
                if($i == 0){
                    $new_number = $first_total + 1;
                    $newlink = $link."-".$new_number;
                }
                $check_lnk = $db->prepare("SELECT id FROM posts WHERE permalink = :permalink");
                $check_lnk->execute(array('permalink' => $newlink));
                $other = $check_lnk->fetchAll(PDO::FETCH_COLUMN);
                $other_total = count($other);
                if($other_total != 0){
                    $first_total = $first_total + $other_total;
                    $new_number = $first_total;
                    $newlink = $link."-".$new_number;
                }elseif($other_total == 0){
                    $first_total = 0;
                }
            }
            if($i > 0)
                return $newlink;
            else
                return $link;
        }

It works well for me.


问:
Making 2 sequential requests with Axios - second request depends on the response of 1st
The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

```<code>return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})
</code>```

Thanks in advance.

San

答:
you can use async and await here, something like this:       </p>

```<code> async function getData() {
      const firstRequest = await axios.get(`${<URL1>}`);
      data1 = firstRequest.data[0];
      if (!data1){
          const secondRequest = await axios.get(`${<URL2>}`);
          data1 = secondRequest.data;
      }
      return data1;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})

Thanks in advance.

San

Body:
you can use async and await here, something like this:

 async function getData() {
      const firstRequest = await axios.get(`${<URL1>}`);
      data1 = firstRequest.data[0];
      if (!data1){
          const secondRequest = await axios.get(`${<URL2>}`);
          data1 = secondRequest.data;
      }
      return data1;
  }


问:
How can i write SQL search name?
how can i write SQL to search name in database? Example name : Brul Nol
Note: I can search Brul Nol or Nol Brul and then i get the same result </p>

答:
You can use fulltext search technique (If you use Mysql).

```<code>SELECT * FROM table_name WHERE MATCH(first_name, last_name) AGAINST('Brul Nol' IN BOOLEAN MODE);
</code>```

To perform fulltext search you need to add FTS index firstly,

```<code>ALTER TABLE table_name ADD FULLTEXT index_name(first_name, last_name);
</code>```

Title: How can i write SQL search name?

Body:
You can use fulltext search technique (If you use Mysql).

SELECT * FROM table_name WHERE MATCH(first_name, last_name) AGAINST('Brul Nol' IN BOOLEAN MODE);

To perform fulltext search you need to add FTS index firstly,

ALTER TABLE table_name ADD FULLTEXT index_name(first_name, last_name);


问:
How to pass Dictionary<string, string> object in some method
Can somebody give an example of how i pass Dictionary object in some method.???</p>

答:
If from the syntax you are referring to .NET then it would be as simple as passing any other parameter into a method

```<code>AMethod(Dictionary<string,string> dictionary)
{
//  Stuff
}
</code>```

If you are doing a new inside the AMethod to create a new dictionary then don't forget to add a "ref".

ContentLicense: CC BY-SA 2.5

Body:
If from the syntax you are referring to .NET then it would be as simple as passing any other parameter into a method

AMethod(Dictionary<string,string> dictionary)
{
//  Stuff
}

If you are doing a new inside the AMethod to create a new dictionary then don't forget to add a "ref".


问:
In Messenger bot webview , How to know that user has completed registration form
In messenger bot i was showing a webview form here how can we know that user completed form and trigger a message a particular user about successfully form submitted</p>

答:
When the submit button for the form is clicked you can call requestCloseBrowser() to close the webview, and send an event to your webhook to notify it to send the follow up message in the conversation.

https://developers.facebook.com/docs/messenger-platform/webview#close


问:
Oracle - Identifying Dominant Records
I have a table that contains two STRING values (all single words) along with a corresponding COUNT for each occurrence of the STRING, e.g;

```<code>ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     2         APPLES    10
2   APPLES      10        ORANGES   2
3   ORANGES     2         BANANAS   1
4   BANANAS     1         APPLES    10
5   BANANAS     1         ORANGES   2
</code>```

N.B. STR_1 is considered the ‘master’ value. Also, the COUNT for each individual STRING value will be consistent between STR_1 And STR_2 and between rows (e.g. ORANGES will always have a COUNT of 2)

What I’m trying to achieve is to remove records whereby an ‘enantiomer’ exists, for example; in the above data, ID 2 would be considered an ‘enantiomer’ of ID 1 (ID 1.STR_1 = ID.2 STR_2 and ID 1.STR_2 = ID.2 STR_1), however, ID 2 would be considered the dominant record with ID 1 being discarded (because the COUNT for APPLES is greater than the COUNT for ORANGES) – therefore the desired output would be;

```<code>ID  STR_1       COUNT_1   STR_2     COUNT_2
2   APPLES      10        ORANGES   2
3   ORANGES     2         BANANAS   1
4   BANANAS     1         APPLES    10
</code>```

IF a scenario exists whereby the COUNT values between different STRINGS match, the longest STRING would be considered the dominant record and retained e.g.;

```<code>ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     10        APPLES    10
2   APPLES      10        ORANGES   10
3   ORANGES     10        BANANAS   1
4   BANANAS     1         APPLES    10
5   BANANAS     1         ORANGES   10
</code>```

With the desired output being;

```<code>ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     10        APPLES    10
3   ORANGES     10        BANANAS   1
4   BANANAS     1         APPLES    10
</code>```

Test Data;

```<code>WITH
  TEST_DATA AS
  (
  SELECT 1 ID, 'ORANGES' STR_1, 2 COUNT_1, 'APPLES' STR_2, 10 COUNT_2 FROM DUAL
  UNION
  SELECT 2 ID, 'APPLES' STR_1, 10 COUNT_1, 'ORANGES' STR_2, 2 COUNT_2 FROM DUAL
  UNION
  SELECT 3 ID, 'ORANGES' STR_1, 2 COUNT_1, 'BANANAS' STR_2, 1 COUNT_2 FROM DUAL
  UNION
  SELECT 4 ID, 'BANANAS' STR_1, 1 COUNT_1, 'APPLES' STR_2, 10 COUNT_2 FROM DUAL
  UNION
  SELECT 5 ID, 'BANANAS' STR_1, 1 COUNT_1, 'ORANGES' STR_2, 2 COUNT_2 FROM DUAL
  )
</code>```

Any help finding a solution to the above would be much appreciated.

Many thanks in advance.

答:
Use anti join (not exists operator):

```<code>select *
from test_data t
where not exists (
   select 1 from test_data t1
   where t.str_1 = t1.str_2
    and  t.str_2 = t1.str_1
    and (
       t.count_1 < t1.count_1
       or
       t.count_1 = t1.count_1
       and
       length( t.str_1 ) < length( t1.str_1 )
    )
)
order by id
</code>```

In a case when for a given pair of rows both counts and lengths are equal, then the query picks both rows.

Title: Oracle - Identifying Dominant Records

Body:
I have a table that contains two STRING values (all single words) along with a corresponding COUNT for each occurrence of the STRING, e.g;

ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     2         APPLES    10
2   APPLES      10        ORANGES   2
3   ORANGES     2         BANANAS   1
4   BANANAS     1         APPLES    10
5   BANANAS     1         ORANGES   2

N.B. STR_1 is considered the ‘master’ value. Also, the COUNT for each individual STRING value will be consistent between STR_1 And STR_2 and between rows (e.g. ORANGES will always have a COUNT of 2)

What I’m trying to achieve is to remove records whereby an ‘enantiomer’ exists, for example; in the above data, ID 2 would be considered an ‘enantiomer’ of ID 1 (ID 1.STR_1 = ID.2 STR_2 and ID 1.STR_2 = ID.2 STR_1), however, ID 2 would be considered the dominant record with ID 1 being discarded (because the COUNT for APPLES is greater than the COUNT for ORANGES) – therefore the desired output would be;

ID  STR_1       COUNT_1   STR_2     COUNT_2
2   APPLES      10        ORANGES   2
3   ORANGES     2         BANANAS   1
4   BANANAS     1         APPLES    10

IF a scenario exists whereby the COUNT values between different STRINGS match, the longest STRING would be considered the dominant record and retained e.g.;

ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     10        APPLES    10
2   APPLES      10        ORANGES   10
3   ORANGES     10        BANANAS   1
4   BANANAS     1         APPLES    10
5   BANANAS     1         ORANGES   10

With the desired output being;

ID  STR_1       COUNT_1   STR_2     COUNT_2
1   ORANGES     10        APPLES    10
3   ORANGES     10        BANANAS   1
4   BANANAS     1         APPLES    10

Test Data;

WITH
  TEST_DATA AS
  (
  SELECT 1 ID, 'ORANGES' STR_1, 2 COUNT_1, 'APPLES' STR_2, 10 COUNT_2 FROM DUAL
  UNION
  SELECT 2 ID, 'APPLES' STR_1, 10 COUNT_1, 'ORANGES' STR_2, 2 COUNT_2 FROM DUAL
  UNION
  SELECT 3 ID, 'ORANGES' STR_1, 2 COUNT_1, 'BANANAS' STR_2, 1 COUNT_2 FROM DUAL
  UNION
  SELECT 4 ID, 'BANANAS' STR_1, 1 COUNT_1, 'APPLES' STR_2, 10 COUNT_2 FROM DUAL
  UNION
  SELECT 5 ID, 'BANANAS' STR_1, 1 COUNT_1, 'ORANGES' STR_2, 2 COUNT_2 FROM DUAL
  )

Any help finding a solution to the above would be much appreciated.

Many thanks in advance.

Body:
Use anti join (not exists operator):

select *
from test_data t
where not exists (
   select 1 from test_data t1
   where t.str_1 = t1.str_2
    and  t.str_2 = t1.str_1
    and (
       t.count_1 < t1.count_1
       or
       t.count_1 = t1.count_1
       and
       length( t.str_1 ) < length( t1.str_1 )
    )
)
order by id

In a case when for a given pair of rows both counts and lengths are equal, then the query picks both rows.


问:
spring CORS and angular not working : HTTP status code 403 error
I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. My Angular code is running on http://localhost:4200 and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/token which I have specified in my login controller. Even though I have added cors configuration in server side, I get this error :-

Failed to load http://localhost:8181/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

(angular) login.service.ts:-

```<code>@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }
</code>```

}

(spring) SecurityConfig.java

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }
</code>```

LoginController.java

```<code>@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);

        return Collections.singletonMap("token", session.getId());
    }
}
</code>```

答:
inside your controller use the value from a .properties file

@Value("${cors.site.enable}")
private String site;

use @crossOrigin(site)

Body:
I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. My Angular code is running on http://localhost:4200 and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/token which I have specified in my login controller. Even though I have added cors configuration in server side, I get this error :-

Failed to load http://localhost:8181/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

(angular) login.service.ts:-

@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }

}

(spring) SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

LoginController.java

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);

        return Collections.singletonMap("token", session.getId());
    }
}


问:
simple html dom, scraping error Notice: Trying to get property of non-object in C:\xampp\htdocs\scraper\au_div_puller.php on line 60
I have written a scraper in php using simple html Dom.

Problem is that it returns the results but gives me an error

Can anyone point me in the right direction on how to fix it please
Error is:

Notice: Trying to get property of non-object in C:\xampp\htdocs\scraper\au_div_puller.php on line 60

Many thanks
Line 60 is

$Ex_Date = $tr->find('td', 0)->plaintext; // Find the first TD (starts with 0)

```<code> <?php
    //REQUIRED FILES
    require ('connect_mysql.php');
    require('simple_html_dom.php');

//SET VARIABLES OF WEBSITE TO CRAWL
$url = ('http://www.shares.com/ANZ');  //WEBSITE TO SCRAPE WITH MYSQL INJECTED FROM ABOVE
echo ($url . "<br>");

//SET USER AGENT TO BE GOOGLEBOT
        $opts = array  ('http'=>array(  'method'=>"GET", 'header' => 'User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', ));
        $context = stream_context_create($opts);
        //$html = new simple_html_dom();
        $response = file_get_html($url, false, $context);
        $html = str_get_html($response);

//CHECK IT IS NOT A 404 PAGE IF SO SKIP
if (!empty($html)) {
//CHECK IT IS NOT BLANK PAGE OR EMPTY PAGE IF SO SKIP
$count = count($html->find('table'));
if($count > 0){

//START TABLE PROCESSING
$table = $html->find('table', 0); // ID LOCK IE TABLE 0 (first table) Get the first table ??
foreach($table ->find('tr') as $tr) {     // Foreach row in the table!
$Ex_Date = $tr->find('td', 0)->plaintext; // Find the first TD (starts with 0)
if($Ex_Date == "" || $Ex_Date == " ") continue;  // Don't allow empty records
$Amount = $tr->find('td', 1)->plaintext; // Find the second TD (which will be 1)
$Franked = $tr->find('td', 2)->plaintext; // Find the third TD (which will be 2)
$Franking_Credit = $tr->find('td', 3)->plaintext; // Find the fourth TD (which will be 3)
$Books_Close = $tr->find('td', 4)->plaintext; // Find the fifth TD (which will be 4)
$Date_Payable = $tr->find('td', 5)->plaintext; // Find the sixth TD (which will be 5)

//MYSQL DATA FORMATTING
//ESCAPE STRINGS AND DATE FORMATTING
//Now validate the data with mysqli_real_escape_string(). This function will escape characters that cause problems, like single quotes.
//Note there needs to be an open connection to the MySQL server for this work, otherwise you'll have blank strings returned.
// convert 04-Dec-1997 to yyyy-mm-dd formate
// for other versions of date format see:   https://stackoverflow.com/questions/16139696/convert-date-to-mysql-date-format-php
$Ex_Date_c = mysqli_real_escape_string($conn, $Ex_Date);
    $Ex_Date_c = date('Y-m-d', strtotime($Ex_Date_c)); //fix date format
$Amount_c = mysqli_real_escape_string($conn, $Amount);
$Franked_c = mysqli_real_escape_string($conn, $Franked);
$Franking_Credit_c = mysqli_real_escape_string($conn, $Franking_Credit);
$Books_Close_c = mysqli_real_escape_string($conn, $Books_Close);
    $Books_Close_c = date('Y-m-d', strtotime($Books_Close_c));//fix date format
$Date_Payable_c = mysqli_real_escape_string($conn, $Date_Payable);
    $Date_Payable_c = date('Y-m-d', strtotime($Date_Payable_c));//fix date format

//MYSQL INSERT TIME AND TESTING
//MYSQL INSERT QUERY
$sql = "INSERT INTO $insertintotable    (stockcode, exchange, exdate, amount, franked, frankingcredit, booksclose, datepayable, updatedatetime)
                            VALUES      ('$stockcode', 'ASX', '$Ex_Date_c', '$Amount_c', '$Franked_c', '$Franking_Credit_c', '$Books_Close_c', '$Date_Payable_c', '$updatedatetime')";
//MYSQL RESULT TEST
//echo ($sql . "<br>");  // Show the Mysql query

 if ($conn->query($sql) === TRUE)   {
 //                                 echo "New record created successfully <br>";  //TESTING --- Uncomment this code after verifying that the echo statements produce valid INSERT queries.
                                    }
                                    else {echo "Error: " . $sql . "<br>" . $conn->error;}

}
}
}
}
// CLOSE AND CLEAR SESSION
$html->clear();
unset($html);
}
$conn->close();
?>
</code>```

This is a prepared statement I could use that I copied off a learning site

```<code>// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
</code>```

答:
Since you can't guarantee that find('td', 0) will find a value, you must guarantee that you don't try to ask for the property plaintext if there is no td found.

```<code>$table = $html->find('table', 0); // ID LOCK IE TABLE 0 (first table) Get the first table ??
foreach($table ->find('tr') as $tr) {     // Foreach row in the table!
    if($td = $tr->find('td', 0)) {
        $Ex_Date = $td->plaintext; // Find the first TD (starts with 0)
        // ... and so on for each variable
</code>```

Granted, it's not as sexy as chaining them together, but the chaining only works if you know that the first method ($td in my example) will always return an object having the method/property you're calling.

On a side note, you should also look at using prepared statements (values(?,?,?,?,?,?,?,?)) instead of sticking values into your $sql variable.

Body:
I have written a scraper in php using simple html Dom.

Problem is that it returns the results but gives me an error

Can anyone point me in the right direction on how to fix it please
Error is:

Notice: Trying to get property of non-object in C:\xampp\htdocs\scraper\au_div_puller.php on line 60

Many thanks
Line 60 is

$Ex_Date = $tr->find('td', 0)->plaintext; // Find the first TD (starts with 0)

 <?php
    //REQUIRED FILES
    require ('connect_mysql.php');
    require('simple_html_dom.php');

//SET VARIABLES OF WEBSITE TO CRAWL
$url = ('http://www.shares.com/ANZ');  //WEBSITE TO SCRAPE WITH MYSQL INJECTED FROM ABOVE
echo ($url . "
");

//SET USER AGENT TO BE GOOGLEBOT
        $opts = array  ('http'=>array(  'method'=>"GET", 'header' => 'User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', ));
        $context = stream_context_create($opts);
        //$html = new simple_html_dom();
        $response = file_get_html($url, false, $context);
        $html = str_get_html($response);

//CHECK IT IS NOT A 404 PAGE IF SO SKIP
if (!empty($html)) {
//CHECK IT IS NOT BLANK PAGE OR EMPTY PAGE IF SO SKIP
$count = count($html->find('table'));
if($count > 0){

//START TABLE PROCESSING
$table = $html->find('table', 0); // ID LOCK IE TABLE 0 (first table) Get the first table ??
foreach($table ->find('tr') as $tr) {     // Foreach row in the table!
$Ex_Date = $tr->find('td', 0)->plaintext; // Find the first TD (starts with 0)
if($Ex_Date == "" || $Ex_Date == " ") continue;  // Don't allow empty records
$Amount = $tr->find('td', 1)->plaintext; // Find the second TD (which will be 1)
$Franked = $tr->find('td', 2)->plaintext; // Find the third TD (which will be 2)
$Franking_Credit = $tr->find('td', 3)->plaintext; // Find the fourth TD (which will be 3)
$Books_Close = $tr->find('td', 4)->plaintext; // Find the fifth TD (which will be 4)
$Date_Payable = $tr->find('td', 5)->plaintext; // Find the sixth TD (which will be 5)

//MYSQL DATA FORMATTING
//ESCAPE STRINGS AND DATE FORMATTING
//Now validate the data with mysqli_real_escape_string(). This function will escape characters that cause problems, like single quotes.
//Note there needs to be an open connection to the MySQL server for this work, otherwise you'll have blank strings returned.
// convert 04-Dec-1997 to yyyy-mm-dd formate
// for other versions of date format see:   https://stackoverflow.com/questions/16139696/convert-date-to-mysql-date-format-php
$Ex_Date_c = mysqli_real_escape_string($conn, $Ex_Date);
    $Ex_Date_c = date('Y-m-d', strtotime($Ex_Date_c)); //fix date format
$Amount_c = mysqli_real_escape_string($conn, $Amount);
$Franked_c = mysqli_real_escape_string($conn, $Franked);
$Franking_Credit_c = mysqli_real_escape_string($conn, $Franking_Credit);
$Books_Close_c = mysqli_real_escape_string($conn, $Books_Close);
    $Books_Close_c = date('Y-m-d', strtotime($Books_Close_c));//fix date format
$Date_Payable_c = mysqli_real_escape_string($conn, $Date_Payable);
    $Date_Payable_c = date('Y-m-d', strtotime($Date_Payable_c));//fix date format

//MYSQL INSERT TIME AND TESTING
//MYSQL INSERT QUERY
$sql = "INSERT INTO $insertintotable    (stockcode, exchange, exdate, amount, franked, frankingcredit, booksclose, datepayable, updatedatetime)
                            VALUES      ('$stockcode', 'ASX', '$Ex_Date_c', '$Amount_c', '$Franked_c', '$Franking_Credit_c', '$Books_Close_c', '$Date_Payable_c', '$updatedatetime')";
//MYSQL RESULT TEST
//echo ($sql . "
");  // Show the Mysql query

 if ($conn->query($sql) === TRUE)   {
 //                                 echo "New record created successfully
";  //TESTING --- Uncomment this code after verifying that the echo statements produce valid INSERT queries.
                                    }
                                    else {echo "Error: " . $sql . "
" . $conn->error;}

}
}
}
}
// CLOSE AND CLEAR SESSION
$html->clear();
unset($html);
}
$conn->close();
?>

This is a prepared statement I could use that I copied off a learning site

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();

Body:
Since you can't guarantee that find('td', 0) will find a value, you must guarantee that you don't try to ask for the property plaintext if there is no td found.

$table = $html->find('table', 0); // ID LOCK IE TABLE 0 (first table) Get the first table ??
foreach($table ->find('tr') as $tr) {     // Foreach row in the table!
    if($td = $tr->find('td', 0)) {
        $Ex_Date = $td->plaintext; // Find the first TD (starts with 0)
        // ... and so on for each variable

Granted, it's not as sexy as chaining them together, but the chaining only works if you know that the first method ($td in my example) will always return an object having the method/property you're calling.

On a side note, you should also look at using prepared statements (values(?,?,?,?,?,?,?,?)) instead of sticking values into your $sql variable.


问:
best way to create a form inside your iphone application
What is the best way to create a contact form inside an iphone application. Should an html page be embedded or can it be done using only objective c? </p>

答:
XCode has a component called Interface Builder, which is perfect for forms.
Yes, it uses an objective c interface.
I wouldn't say it's the only way, but I strongly imagine it's the best.</p>


问:
How to read mutliline input from stdin into variable and how to print one out in shell(sh,bash)?
What I want to do is the following:

read in multiple line input from stdin into variable A

make various operations on A

pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command

The current problem is that, I can't read it in with read command, because it stops reading at newline.

I can read stdin with cat, like this:

```<code>my_var=`cat /dev/stdin`
</code>```

, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.

My sample script looks like this:

```<code>#!/usr/local/bin/bash

A=`cat /dev/stdin`

if [ ${#A} -eq 0 ]; then
        exit 0
else
        cat ${A} | /usr/local/sbin/nextcommand
fi
</code>```

答:
[updated]

This assignment will hang indefinitely if there is nothing in the pipe...

```<code>var="$(< /dev/stdin)"
</code>```

We can prevent this though by doing a timeout read for the first character. If it times out, the return code will be greater than 128 and we'll know the STDIN pipe (a.k.a /dev/stdin) is empty.

Otherwise, we get the rest of STDIN by...

setting IFS to NULL for just the read command

turning off escapes with -r

eliminating read's delimiter with -d ''.

and finally, appending that to the character we got initially

Thus...

```<code>__=""
_stdin=""

read -N1 -t1 __  && {
  (( $? <= 128 ))  && {
    IFS= read -rd '' _stdin
    _stdin="$__$_stdin"
  }
}
</code>```

This technique avoids using var="$(command ...)" Command Substitution which, by design, will always strip off any trailing newlines.

If Command Substitution is preferred, to preserve trailing newlines we can append one or more delimiter characters to the output inside the $() and then strip them off outside.

For example ( note $(parens) in first command and ${braces} in second )...

```<code>_stdin="$(awk '{print}; END {print "|||"}' /dev/stdin)"
_stdin="${_stdin%|||}"
</code>```

OwnerDisplayName: kakas

Body:
What I want to do is the following:

read in multiple line input from stdin into variable A

make various operations on A

pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command

The current problem is that, I can't read it in with read command, because it stops reading at newline.

I can read stdin with cat, like this:

my_var=`cat /dev/stdin`

, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.

My sample script looks like this:

#!/usr/local/bin/bash

A=`cat /dev/stdin`

if [ ${#A} -eq 0 ]; then
        exit 0
else
        cat ${A} | /usr/local/sbin/nextcommand
fi

Body:
[updated]

This assignment will hang indefinitely if there is nothing in the pipe...

var="$(< /dev/stdin)"

We can prevent this though by doing a timeout read for the first character. If it times out, the return code will be greater than 128 and we'll know the STDIN pipe (a.k.a /dev/stdin) is empty.

Otherwise, we get the rest of STDIN by...

setting IFS to NULL for just the read command

turning off escapes with -r

eliminating read's delimiter with -d ''.

and finally, appending that to the character we got initially

Thus...

__=""
_stdin=""

read -N1 -t1 __  && {
  (( $? <= 128 ))  && {
    IFS= read -rd '' _stdin
    _stdin="$__$_stdin"
  }
}

This technique avoids using var="$(command ...)" Command Substitution which, by design, will always strip off any trailing newlines.

If Command Substitution is preferred, to preserve trailing newlines we can append one or more delimiter characters to the output inside the $() and then strip them off outside.

For example ( note $(parens) in first command and ${braces} in second )...

_stdin="$(awk '{print}; END {print "|||"}' /dev/stdin)"
_stdin="${_stdin%|||}"


问:
Apple PushKit didUpdatePushCredentials is never called on iOS 9+
I am developing a VoIP app for iPhone. To receive calls, Apple developed PushKit so developers can send VoIP notifications using APNS.

Everything was working fine on iOS 8. When I updated to iOS 9, the PKRegistryDelegate does not fire the method didUpdatePushCredentials after registration.

Any ideas/suggestions?

答:
So I had this problem as well, and spent two days pulling my hair out. I did all of these:

clean project turn on / off background modes

turn on / off push notifications

restart x-code

restart computer

removed app from device

cleaned /Library/Developer/DerivedData

then i'd revoke all certificates, removed all provisioning profiles. Removed them even from my keychain. Created everything again and installed it again in keychain and xcode.

All of this did not help.

Then, for some reason i thought, what if i just turn my phone, which i was testing with, off and on again.

and then it worked...


问:
ASP.NET / Webforms / C# - populating 2nd dropdown based on 1st dropdown without postback with code behind binding
Please help.

I have 3 dropdowns :
1. Country
2. Port
3. Company Name

Once 1st dropdown (countries) is selected, 2nd dropdown should be populated with a list of specific ports, then based on 1st and 2nd dropdown, the 3rd dropdown will be populated also.

this is a one time key-in. Meaning once selection is done, the user will save it in db and the value should remain in the dropdown unless the user change.

Right now, i'm using OnSelectedIndexChanged which is very slow because of the postback.

let me know if there's any other way of doing.

Thanks,
Jack

答:
You basically have 2 options, preload your values into a js structure (counties, ports and companies), or use a ajax/xmlhttprequest call to load just the relevant information (just the ports for a specific country).  If preloading the values, you can either mix it in with your html in the body of a script tag, or have it be a seperate file that is loaded via a src attribute.

Which is best to use will vary based upon your user base and data size, and how frequently the data changes.


问:
Angular 4: How to include external js libraries?
I know there were some of this topics, but I didn't find the solution for my problem.

I've tried to include this lib: https://github.com/euoia/hex-grid.js#new_module_hex-grid--HexGrid_new unfortunatelly I couldn't.

I put the unzipped project into src/js folder.
Into angular-cli.json inside the scripts tag I put the url to the hex-grid.js:
"scripts": ["js/hex-grid.js-master/src/hex-grid.js"]. the route is good, because the app was compiled succesfully.
I have a game-map.component.ts file where I want to use this lib.

```<code>import {Component} from '@angular/core';

declare var hexGrid: any;

@Component({
  selector: 'app-game-map',
  templateUrl: './game-map.component.html',
  styleUrls: ['./game-map.component.css']
})
export class GameMapComponent {

hex: any;

constructor() {
  this.hex = new hexGrid({
    width: 20,
    height: 10,
    orientation: 'flat-topped',
    layout: 'odd-q'
  });
  }
}
</code>```

But I got this error: Uncaught ReferenceError: module is not defined
    at scripts.bundle.js:2

And it has problem with this module: module.exports = (function () {
    /**

Someone can help me in this issue?
Thanks!

答:
To use this technique you have to place your someJsFile.js in your public folder so as the gwt compiler copy it to the final folder where it places the html and js stuff.

If you are using maven you have to check if the resources plugin is copying this file to the war and in which path.

By the way, there are other techniques to insert external javascript in your document:

Placing the script tag in your .html file.
Using ScriptInjector.fromUrl().
A better approach is to use a TextResource and ScriptInjector.fromString() so as the compiler reads the javascript file and includes the content in the final compiled file.
You can use gwtquery Ajax.getScript to get the script via ajax and inject it in the dom.
A new way, recently added to gwtquery, allows you to include your javascript as a JSNI block, so as the compiler can optimize and obfuscate it.

Body:
I know there were some of this topics, but I didn't find the solution for my problem.

I've tried to include this lib: https://github.com/euoia/hex-grid.js#new_module_hex-grid--HexGrid_new unfortunatelly I couldn't.

I put the unzipped project into src/js folder.
Into angular-cli.json inside the scripts tag I put the url to the hex-grid.js:
"scripts": ["js/hex-grid.js-master/src/hex-grid.js"]. the route is good, because the app was compiled succesfully.
I have a game-map.component.ts file where I want to use this lib.

import {Component} from '@angular/core';

declare var hexGrid: any;

@Component({
  selector: 'app-game-map',
  templateUrl: './game-map.component.html',
  styleUrls: ['./game-map.component.css']
})
export class GameMapComponent {

hex: any;

constructor() {
  this.hex = new hexGrid({
    width: 20,
    height: 10,
    orientation: 'flat-topped',
    layout: 'odd-q'
  });
  }
}

But I got this error: Uncaught ReferenceError: module is not defined
    at scripts.bundle.js:2

And it has problem with this module: module.exports = (function () {
    /**

Someone can help me in this issue?
Thanks!


问:
Speed up PowerShell script ( Invoke-Sqlcmd and Word Object )
So i have this loop in my script:

```<code>foreach ( $candID in Get-Content $candList )
{
    $candID = $candID -replace '\s',''
    $candID

    $templateDir = Get-ChildItem ($ScriptPath + "Templates\Resumes\") | Get-Random -Count 1
    $templateFile = $templateDir
    $templateDir =  ($ScriptPath + "Templates\Resumes\" + $templateDir)

    $lname = Invoke-Sqlcmd -Query "SELECT LEFT(personFirstName, 1) FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName

    $firstname = Invoke-Sqlcmd -Query "SELECT personFirstName FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $surname   = Invoke-Sqlcmd -Query "SELECT personSurname FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Address1  = Invoke-Sqlcmd -Query "SELECT CandidateAddress FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $City      = Invoke-Sqlcmd -Query "SELECT CandidateCity FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Postcode  = Invoke-Sqlcmd -Query "SELECT CandidatePostcode FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Mobile    = Invoke-Sqlcmd -Query "SELECT personMobileTelephone FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $State     = Invoke-Sqlcmd -Query "SELECT CandidateState FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName

    $firstname = $firstname.ItemArray[0]
    $surname   = $surname.ItemArray[0]
    $Address1  = $Address1.ItemArray[0]
    $City      = $City.ItemArray[0]
    $Postcode  = $Postcode.ItemArray[0]
    $Mobile    = $Mobile.ItemArray[0]
    $State     = $State.ItemArray[0]
    $lName     = $lName.ItemArray[0]

    cls

    ### Loop Visual
    Write-Host ""
    Write-Host "Generating resumes" -ForegroundColor Cyan
    Write-Host " ---------------------------------------------------------------------------------------------------- "
    Write-Host ""
    Write-Host ""
    Write-Host "Using resume template: $templateFile" -foregroundColor GREEN
    Write-Host ""
    Write-Host "Data:"

    Write-Host "    Firstname   = $firstname"
    Write-Host "    surname     = $surname"
    Write-Host "    Address1    = $Address1"
    Write-Host "    City        = $City"
    Write-Host "    Postcode    = $Postcode"
    Write-Host "    Mobile      = $Mobile"
    Write-Host "    State       = $State"

    ### End Loop Visual

    $filename = ($firstname + " " + $surname + " - " + $candID + ".doc")
    $filename2 = ($firstname + " " + $surname + " - " + $candID + ".txt")

    $saveAs = ($scriptPath + "Documents\Original Resumes\" + $lName + "\" + $filename)
    $saveAs2 = ($scriptPath + "Documents\Original Resumes\" + $lName + "\" + $filename2)

    $objWord = New-Object -comobject Word.Application
    $doc=$objWord.documents.Add($templateDir)
    $objWord.Visible = $false
    $doc.Bookmarks.Item("Address1").Range.Text = $Address1
    $doc.Bookmarks.Item("firstName").Range.Text = $firstname
    $doc.Bookmarks.Item("surName").Range.Text = $surname
    $doc.Bookmarks.Item("City").Range.Text = $City
    $doc.Bookmarks.Item("Postcode").Range.Text = $Postcode
    $doc.Bookmarks.Item("Mobile").Range.Text = $Mobile
    $doc.Bookmarks.Item("State").Range.Text = $State
    $doc.SaveAs([REF]$saveAs)
    $doc.Close()

    $doc2=$objWord.documents.Add($saveAs)
    $doc2.SaveAs([REF]$saveAs2, [REF] 2)

    $objWord.Quit()
}
</code>```

Basically, I am creating spoof resumes for records in the database using word templates. The script works but it is only creating around 2 - 3 resumes every 5 seconds, this is a bit of an issue since I need to fill the entire database ( 1 million spoofed records ).

Plus, it will only get longer since at some point I will be customising this so the template isn't random but instead catered to the industry of the person, as well as adding a lot more data into each resume ( skills, references etc ).

Is there anything I can do to speed this up a bit?

答:
The first step is ensuring that you are running this script under PowerShell 3.0 or higher. The office COM objects are known for poor performance in PowerShell 2.0, and without editing your script it will likely run faster.

For your script as a whole, I would adjust the portion of retrieving data from SQL Server. As commented you can make this into one call.

Which without having sample data or knowing what that file in $candList really contains, you can make the top half of your script something like this:

```<code>$candData = Get-Content $candList -Raw | ForEach-Object {$_ -replace '\s',''}

$qry = "
    SELECT personFistName,
        LEFT(personFirstName, 1) AS personLastName,
        personSurname,
        CandidateAddress,
        CandidateCity,
        CandidatePostcode,
        personMobileTelephone,
        CandidateState
    FROM tblCandidate
    WHERE personID IN ($($candData -split ','));
"
$templateDir = Get-ChildItem ($ScriptPath + "Templates\Resumes\") | Get-Random -Count 1
$templateFile = $templateDir
$templateDir =  ($ScriptPath + "Templates\Resumes\" + $templateDir)

$data = Invoke-SqlCmd -ServerInstance $ServerAddress -Database $DatabaseName -Query $qry

foreach ($row in $data) {
    $lname = $row.personLastName
    $firstname = $row.personFirstName
    $surname   = $row.personSurname
    $Address1  = $row.CandidateAddress
    $City      = $row.CandidateCity
    $Postcode  = $row.CandidatePostcode
    $Mobile    = $row.personMobileTelephone
    $State     = $row.CandidateState
</code>```

Body:
So i have this loop in my script:

foreach ( $candID in Get-Content $candList )
{
    $candID = $candID -replace '\s',''
    $candID

    $templateDir = Get-ChildItem ($ScriptPath + "Templates\Resumes\") | Get-Random -Count 1
    $templateFile = $templateDir
    $templateDir =  ($ScriptPath + "Templates\Resumes\" + $templateDir)

    $lname = Invoke-Sqlcmd -Query "SELECT LEFT(personFirstName, 1) FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName

    $firstname = Invoke-Sqlcmd -Query "SELECT personFirstName FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $surname   = Invoke-Sqlcmd -Query "SELECT personSurname FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Address1  = Invoke-Sqlcmd -Query "SELECT CandidateAddress FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $City      = Invoke-Sqlcmd -Query "SELECT CandidateCity FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Postcode  = Invoke-Sqlcmd -Query "SELECT CandidatePostcode FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $Mobile    = Invoke-Sqlcmd -Query "SELECT personMobileTelephone FROM tblPErson WHERE personID = $candID" -serverinstance $ServerAddress -Database $DatabaseName
    $State     = Invoke-Sqlcmd -Query "SELECT CandidateState FROM tblCandidate WHERE CandidateID = $candID" -serverinstance $ServerAddress -Database $DatabaseName

    $firstname = $firstname.ItemArray[0]
    $surname   = $surname.ItemArray[0]
    $Address1  = $Address1.ItemArray[0]
    $City      = $City.ItemArray[0]
    $Postcode  = $Postcode.ItemArray[0]
    $Mobile    = $Mobile.ItemArray[0]
    $State     = $State.ItemArray[0]
    $lName     = $lName.ItemArray[0]

    cls

    ### Loop Visual
    Write-Host ""
    Write-Host "Generating resumes" -ForegroundColor Cyan
    Write-Host " ---------------------------------------------------------------------------------------------------- "
    Write-Host ""
    Write-Host ""
    Write-Host "Using resume template: $templateFile" -foregroundColor GREEN
    Write-Host ""
    Write-Host "Data:"

    Write-Host "    Firstname   = $firstname"
    Write-Host "    surname     = $surname"
    Write-Host "    Address1    = $Address1"
    Write-Host "    City        = $City"
    Write-Host "    Postcode    = $Postcode"
    Write-Host "    Mobile      = $Mobile"
    Write-Host "    State       = $State"

    ### End Loop Visual

    $filename = ($firstname + " " + $surname + " - " + $candID + ".doc")
    $filename2 = ($firstname + " " + $surname + " - " + $candID + ".txt")

    $saveAs = ($scriptPath + "Documents\Original Resumes\" + $lName + "\" + $filename)
    $saveAs2 = ($scriptPath + "Documents\Original Resumes\" + $lName + "\" + $filename2)

    $objWord = New-Object -comobject Word.Application
    $doc=$objWord.documents.Add($templateDir)
    $objWord.Visible = $false
    $doc.Bookmarks.Item("Address1").Range.Text = $Address1
    $doc.Bookmarks.Item("firstName").Range.Text = $firstname
    $doc.Bookmarks.Item("surName").Range.Text = $surname
    $doc.Bookmarks.Item("City").Range.Text = $City
    $doc.Bookmarks.Item("Postcode").Range.Text = $Postcode
    $doc.Bookmarks.Item("Mobile").Range.Text = $Mobile
    $doc.Bookmarks.Item("State").Range.Text = $State
    $doc.SaveAs([REF]$saveAs)
    $doc.Close()

    $doc2=$objWord.documents.Add($saveAs)
    $doc2.SaveAs([REF]$saveAs2, [REF] 2)

    $objWord.Quit()
}

Basically, I am creating spoof resumes for records in the database using word templates. The script works but it is only creating around 2 - 3 resumes every 5 seconds, this is a bit of an issue since I need to fill the entire database ( 1 million spoofed records ).

Plus, it will only get longer since at some point I will be customising this so the template isn't random but instead catered to the industry of the person, as well as adding a lot more data into each resume ( skills, references etc ).

Is there anything I can do to speed this up a bit?

Body:
The first step is ensuring that you are running this script under PowerShell 3.0 or higher. The office COM objects are known for poor performance in PowerShell 2.0, and without editing your script it will likely run faster.

For your script as a whole, I would adjust the portion of retrieving data from SQL Server. As commented you can make this into one call.

Which without having sample data or knowing what that file in $candList really contains, you can make the top half of your script something like this:

$candData = Get-Content $candList -Raw | ForEach-Object {$_ -replace '\s',''}

$qry = "
    SELECT personFistName,
        LEFT(personFirstName, 1) AS personLastName,
        personSurname,
        CandidateAddress,
        CandidateCity,
        CandidatePostcode,
        personMobileTelephone,
        CandidateState
    FROM tblCandidate
    WHERE personID IN ($($candData -split ','));
"
$templateDir = Get-ChildItem ($ScriptPath + "Templates\Resumes\") | Get-Random -Count 1
$templateFile = $templateDir
$templateDir =  ($ScriptPath + "Templates\Resumes\" + $templateDir)

$data = Invoke-SqlCmd -ServerInstance $ServerAddress -Database $DatabaseName -Query $qry

foreach ($row in $data) {
    $lname = $row.personLastName
    $firstname = $row.personFirstName
    $surname   = $row.personSurname
    $Address1  = $row.CandidateAddress
    $City      = $row.CandidateCity
    $Postcode  = $row.CandidatePostcode
    $Mobile    = $row.personMobileTelephone
    $State     = $row.CandidateState


问:
Selenium Web Driver issue in Threading. C#
Here's the code.

```<code>browser = new FirefoxDriver();
browser.Navigate().GoToUrl("https://www.vicroads.vic.gov.au/registration/buy-sell-or-transfer-a-vehicle/buy-a-vehicle/check-vehicle-registration/vehicle-registration-enquiry");
Thread.Sleep(5000);
browser.FindElement(By.Name("ph_pagebody_0$phthreecolumnmaincontent_1$panel$VehicleSearch$RegistrationNumberCar$RegistrationNumber_CtrlHolderDivShown")).SendKeys("asdf");
</code>```

It works ok but if I run in thread it shows element not visible.... why it's throwing in a thread?

答:
Element could be non-visible cuz page didnt reload at check moment or website using dynamic names, classes etc.

You can try something like this:

```<code>IWebDriver browser = new FirefoxDriver();
browser.Navigate().GoToUrl("https://www.vicroads.vic.gov.au/registration/buy-sell-or-transfer-a-vehicle/buy-a-vehicle/check-vehicle-registration/vehicle-registration-enquiry");

while ( true ) {
    try {
        browser.FindElement(By.Name("ph_pagebody_0$phthreecolumnmaincontent_1$panel$VehicleSearch$RegistrationNumberCar$RegistrationNumber_CtrlHolderDivShown")).SendKeys("asdf");
        break;
    }
    catch { Thread.Sleep(1000);}
}
</code>```

Body:
Here's the code.

browser = new FirefoxDriver();
browser.Navigate().GoToUrl("https://www.vicroads.vic.gov.au/registration/buy-sell-or-transfer-a-vehicle/buy-a-vehicle/check-vehicle-registration/vehicle-registration-enquiry");
Thread.Sleep(5000);
browser.FindElement(By.Name("ph_pagebody_0$phthreecolumnmaincontent_1$panel$VehicleSearch$RegistrationNumberCar$RegistrationNumber_CtrlHolderDivShown")).SendKeys("asdf");

It works ok but if I run in thread it shows element not visible.... why it's throwing in a thread?

Body:
Element could be non-visible cuz page didnt reload at check moment or website using dynamic names, classes etc.

You can try something like this:

IWebDriver browser = new FirefoxDriver();
browser.Navigate().GoToUrl("https://www.vicroads.vic.gov.au/registration/buy-sell-or-transfer-a-vehicle/buy-a-vehicle/check-vehicle-registration/vehicle-registration-enquiry");

while ( true ) {
    try {
        browser.FindElement(By.Name("ph_pagebody_0$phthreecolumnmaincontent_1$panel$VehicleSearch$RegistrationNumberCar$RegistrationNumber_CtrlHolderDivShown")).SendKeys("asdf");
        break;
    }
    catch { Thread.Sleep(1000);}
}