问:
Convert integers to written numbers
Is there an efficient method of converting an integer into the written numbers, for example:

```<code>string Written = IntegerToWritten(21);
</code>```

would return "Twenty One".

Is there any way of doing this that doesn't involve a massive look-up table?

答:
The following C# console app code will accepts a monetary value in numbers up to 2 decimals and prints it in English. This not only converts integer to its English equivalent but as a monetary value in dollars and cents. </p>

```<code> namespace ConsoleApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    class Program
    {
       static void Main(string[] args)
        {
            bool repeat = true;
            while (repeat)
            {
                string inputMonetaryValueInNumberic = string.Empty;
                string centPart = string.Empty;
                string dollarPart = string.Empty;
                Console.Write("\nEnter the monetary value : ");
                inputMonetaryValueInNumberic = Console.ReadLine();
                inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');

                if (ValidateInput(inputMonetaryValueInNumberic))
                {

                    if (inputMonetaryValueInNumberic.Contains('.'))
                    {
                        centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(".") + 1));
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(".")));
                    }
                    else
                    {
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic);
                    }
                    centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : " and " + centPart;
                    Console.WriteLine(string.Format("\n\n{0}{1}", dollarPart, centPart));
                }
                else
                {
                    Console.WriteLine("Invalid Input..");
                }

                Console.WriteLine("\n\nPress any key to continue or Escape of close : ");
                var loop = Console.ReadKey();
                repeat = !loop.Key.ToString().Contains("Escape");
                Console.Clear();
            }

        }

        private static string ProcessCents(string cents)
        {
            string english = string.Empty;
            string dig3 = Process3Digit(cents);
            if (!string.IsNullOrWhiteSpace(dig3))
            {
                dig3 = string.Format("{0} {1}", dig3, GetSections(0));
            }
            english = dig3 + english;
            return english;
        }
        private static string ProcessDollar(string dollar)
        {
            string english = string.Empty;
            foreach (var item in Get3DigitList(dollar))
            {
                string dig3 = Process3Digit(item.Value);
                if (!string.IsNullOrWhiteSpace(dig3))
                {
                    dig3 = string.Format("{0} {1}", dig3, GetSections(item.Key));
                }
                english = dig3 + english;
            }
            return english;
        }
        private static string Process3Digit(string digit3)
        {
            string result = string.Empty;
            if (Convert.ToInt32(digit3) != 0)
            {
                int place = 0;
                Stack<string> monetaryValue = new Stack<string>();
                for (int i = digit3.Length - 1; i >= 0; i--)
                {
                    place += 1;
                    string stringValue = string.Empty;
                    switch (place)
                    {
                        case 1:
                            stringValue = GetOnes(digit3[i].ToString());
                            break;
                        case 2:
                            int tens = Convert.ToInt32(digit3[i]);
                            if (tens == 1)
                            {
                                if (monetaryValue.Count > 0)
                                {
                                    monetaryValue.Pop();
                                }
                                stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));
                            }
                            else
                            {
                                stringValue = GetTens(digit3[i].ToString());
                            }
                            break;
                        case 3:
                            stringValue = GetOnes(digit3[i].ToString());
                            if (!string.IsNullOrWhiteSpace(stringValue))
                            {
                                string postFixWith = " Hundred";
                                if (monetaryValue.Count > 0)
                                {
                                    postFixWith = postFixWith + " And";
                                }
                                stringValue += postFixWith;
                            }
                            break;
                    }
                    if (!string.IsNullOrWhiteSpace(stringValue))
                        monetaryValue.Push(stringValue);
                }
                while (monetaryValue.Count > 0)
                {
                    result += " " + monetaryValue.Pop().ToString().Trim();
                }
            }
            return result;
        }
        private static Dictionary<int, string> Get3DigitList(string monetaryValueInNumberic)
        {
            Dictionary<int, string> hundredsStack = new Dictionary<int, string>();
            int counter = 0;
            while (monetaryValueInNumberic.Length >= 3)
            {
                string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);
                monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);
                hundredsStack.Add(++counter, digit3);
            }
            if (monetaryValueInNumberic.Length != 0)
                hundredsStack.Add(++counter, monetaryValueInNumberic);
            return hundredsStack;
        }
        private static string GetTens(string tensPlaceValue)
        {
            string englishEquvalent = string.Empty;
            int value = Convert.ToInt32(tensPlaceValue);
            Dictionary<int, string> tens = new Dictionary<int, string>();
            tens.Add(2, "Twenty");
            tens.Add(3, "Thirty");
            tens.Add(4, "Forty");
            tens.Add(5, "Fifty");
            tens.Add(6, "Sixty");
            tens.Add(7, "Seventy");
            tens.Add(8, "Eighty");
            tens.Add(9, "Ninty");
            tens.Add(10, "Ten");
            tens.Add(11, "Eleven");
            tens.Add(12, "Twelve");
            tens.Add(13, "Thrteen");
            tens.Add(14, "Fourteen");
            tens.Add(15, "Fifteen");
            tens.Add(16, "Sixteen");
            tens.Add(17, "Seventeen");
            tens.Add(18, "Eighteen");
            tens.Add(19, "Ninteen");
            if (tens.ContainsKey(value))
            {
                englishEquvalent = tens[value];
            }

            return englishEquvalent;

        }
        private static string GetOnes(string onesPlaceValue)
        {
            int value = Convert.ToInt32(onesPlaceValue);
            string englishEquvalent = string.Empty;
            Dictionary<int, string> ones = new Dictionary<int, string>();
            ones.Add(1, " One");
            ones.Add(2, " Two");
            ones.Add(3, " Three");
            ones.Add(4, " Four");
            ones.Add(5, " Five");
            ones.Add(6, " Six");
            ones.Add(7, " Seven");
            ones.Add(8, " Eight");
            ones.Add(9, " Nine");

            if (ones.ContainsKey(value))
            {
                englishEquvalent = ones[value];
            }

            return englishEquvalent;
        }
        private static string GetSections(int section)
        {
            string sectionName = string.Empty;
            switch (section)
            {
                case 0:
                    sectionName = "Cents";
                    break;
                case 1:
                    sectionName = "Dollars";
                    break;
                case 2:
                    sectionName = "Thousand";
                    break;
                case 3:
                    sectionName = "Million";
                    break;
                case 4:
                    sectionName = "Billion";
                    break;
                case 5:
                    sectionName = "Trillion";
                    break;
                case 6:
                    sectionName = "Zillion";
                    break;
            }
            return sectionName;
        }
        private static bool ValidateInput(string input)
        {
            return Regex.IsMatch(input, "[0-9]{1,18}(\\.[0-9]{1,2})?"))
        }
    }
}
</code>```

Title: Convert integers to written numbers

Body:
Is there an efficient method of converting an integer into the written numbers, for example:

string Written = IntegerToWritten(21);

would return "Twenty One".

Is there any way of doing this that doesn't involve a massive look-up table?

LastEditorDisplayName: Gortok

Body:
The following C# console app code will accepts a monetary value in numbers up to 2 decimals and prints it in English. This not only converts integer to its English equivalent but as a monetary value in dollars and cents.

 namespace ConsoleApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    class Program
    {
       static void Main(string[] args)
        {
            bool repeat = true;
            while (repeat)
            {
                string inputMonetaryValueInNumberic = string.Empty;
                string centPart = string.Empty;
                string dollarPart = string.Empty;
                Console.Write("\nEnter the monetary value : ");
                inputMonetaryValueInNumberic = Console.ReadLine();
                inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');

                if (ValidateInput(inputMonetaryValueInNumberic))
                {

                    if (inputMonetaryValueInNumberic.Contains('.'))
                    {
                        centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(".") + 1));
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(".")));
                    }
                    else
                    {
                        dollarPart = ProcessDollar(inputMonetaryValueInNumberic);
                    }
                    centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : " and " + centPart;
                    Console.WriteLine(string.Format("\n\n{0}{1}", dollarPart, centPart));
                }
                else
                {
                    Console.WriteLine("Invalid Input..");
                }

                Console.WriteLine("\n\nPress any key to continue or Escape of close : ");
                var loop = Console.ReadKey();
                repeat = !loop.Key.ToString().Contains("Escape");
                Console.Clear();
            }

        }

        private static string ProcessCents(string cents)
        {
            string english = string.Empty;
            string dig3 = Process3Digit(cents);
            if (!string.IsNullOrWhiteSpace(dig3))
            {
                dig3 = string.Format("{0} {1}", dig3, GetSections(0));
            }
            english = dig3 + english;
            return english;
        }
        private static string ProcessDollar(string dollar)
        {
            string english = string.Empty;
            foreach (var item in Get3DigitList(dollar))
            {
                string dig3 = Process3Digit(item.Value);
                if (!string.IsNullOrWhiteSpace(dig3))
                {
                    dig3 = string.Format("{0} {1}", dig3, GetSections(item.Key));
                }
                english = dig3 + english;
            }
            return english;
        }
        private static string Process3Digit(string digit3)
        {
            string result = string.Empty;
            if (Convert.ToInt32(digit3) != 0)
            {
                int place = 0;
                Stack<string> monetaryValue = new Stack<string>();
                for (int i = digit3.Length - 1; i >= 0; i--)
                {
                    place += 1;
                    string stringValue = string.Empty;
                    switch (place)
                    {
                        case 1:
                            stringValue = GetOnes(digit3[i].ToString());
                            break;
                        case 2:
                            int tens = Convert.ToInt32(digit3[i]);
                            if (tens == 1)
                            {
                                if (monetaryValue.Count > 0)
                                {
                                    monetaryValue.Pop();
                                }
                                stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));
                            }
                            else
                            {
                                stringValue = GetTens(digit3[i].ToString());
                            }
                            break;
                        case 3:
                            stringValue = GetOnes(digit3[i].ToString());
                            if (!string.IsNullOrWhiteSpace(stringValue))
                            {
                                string postFixWith = " Hundred";
                                if (monetaryValue.Count > 0)
                                {
                                    postFixWith = postFixWith + " And";
                                }
                                stringValue += postFixWith;
                            }
                            break;
                    }
                    if (!string.IsNullOrWhiteSpace(stringValue))
                        monetaryValue.Push(stringValue);
                }
                while (monetaryValue.Count > 0)
                {
                    result += " " + monetaryValue.Pop().ToString().Trim();
                }
            }
            return result;
        }
        private static Dictionary<int, string> Get3DigitList(string monetaryValueInNumberic)
        {
            Dictionary<int, string> hundredsStack = new Dictionary<int, string>();
            int counter = 0;
            while (monetaryValueInNumberic.Length >= 3)
            {
                string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);
                monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);
                hundredsStack.Add(++counter, digit3);
            }
            if (monetaryValueInNumberic.Length != 0)
                hundredsStack.Add(++counter, monetaryValueInNumberic);
            return hundredsStack;
        }
        private static string GetTens(string tensPlaceValue)
        {
            string englishEquvalent = string.Empty;
            int value = Convert.ToInt32(tensPlaceValue);
            Dictionary<int, string> tens = new Dictionary<int, string>();
            tens.Add(2, "Twenty");
            tens.Add(3, "Thirty");
            tens.Add(4, "Forty");
            tens.Add(5, "Fifty");
            tens.Add(6, "Sixty");
            tens.Add(7, "Seventy");
            tens.Add(8, "Eighty");
            tens.Add(9, "Ninty");
            tens.Add(10, "Ten");
            tens.Add(11, "Eleven");
            tens.Add(12, "Twelve");
            tens.Add(13, "Thrteen");
            tens.Add(14, "Fourteen");
            tens.Add(15, "Fifteen");
            tens.Add(16, "Sixteen");
            tens.Add(17, "Seventeen");
            tens.Add(18, "Eighteen");
            tens.Add(19, "Ninteen");
            if (tens.ContainsKey(value))
            {
                englishEquvalent = tens[value];
            }

            return englishEquvalent;

        }
        private static string GetOnes(string onesPlaceValue)
        {
            int value = Convert.ToInt32(onesPlaceValue);
            string englishEquvalent = string.Empty;
            Dictionary<int, string> ones = new Dictionary<int, string>();
            ones.Add(1, " One");
            ones.Add(2, " Two");
            ones.Add(3, " Three");
            ones.Add(4, " Four");
            ones.Add(5, " Five");
            ones.Add(6, " Six");
            ones.Add(7, " Seven");
            ones.Add(8, " Eight");
            ones.Add(9, " Nine");

            if (ones.ContainsKey(value))
            {
                englishEquvalent = ones[value];
            }

            return englishEquvalent;
        }
        private static string GetSections(int section)
        {
            string sectionName = string.Empty;
            switch (section)
            {
                case 0:
                    sectionName = "Cents";
                    break;
                case 1:
                    sectionName = "Dollars";
                    break;
                case 2:
                    sectionName = "Thousand";
                    break;
                case 3:
                    sectionName = "Million";
                    break;
                case 4:
                    sectionName = "Billion";
                    break;
                case 5:
                    sectionName = "Trillion";
                    break;
                case 6:
                    sectionName = "Zillion";
                    break;
            }
            return sectionName;
        }
        private static bool ValidateInput(string input)
        {
            return Regex.IsMatch(input, "[0-9]{1,18}(\\.[0-9]{1,2})?"))
        }
    }
}


来源: stackexchange

问:
How to add AOV post hoc test to ggplot2 boxplot? I can't plot the labels on my graph
I wonder what's wrong to my code?

My code is like:

```<code>a=aov(tem.range~Butterfly.colonies, data=my.data)
summary(a)
tHSD <- TukeyHSD(a, ordered = FALSE, conf.level = 0.95)
tHSD
generate_label_df <- function(HSD, flev){
  # Extract labels and factor levels from Tukey post-hoc
  Tukey.levels <- HSD[[flev]][,4]
  Tukey.labels <- multcompLetters(Tukey.levels)['Letters']
  plot.labels <- names(Tukey.labels[['Letters']])
  boxplot.df <- ddply(my.data, flev, function (x) max(fivenum(x$y)) + 0.2)

  plot.levels <- data.frame(plot.labels, labels = Tukey.labels[['Letters']], stringsAsFactors = FALSE)
  # Merge it with the labels
  labels.df <- merge(plot.levels, boxplot.df, by.x = 'plot.labels', by.y = flev, sort = FALSE)
  return(labels.df)
}
ggplot(my.data, aes(x=Butterfly.colonies, y=tem.range))+
 geom_boxplot(width = 0.5) +
 scale_y_continuous(breaks = seq(0, 20, by = 2))+
 theme(plot.margin=unit(c(1,3,1,3),"cm"))+
 labs(y="tem.range(Celsius")+
 labs(x="Colony")+
 geom_text(data = generate_label_df(tHSD, 'Butterfly.colonies'),
    aes(x =  plot.labels, y = V1, label = labels))
</code>```

However, in the end there was an error

And thus, I can't put the label on my graph

I hope it will be like:

答:
my code:</p>

```<code>a=aov(tem.range~Butterfly.colonies,data=my.data)
tHSD <- TukeyHSD(a, ordered = FALSE, conf.level = 0.95)
generate_label_df <- function(HSD, flev){
Tukey.levels <- HSD[[flev]][,4]
Tukey.labels <- multcompLetters(Tukey.levels)['Letters']
plot.labels <- names(Tukey.labels[['Letters']])
boxplot.df <- ddply(my.data, flev, function (x) max(fivenum(x$y)) + 0.2)
plot.levels <- data.frame(plot.labels, labels = Tukey.labels[['Letters']],stringsAsFactors = FALSE)
labels.df <- merge(plot.levels, boxplot.df, by.x = 'plot.labels', by.y = flev, sort = FALSE)
return(labels.df)}
ggplot(my.data, aes(x=Butterfly.colonies, y=tem.range))+geom_boxplot(width = 0.5) + scale_y_continuous(breaks = seq(0, 20, by = 2))+ theme(plot.margin=unit(c(1,3,1,3),"cm"))+labs(y="tem.range(Celsius")+labs(x="Colony")+geom_text(data = generate_label_df(tHSD, 'Butterfly.colonies'), aes(x = plot.labels, y = V1, label = labels))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wonder what's wrong to my code?

My code is like:

a=aov(tem.range~Butterfly.colonies, data=my.data)
summary(a)
tHSD <- TukeyHSD(a, ordered = FALSE, conf.level = 0.95)
tHSD
generate_label_df <- function(HSD, flev){
  # Extract labels and factor levels from Tukey post-hoc
  Tukey.levels <- HSD[[flev]][,4]
  Tukey.labels <- multcompLetters(Tukey.levels)['Letters']
  plot.labels <- names(Tukey.labels[['Letters']])
  boxplot.df <- ddply(my.data, flev, function (x) max(fivenum(x$y)) + 0.2)

  plot.levels <- data.frame(plot.labels, labels = Tukey.labels[['Letters']], stringsAsFactors = FALSE)
  # Merge it with the labels
  labels.df <- merge(plot.levels, boxplot.df, by.x = 'plot.labels', by.y = flev, sort = FALSE)
  return(labels.df)
}
ggplot(my.data, aes(x=Butterfly.colonies, y=tem.range))+
 geom_boxplot(width = 0.5) +
 scale_y_continuous(breaks = seq(0, 20, by = 2))+
 theme(plot.margin=unit(c(1,3,1,3),"cm"))+
 labs(y="tem.range(Celsius")+
 labs(x="Colony")+
 geom_text(data = generate_label_df(tHSD, 'Butterfly.colonies'),
    aes(x =  plot.labels, y = V1, label = labels))

However, in the end there was an error

And thus, I can't put the label on my graph

I hope it will be like:

Body:
my code:

a=aov(tem.range~Butterfly.colonies,data=my.data)
tHSD <- TukeyHSD(a, ordered = FALSE, conf.level = 0.95)
generate_label_df <- function(HSD, flev){
Tukey.levels <- HSD[[flev]][,4]
Tukey.labels <- multcompLetters(Tukey.levels)['Letters']
plot.labels <- names(Tukey.labels[['Letters']])
boxplot.df <- ddply(my.data, flev, function (x) max(fivenum(x$y)) + 0.2)
plot.levels <- data.frame(plot.labels, labels = Tukey.labels[['Letters']],stringsAsFactors = FALSE)
labels.df <- merge(plot.levels, boxplot.df, by.x = 'plot.labels', by.y = flev, sort = FALSE)
return(labels.df)}
ggplot(my.data, aes(x=Butterfly.colonies, y=tem.range))+geom_boxplot(width = 0.5) + scale_y_continuous(breaks = seq(0, 20, by = 2))+ theme(plot.margin=unit(c(1,3,1,3),"cm"))+labs(y="tem.range(Celsius")+labs(x="Colony")+geom_text(data = generate_label_df(tHSD, 'Butterfly.colonies'), aes(x = plot.labels, y = V1, label = labels))


问:
Java Socket read from socket in real time
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

```<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}
</code>```

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush

答: Whenever the server gets some output from the program, it should push it out on the network and flush the stream.</p>

Body:
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush

ContentLicense: CC BY-SA 2.5


问:
Using jQuery I need to replace spaces inside href with hyphens
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

href="http://www.projectknow.com/find/New York/" class="spaces">

MUST BE REPLACED WITH

href="http://www.projectknow.com/find/New-York/" class="spaces">

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

```<code>var option = '';
for (var i = 0; i < states.length;i++){
    option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
    class="spaces">'+ states[i] +'</a></li>';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});
</code>```

答:
var states = [ 'New York', 'New Jersey', 'New Mexico' ];

$('.menu').append(states.map(function(state){
  return '
'+ state +'
';
}).join(''));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu"></ul></code>```

Body:
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

MUST BE REPLACED WITH

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

var option = '';
for (var i = 0; i < states.length;i++){
    option += '
'+ states[i] +'
';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});

Body:
var states = [ 'New York', 'New Jersey', 'New Mexico' ];

$('.menu').append(states.map(function(state){
  return '<li><a href="http://www.states.com/find/'+ state.replace(/[ ]/g, '-') +'/" class="spaces">'+ state +'</a></li>';
}).join(''));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu"></ul>


问:
How to query a child from another child. Firebase(SWIFT)
im developing a delivery app. So I have productos and popular products in firebase this way:

Products

PopularProducts(ID of the product as key and true as value)

How I can query only the products who are popular using those childs?

答:
You can query ordered by the esPopular child and only return the children with it equal to true.

```<code>let ref = Database.database().reference(withPath: "productos")
let query = ref.queryOrdered(byChild: "esPopular").queryEqual(toValue: true)

query.observe(.childAdded, with: { (snapshot) in
    print(snapshot)
}) { (error) in
    print(error)
}
</code>```

Body:
You can query ordered by the esPopular child and only return the children with it equal to true.

let ref = Database.database().reference(withPath: "productos")
let query = ref.queryOrdered(byChild: "esPopular").queryEqual(toValue: true)

query.observe(.childAdded, with: { (snapshot) in
    print(snapshot)
}) { (error) in
    print(error)
}


问:
Receiving uploaded file from client , rest
I am sending to backend a file, this is the upload code:

```<code>export class FileUploadComponent {

  @Input() multiple: boolean = false;
  @ViewChild('fileInput') inputEl: ElementRef;

  constructor(private http: Http) {}

  upload() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
      for (let i = 0; i < fileCount; i++) {
        formData.append('file[]', inputEl.files.item(i));
      }
      this.http
        .post('http://localhost:8080/upload', formData).toPromise().then(() => console.log('success')).catch(() => console.log('error'));
    }
  }
}
</code>```

Now on the backendside I'd like to receive it via controller, but I don't know how to map the file property, following gives null's:

```<code> public @ResponseBody String handleFileUpload(@RequestBody MultipartFile file)
</code>```

答:
Your method signature is incorrect.

@RequestBody annotation parameters maps to the HTTP request body.

@RequestParam annotation parameters maps to the specific Servlet request parameters.

Use the following:

```<code>public @ResponseBody String handleFileUpload(@RequestParam MultipartFile file)
</code>```

If you are sending multiple, then use array:

```<code>public @ResponseBody String handleFileUpload(@RequestParam MultipartFile[[] file)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am sending to backend a file, this is the upload code:

export class FileUploadComponent {

  @Input() multiple: boolean = false;
  @ViewChild('fileInput') inputEl: ElementRef;

  constructor(private http: Http) {}

  upload() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
      for (let i = 0; i < fileCount; i++) {
        formData.append('file[]', inputEl.files.item(i));
      }
      this.http
        .post('http://localhost:8080/upload', formData).toPromise().then(() => console.log('success')).catch(() => console.log('error'));
    }
  }
}

Now on the backendside I'd like to receive it via controller, but I don't know how to map the file property, following gives null's:

 public @ResponseBody String handleFileUpload(@RequestBody MultipartFile file)

Body:
Your method signature is incorrect.

@RequestBody annotation parameters maps to the HTTP request body.

@RequestParam annotation parameters maps to the specific Servlet request parameters.

Use the following:

public @ResponseBody String handleFileUpload(@RequestParam MultipartFile file)

If you are sending multiple, then use array:

public @ResponseBody String handleFileUpload(@RequestParam MultipartFile[[] file)


问:
How to rewrite this Java class to a Kotlin data class?
I have this in Java :

```<code>public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}
</code>```

In a Kotlin class its something like this :

```<code>class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}
</code>```

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters

答:
In Kotlin we can have that in a single constructor like this

```<code>data class User(var name: String, var age: Int = 0, var id: String = "ABC")
</code>```

If we want to expose getters and not setters, we just provide val instead of var like below,

```<code>data class User(val name: String, val age: Int = 0, val id: String = "ABC")
</code>```

getters/setters visibility modifiers we can provide them in the constructor like this,

```<code>data class User(internal val name, internal val age: Int = 0, internal var id: String = "ABC")
</code>```

In this above case, getter will be accessible only to that module.

We can create object like this,

```<code>    var user = User("XYZ")
    var user1 = User("XYZ", 29)
    var user2 = User("XYZ", 29, "AXCVFC")
</code>```

Body:
I have this in Java :

public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}

In a Kotlin class its something like this :

class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters

Body:
In Kotlin we can have that in a single constructor like this

data class User(var name: String, var age: Int = 0, var id: String = "ABC")

If we want to expose getters and not setters, we just provide val instead of var like below,

data class User(val name: String, val age: Int = 0, val id: String = "ABC")

getters/setters visibility modifiers we can provide them in the constructor like this,

data class User(internal val name, internal val age: Int = 0, internal var id: String = "ABC")

In this above case, getter will be accessible only to that module.

We can create object like this,

    var user = User("XYZ")
    var user1 = User("XYZ", 29)
    var user2 = User("XYZ", 29, "AXCVFC")


问:
space issue between Month and date in linux
In my linux system date is having two space between month and date(ex:Jun  4) .so i used date command(ex:date +'%b %_d %H') and stored the value in variable that time i am getting only one space between month and date(ex:Jun 4), so please help me to get the actual system format while using variable. </p>

答:
date is outputting the string you want; I suspect you aren't properly quoting the variable value when you expand it.

```<code>$ d=$(date +'%b %_d %H')
$ echo $d
Jun 6 20
$ echo "$d"
Jun  6 20
</code>```

Body:
date is outputting the string you want; I suspect you aren't properly quoting the variable value when you expand it.

$ d=$(date +'%b %_d %H')
$ echo $d
Jun 6 20
$ echo "$d"
Jun  6 20


问:
TPL Dataflow how to synchronize with "global" data
I'm actually learning about TPL Dataflows. Whenever I read something about it, I think ok sounds great, but then I often ask myself: "Ok, and what if I have kind of a manager, handling different sessions. These sessions can be updated by certain messages. In case of a complex TPL dataflow mesh I've to build-in synchronization mechanism for accessing the manager, which will slow down or block the mesh."

Using a management object for TPL dataflows feels kind of wrong.

Can anybody give me some hints (links, books, examples ...) to the "right" direction, how to solve above example.

答:
Kind of very broad question without some code. But usually you either passing some "state" objects with Tuples or some DTO, which I personally consider as leaking design, or you can inject some blocks into your pipeline.

For example, you can create a WriteOnceBlock with providing it a session value, unique for each pipeline, and simply notifying it's value with new events happened during execution. This may be an option for you if you create a pipeline for different session, but if you have one big pipeline, you need another way.

For example, you have a BufferBlock, an ActionBlock, which performs a session update, and an TransformBlock, which simply continues your normal pipeline execution. The thing you can do in this case is to introduce a BroadcastBlock, link it with action block and transform block. Now you link your buffer to broadcast block with a predicate, and after that you link buffer to transform block directly.

The idea here is that if your message is filtered (so the session update needed), it will go to broadcast block, and, after that, to session update action and to your normal execution pipeline. If it does not match the predicate, it simply go over your normal workflow.

PS: if this is too complicated in words, I can provide some sample code for such scenario.

```<code>var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };

var buffer = new BufferBlock<int>();
// broadcast do copy according lambda from constructor
// if you provide same reference for message, make sure that your access is thread-safe
var broadcast = new BroadcastBlock<int>(i => i);
buffer.LinkTo(broadcast, linkOptions);

// session update block
var sessionUpdate = new ActionBlock<int>(i =>
    {
        Thread.Sleep(new Random().Next(1000));
        Console.WriteLine($"Session update:{i}");
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });
// normal execution
var transform = new TransformBlock<int, int>(i =>
    {
        Thread.Sleep(new Random().Next(1000));
        Console.WriteLine($"Normal execution:{i}");
        return i;
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });
// do not complete the standalone session block
// message will be accepted only for multipliers of 3
broadcast.LinkTo(sessionUpdate, i => i % 3 == 0);
// normal pipeline with completion propagation
broadcast.LinkTo(transform, linkOptions);

for (var i = 0; i < 10; ++i)
{
    // async message
    await buffer.SendAsync(i);
}
buffer.Complete();
await transform.Completion;
</code>```

Body:
Kind of very broad question without some code. But usually you either passing some "state" objects with Tuples or some DTO, which I personally consider as leaking design, or you can inject some blocks into your pipeline.

For example, you can create a WriteOnceBlock with providing it a session value, unique for each pipeline, and simply notifying it's value with new events happened during execution. This may be an option for you if you create a pipeline for different session, but if you have one big pipeline, you need another way.

For example, you have a BufferBlock, an ActionBlock, which performs a session update, and an TransformBlock, which simply continues your normal pipeline execution. The thing you can do in this case is to introduce a BroadcastBlock, link it with action block and transform block. Now you link your buffer to broadcast block with a predicate, and after that you link buffer to transform block directly.

The idea here is that if your message is filtered (so the session update needed), it will go to broadcast block, and, after that, to session update action and to your normal execution pipeline. If it does not match the predicate, it simply go over your normal workflow.

PS: if this is too complicated in words, I can provide some sample code for such scenario.

var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };

var buffer = new BufferBlock<int>();
// broadcast do copy according lambda from constructor
// if you provide same reference for message, make sure that your access is thread-safe
var broadcast = new BroadcastBlock<int>(i => i);
buffer.LinkTo(broadcast, linkOptions);

// session update block
var sessionUpdate = new ActionBlock<int>(i =>
    {
        Thread.Sleep(new Random().Next(1000));
        Console.WriteLine($"Session update:{i}");
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });
// normal execution
var transform = new TransformBlock<int, int>(i =>
    {
        Thread.Sleep(new Random().Next(1000));
        Console.WriteLine($"Normal execution:{i}");
        return i;
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });
// do not complete the standalone session block
// message will be accepted only for multipliers of 3
broadcast.LinkTo(sessionUpdate, i => i % 3 == 0);
// normal pipeline with completion propagation
broadcast.LinkTo(transform, linkOptions);

for (var i = 0; i < 10; ++i)
{
    // async message
    await buffer.SendAsync(i);
}
buffer.Complete();
await transform.Completion;


问:
How to get the URL of a file on AWS S3 using aws-sdk?
I'm using an AWS Lambda function to create a file and save it to my bucket on S3, it is working fine. After executing the putObject method, I get a data object, but it only contains an Etag of the recently added object.

```<code>s3.putObject(params, function(err, data) {
    // data only contains Etag
});
</code>```

I need to know the exact URL that I can use in a browser so the client can see the file. The folder has been already made public and I can see the file if I copy the Link from the S3 console.

I tried using getSignedUrl but the URL it returns is used for other purposes, I believe.

Thanks!

答:
The SDKs do not generally contain a convenience method to create a URL for publicly-readable objects. However, when you called PutObject, you provided the bucket and the object's key and that's all you need. You can simply combine those to make the URL of the object, for example:

https://bucket.s3.amazonaws.com/key

So, for example, if your bucket is pablo and the object key is dogs/toto.png, use:

https://pablo.s3.amazonaws.com/dogs/toto.png

Note that S3 keys do not begin with a / prefix. A key is of the form dogs/toto.png, and not /dogs/toto.png.

For region-specific buckets, see Working with Amazon S3 Buckets and AWS S3 URL Styles. Replace s3 with s3.<region>.amazonaws.com or s3-<region>.amazonaws.com in the above URLs, for example:

https://seamus.s3.eu-west-1.amazonaws.com/dogs/setter.png (with dot)

https://seamus.s3-eu-west-1.amazonaws.com/dogs/setter.png (with dash)

If you are using IPv6, then the general URL form will be:

https://BUCKET.s3.dualstack.REGION.amazonaws.com

For some buckets, you may use the older path-style URLs. Path-style URLs are deprecated and only work with buckets created on or before September 30, 2020. They are used like this:

https://s3.amazonaws.com/bucket/key

https://s3.amazonaws.com/pablo/dogs/toto.png

https://s3.eu-west-1.amazonaws.com/seamus/dogs/setter.png

https://s3.dualstack.REGION.amazonaws.com/BUCKET

Currently there are TLS and SSL certificate issues that may require some buckets with dots (.) in their name to be accessed via path-style URLs. AWS plans to address this. See the AWS announcement.

Note: General guidance on object keys where certain characters need special handling. For example space is encoded to + (plus sign) and plus sign is encoded to %2B. Also here.

Body:
I'm using an AWS Lambda function to create a file and save it to my bucket on S3, it is working fine. After executing the putObject method, I get a data object, but it only contains an Etag of the recently added object.

s3.putObject(params, function(err, data) {
    // data only contains Etag
});

I need to know the exact URL that I can use in a browser so the client can see the file. The folder has been already made public and I can see the file if I copy the Link from the S3 console.

I tried using getSignedUrl but the URL it returns is used for other purposes, I believe.

Thanks!


问:
when a JRadioButton is clicked it will not print out correct
i am trying to make a code that when pressed by he user it will print out correct but instead of printing out correct it just does nothing. i have researched this topic very clearly but i cannot seem to find the right answer if any body can help me it will be greatly appreciated</p>

```<code>import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;

public class JRadioButtonTest
{

  public static void main(String[] args)
  {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JRadioButton Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JRadioButton button1 = new JRadioButton("0.4");
    JRadioButton button2 = new JRadioButton("12");
    JRadioButton button3 = new JRadioButton("37");

    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);

    frame.add(new JLabel("what is the density of a piece of rock that is 40 grams and 25cm3"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);

    if(button2.isSelected()){
      JOptionPane.showMessageDialog(null,"correct");
      }
    }
  }
</code>```

答:
Just a tip to make this easier:

There are some Eclipse Neon packages that allow you to implement a view that will let you enable functions such as that with clicks of a button and allow you to see the project in real time.

help>install package

http://downlods.eclipse.org/releases/neon

Looking through that might be useful to you!

Body:
i am trying to make a code that when pressed by he user it will print out correct but instead of printing out correct it just does nothing. i have researched this topic very clearly but i cannot seem to find the right answer if any body can help me it will be greatly appreciated

import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;

public class JRadioButtonTest
{

  public static void main(String[] args)
  {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JRadioButton Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JRadioButton button1 = new JRadioButton("0.4");
    JRadioButton button2 = new JRadioButton("12");
    JRadioButton button3 = new JRadioButton("37");

    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);

    frame.add(new JLabel("what is the density of a piece of rock that is 40 grams and 25cm3"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);

    if(button2.isSelected()){
      JOptionPane.showMessageDialog(null,"correct");
      }
    }
  }


问:
Updating database without grabbing all the rows
Currently I do a property to property comparison with reflection to determine which values I should update in the database. The problem is that before I can do the comparison of the existing and new value, I need to grab all the rows from the database. These rows are already filtered but can contain thousands of records. As a result, my program is extremely slow and is bottlenecked by all the SELECT LINQ to SQL queries. These select queries take minutes at a time for each to complete.

Example LINQ:

```<code>    List<Customer> customersFromDatabase= _customerRepository
        .List()
        .Where(c=> c.country.Equals(country))
        .ToList();
</code>```

This is the LINQ I use to determine whether they are a new customer or if they exist in which case they would be updated.

```<code>var customerInDb = customersFromDatabase
        .Where(c=> c.id.ToLower() == customer.id.ToLower())
        .FirstOrDefault();
</code>```

Is there a way to filter and grab only specific rows without having to pull the entire dataset down first?

The source data is a CSV file and the target is a database table\

Thanks.

答:
Application side you should be tracking your dirty rows (Ids) and their respective version information. (Row Version # / Last Modified Date/Time) For example if you are displaying a list of editable rows, your application should at a minimum be responsible for tracking which rows have been modified, from there you would retrieve your Customers by ID, validate that their Version information is the same, (someone else hasn't modified the record while your current user was editing) handle the merge, overwrite, or notification if there was a concurrent edit, and then update the source entity based on your property inspection.

So for example if you have 50 rows displayed, as a user edits a row, it gets added to a "dirty" collection. When you go to save the changes, you load Customers /w

given: dirtyCustomerIds = List containing the dirty rows...

```<code>dbContext.Customers.Where(c=> dirtyCustomerIds.Contains(c=>c.CustomerId));
</code>```

and work with your entities against your dirty collection of Customer data from there.

Body:
Currently I do a property to property comparison with reflection to determine which values I should update in the database. The problem is that before I can do the comparison of the existing and new value, I need to grab all the rows from the database. These rows are already filtered but can contain thousands of records. As a result, my program is extremely slow and is bottlenecked by all the SELECT LINQ to SQL queries. These select queries take minutes at a time for each to complete.

Example LINQ:

    List<Customer> customersFromDatabase= _customerRepository
        .List()
        .Where(c=> c.country.Equals(country))
        .ToList();

This is the LINQ I use to determine whether they are a new customer or if they exist in which case they would be updated.

var customerInDb = customersFromDatabase
        .Where(c=> c.id.ToLower() == customer.id.ToLower())
        .FirstOrDefault();

Is there a way to filter and grab only specific rows without having to pull the entire dataset down first?

The source data is a CSV file and the target is a database table\

Thanks.

Body:
Application side you should be tracking your dirty rows (Ids) and their respective version information. (Row Version # / Last Modified Date/Time) For example if you are displaying a list of editable rows, your application should at a minimum be responsible for tracking which rows have been modified, from there you would retrieve your Customers by ID, validate that their Version information is the same, (someone else hasn't modified the record while your current user was editing) handle the merge, overwrite, or notification if there was a concurrent edit, and then update the source entity based on your property inspection.

So for example if you have 50 rows displayed, as a user edits a row, it gets added to a "dirty" collection. When you go to save the changes, you load Customers /w

given: dirtyCustomerIds = List containing the dirty rows...

dbContext.Customers.Where(c=> dirtyCustomerIds.Contains(c=>c.CustomerId));

and work with your entities against your dirty collection of Customer data from there.


问:
Perl script seg faults in Cmenu
I am getting a core dump when I use the Cmenu module on Solaris 8. The script works fine on Solaris 10.  Could somebody please suggest a possible workaround for this? Using dbx shows the following:

```<code>terminated by signal SEGV (no mapping at the fault address)

Current function is Perl_safesysmalloc
92   Ptr = (Malloc_t)PerlMem_malloc(size?size:1)

 Perl_safesysmalloc(size = 4U), line 92 in "util.c"
</code>```

I built version 5.10 of Perl using gcc on this machine. Please let me know if you have need any other information.

答:
That's probably a bug on the module. Send a bug report to the author!

... though, the last release is from 2001, probably not being maintained anymore :-(

Title: Perl script seg faults in Cmenu

Body:
I am getting a core dump when I use the Cmenu module on Solaris 8. The script works fine on Solaris 10.  Could somebody please suggest a possible workaround for this? Using dbx shows the following:

terminated by signal SEGV (no mapping at the fault address)

Current function is Perl_safesysmalloc
92   Ptr = (Malloc_t)PerlMem_malloc(size?size:1)

 Perl_safesysmalloc(size = 4U), line 92 in "util.c"

I built version 5.10 of Perl using gcc on this machine. Please let me know if you have need any other information.


问:
Error when trying to add / remove Authorized JavaScript origins for Google OAuth Client ID
This question is for anyone at Google who might monitor this feed - y'all note that users should ask for support here, since there doesn't seem to be another accessible support channel for the Google API Console.

In the Google APIs Console, when trying to add or remove Authorized JavaScript origins tied to a Client ID for a Web Application, I encounter this error after clicking "Save":

That popup includes a link to "Submit Feedback", which I've done twice without any response from the Google team.

I am an Owner on the project, and have been able to successfully add / remove origins in the past (this issue started last week). Another person on my team - also a project Owner - has been unable to add new origins, as well.

I've tried:

Clearing all Google cookies, and browser cache.

Signing out of the API Console, and signing back in.

Doing this in another browser (Firefox), which also fails to work.

Removing the other person on my team as an Owner, and re-adding his permissions.

I am not logged into any other Google account in this profile of Chrome, or in Firefox.

If anyone has suggestions for how to resolve this, I'd love the help.

Thanks!

答:
This is resolved. Since my app interacts with the Gmail API, given the recent issues on Gmail phishing and Google's improved vetting process, it turns out you can no longer submit changes to Credentials through the Google API Console for apps that request. Google notes on that blog post:

You may see an error message as you’re registering new applications or
  modifying existing application attributes in the Google API Console,
  Firebase Console, or Apps Script editor as a result of this change.

The Google team directed me to this form to submit updates to the OAuth Consent Screen or the Credentials (e.g. changing Authorized Javascript origins).

I hope others who face this issue are able to find this post helpful!


问:
Bind dynamically generated forms for ajax validation?
I am generating many forms on a page dynamically using JS.

Each form corresponds to a yii2 model (which has its rules set up for each attribute).

I would like each form to validate all elements (name, email text inputs) to validate with ajax (as they would normally do as if I only had one form).

I am finding that using the method pointed out here:
https://yii2-cookbook.readthedocs.io/forms-activeform-js/

```<code>`$('#contact-form').yiiActiveForm('validateAttribute', 'contactform-name');`
</code>```

gives JS error:

```<code> yii.activeForm.js:276 Uncaught TypeError: Cannot read property 'attributes' of undefined
    at jQuery.fn.init.find (yii.activeForm.js:276)
    at jQuery.fn.init.validateAttribute (yii.activeForm.js:268)
    at jQuery.fn.init.$.fn.yiiActiveForm (yii.activeForm.js:16)
    at HTMLInputElement.<anonymous> (search-follow.js:130)
</code>```

Is there a way to bind dynamically generated forms to yii2 validation?
(not just individual fields but rather entire forms, each with a unique ID).

The documentation on Yii2 js form validation seems not so much unfortunately

help much appreciated

g

答:
In short you can accomplish modal validation by utilizing the native gii generated activeforms using the following steps:

Create File at Location: app/web/js/ajax-modal-popup.js

```<code>$(function(){
     $(document).on('click', '.showModalButton', function(){
        if ($('#modal').data('bs.modal').isShown) {
            $('#modal').find('#modalContent')
                .load($(this).attr('value'));
            document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
        } else {
            $('#modal').modal('show')
                .find('#modalContent')
                .load($(this).attr('value'));
            document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
        }
    });
});
</code>```

Update File at Location: app/asset/AppAsset.php

```<code>class AppAsset extends AssetBundle {

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    ];
    public $js = [
        'js/ajax-modal-popup.js', //<<<------- Register the script.
    ];
    public $depends = [
        'yii\web\YiiAsset',
    ];

}
</code>```

Add code chunk to file location: app/views/index.php

```<code><?php
    Html::button('Close',
      ['value' => Url::to(['ticket/close', 'id'=>$model->ticket_id]),
      'class' => 'showModalButton btn btn-success']
    );

    Modal::begin([
        'header' => '<h2>Ticket Manager</h2>',
        'id' => 'modal',
        'size' => 'modal-md',
    ]);
    echo "<div id='modalContent'></div>";
    Modal::end();
?>
</code>```

Add to Controller: app/controllers/ticketController.php

```<code>public function actionClose($id) {
    $model = $this->findModel($id);
    $model->scenario = 'close'; //Applied by Ticket model rules.
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        $model->record_void = 1;
        $model->save();
        return $this->redirect(['index']);
    }elseif (Yii::$app->request->isAjax) {
        return $this->renderAjax('close', [
            'model' => $model
        ]);
    } else {
        return $this->render('close', [
            'model' => $model
        ]);
    }
}
</code>```

Your Form File Location: app/views/ticket/close.php

```<code><?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Ticket */
/* @var $form ActiveForm */
?>
<div class="ticket-_close">
<h3>Close Ticket</h3>
<?php
    $form = ActiveForm::begin(['options' => [
        'id' => 'takeModal',
        'enableClientValidation' => true,
        'enableAjaxValidation' => true,
    ]]);?>

        <?= $form->field($model, 'ticket_id')->textInput(['readonly' => true, 'value' => $model->ticket_id]) ?>
        <?= $form->field($model, 'problem') ?>
        <?= $form->field($model, 'solution') ?>

        <div class="form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
        </div>
    <?php ActiveForm::end(); ?>

</div><!-- ticket-_close -->
</code>```

See below article for additional details.

http://www.yiiframework.com/wiki/806/render-form-in-popup-via-ajax-create-and-update-with-ajax-validation-also-load-any-page-via-ajax-yii-2-0-2-3/

Body:
I am generating many forms on a page dynamically using JS.

Each form corresponds to a yii2 model (which has its rules set up for each attribute).

I would like each form to validate all elements (name, email text inputs) to validate with ajax (as they would normally do as if I only had one form).

I am finding that using the method pointed out here:
https://yii2-cookbook.readthedocs.io/forms-activeform-js/

`$('#contact-form').yiiActiveForm('validateAttribute', 'contactform-name');`

gives JS error:

 yii.activeForm.js:276 Uncaught TypeError: Cannot read property 'attributes' of undefined
    at jQuery.fn.init.find (yii.activeForm.js:276)
    at jQuery.fn.init.validateAttribute (yii.activeForm.js:268)
    at jQuery.fn.init.$.fn.yiiActiveForm (yii.activeForm.js:16)
    at HTMLInputElement.<anonymous> (search-follow.js:130)

Is there a way to bind dynamically generated forms to yii2 validation?
(not just individual fields but rather entire forms, each with a unique ID).

The documentation on Yii2 js form validation seems not so much unfortunately

help much appreciated

g

Body:
In short you can accomplish modal validation by utilizing the native gii generated activeforms using the following steps:

Create File at Location: app/web/js/ajax-modal-popup.js

$(function(){
     $(document).on('click', '.showModalButton', function(){
        if ($('#modal').data('bs.modal').isShown) {
            $('#modal').find('#modalContent')
                .load($(this).attr('value'));
            document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
        } else {
            $('#modal').modal('show')
                .find('#modalContent')
                .load($(this).attr('value'));
            document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
        }
    });
});

Update File at Location: app/asset/AppAsset.php

class AppAsset extends AssetBundle {

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    ];
    public $js = [
        'js/ajax-modal-popup.js', //<<<------- Register the script.
    ];
    public $depends = [
        'yii\web\YiiAsset',
    ];

}

Add code chunk to file location: app/views/index.php

<?php
    Html::button('Close',
      ['value' => Url::to(['ticket/close', 'id'=>$model->ticket_id]),
      'class' => 'showModalButton btn btn-success']
    );

    Modal::begin([
        'header' => '<h2>Ticket Manager</h2>',
        'id' => 'modal',
        'size' => 'modal-md',
    ]);
    echo "<div id='modalContent'></div>";
    Modal::end();
?>

Add to Controller: app/controllers/ticketController.php

public function actionClose($id) {
    $model = $this->findModel($id);
    $model->scenario = 'close'; //Applied by Ticket model rules.
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        $model->record_void = 1;
        $model->save();
        return $this->redirect(['index']);
    }elseif (Yii::$app->request->isAjax) {
        return $this->renderAjax('close', [
            'model' => $model
        ]);
    } else {
        return $this->render('close', [
            'model' => $model
        ]);
    }
}

Your Form File Location: app/views/ticket/close.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Ticket */
/* @var $form ActiveForm */
?>
<div class="ticket-_close">
<h3>Close Ticket</h3>
<?php
    $form = ActiveForm::begin(['options' => [
        'id' => 'takeModal',
        'enableClientValidation' => true,
        'enableAjaxValidation' => true,
    ]]);?>

        <?= $form->field($model, 'ticket_id')->textInput(['readonly' => true, 'value' => $model->ticket_id]) ?>
        <?= $form->field($model, 'problem') ?>
        <?= $form->field($model, 'solution') ?>

        <div class="form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
        </div>
    <?php ActiveForm::end(); ?>

</div><!-- ticket-_close -->

See below article for additional details.

http://www.yiiframework.com/wiki/806/render-form-in-popup-via-ajax-create-and-update-with-ajax-validation-also-load-any-page-via-ajax-yii-2-0-2-3/


问:
how can i block the user from downloading paid programs with out paying
I want to build e-commerce website with php and I will use omnipay library for paying. The problem is if the file in the url www.mywebsite.com/programs/paint.exe the user can write in his browser that url and the paid program will download..... I searched how to block user from downloading file like RewriteEngine but how can I let the file download if the user paid in this case?

答:
Maybe you can try these :

Store your program name in hashed format, so instead of www.mywebsite.com/programs/paint.exe maybe it's better in something like this www.mywebsite.com/programs/ca63ff966ff272da14e4fc2e73fcd399. You atleast have store your paid programs in a table and that table should provide its hash formatted name column.

www.mywebsite.com/programs/paint.exe this url should and only accessible by authenticated user. And if it's already authenticated users, you check this user's purchase history, if he/she ever buy this paint.exe program, if there is no record of his/her purchase, you must redirect he/she to your payment page.


问:
Request cURL with ESP8266
I am pretty new to programming (the ESP8266).

Right now I am putting code-pieces from different blogs together in order to receive(!) pushes (messages) from Pushbullet.

Sending already works great thanks to:
POST request on arduino with ESP8266 using WifiESP library

The cURL example from Pushbullet is:

curl --header 'Access-Token: <your_access_token_here>' \
     --header 'Content-Type: application/json' \
     --data-binary '{"body":"Space Elevator, Mars Hyperloop, Space Model S (Model Space?)","title":"Space Travel Ideas","type":"note"}' \
     --request POST \
     https://api.pushbullet.com/v2/pushes
```

<p>And the 'translation' to Arduino/ESP8266:</p>

<pre class="lang-cpp prettyprint-override"><code>String request = String("POST ") + url +" HTTP/1.1\r\n" +
                   "Host: " + push_bullet_host + "\r\n" +
                   "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                   "Accept: */*\r\n" +
                   "Content-Type: application/json\r\n" +
                   "Content-Length: "+ body.length() +"\r\n" +
                   "Access-Token: "+ api_token +"\r\n\r\n" +
                   body;
secure_client.print(req);
</code>```

So what I want to do now is requesting the latest messages from Pushbullet.

The example in cURL is:

curl --header 'Access-Token: <your_access_token_here>' \
     --data-urlencode active="true" \
     --data-urlencode modified_after="1.4e+09" \
     --get \
     https://api.pushbullet.com/v2/pushes
```

<p>And my attempt to get it working is:</p>

<pre class="lang-cpp prettyprint-override"><code>  String request = String("GET ") + url +" HTTP/1.1\r\n" +
                   "Host: " + push_bullet_host + "\r\n" +
                   "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                   "Accept: */*\r\n" +
                   "active=\"true\"\r\n" +
                   "modified_after=\"1496508764\"\r\n" +
                   "Access-Token: "+ api_token +"\r\n\r\n";
  secure_client.print(req);
</code>```

But all I receive is the following:

>>HTTP/1.1 200 OK>>
X-Ratelimit-Reset: 1496515364>>
Content-Type: application/json; charset=utf-8>>
X-Ratelimit-Limit: 16384>>
X-Ratelimit-Remaining: 16384>>
X-Cloud-Trace-Context: blablalba>>
Date: Sat, 03 Jun 2017 18:05:06 GMT>>
Server: Google Frontend>>
Content-Length: 13626>>
```

I really appreciate any idea or solution.

答:
active="true" and modified_after="1496508764" are not valid headers.

You don't even want them in headers, since they are supposed to be query parameters.

You should append those parameters to the URL.

String request = String("GET ") + url +"?active=true&modified_after=1.4e%2B09 HTTP/1.1\r\n" +
                 "Host: " + push_bullet_host + "\r\n" +
                 "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                 "Accept: */*\r\n" +
                 "Access-Token: "+ api_token +"\r\n\r\n";
```

<p>You can see what exactly the <code>curl</code> command sends and receives, if you run it the <code>-v</code> or <code>--verbose</code> option:</p>

```curl --header 'Access-Token: <your_access_token_here>' \
     --data-urlencode active="true" \
     --data-urlencode modified_after="1.4e+09" \
     --get -v\
     https://api.pushbullet.com/v2/pushes
```

<p>With this you would see:</p>

```* ... TLS stuff ...
> GET /v2/pushes?active=true&modified_after=1.4e%2B09 HTTP/1.1
> Host: api.pushbullet.com
> User-Agent: curl/7.42.1
> Accept: */*
> Access-Token: <your_access_token_here>
>
< ... Response headers ...
```

Title: Request cURL with ESP8266

Body:
I am pretty new to programming (the ESP8266).

Right now I am putting code-pieces from different blogs together in order to receive(!) pushes (messages) from Pushbullet.

Sending already works great thanks to:
POST request on arduino with ESP8266 using WifiESP library

The cURL example from Pushbullet is:

curl --header 'Access-Token: <your_access_token_here>' \
     --header 'Content-Type: application/json' \
     --data-binary '{"body":"Space Elevator, Mars Hyperloop, Space Model S (Model Space?)","title":"Space Travel Ideas","type":"note"}' \
     --request POST \
     https://api.pushbullet.com/v2/pushes

And the 'translation' to Arduino/ESP8266:

String request = String("POST ") + url +" HTTP/1.1\r\n" +
                   "Host: " + push_bullet_host + "\r\n" +
                   "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                   "Accept: */*\r\n" +
                   "Content-Type: application/json\r\n" +
                   "Content-Length: "+ body.length() +"\r\n" +
                   "Access-Token: "+ api_token +"\r\n\r\n" +
                   body;
secure_client.print(req);

So what I want to do now is requesting the latest messages from Pushbullet.

The example in cURL is:

curl --header 'Access-Token: <your_access_token_here>' \
     --data-urlencode active="true" \
     --data-urlencode modified_after="1.4e+09" \
     --get \
     https://api.pushbullet.com/v2/pushes

And my attempt to get it working is:

  String request = String("GET ") + url +" HTTP/1.1\r\n" +
                   "Host: " + push_bullet_host + "\r\n" +
                   "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                   "Accept: */*\r\n" +
                   "active=\"true\"\r\n" +
                   "modified_after=\"1496508764\"\r\n" +
                   "Access-Token: "+ api_token +"\r\n\r\n";
  secure_client.print(req);

But all I receive is the following:

>>HTTP/1.1 200 OK>>
X-Ratelimit-Reset: 1496515364>>
Content-Type: application/json; charset=utf-8>>
X-Ratelimit-Limit: 16384>>
X-Ratelimit-Remaining: 16384>>
X-Cloud-Trace-Context: blablalba>>
Date: Sat, 03 Jun 2017 18:05:06 GMT>>
Server: Google Frontend>>
Content-Length: 13626>>

I really appreciate any idea or solution.

Body:
active="true" and modified_after="1496508764" are not valid headers.

You don't even want them in headers, since they are supposed to be query parameters.

You should append those parameters to the URL.

String request = String("GET ") + url +"?active=true&modified_after=1.4e%2B09 HTTP/1.1\r\n" +
                 "Host: " + push_bullet_host + "\r\n" +
                 "User-Agent: ESP8266/NodeMCU 0.9\r\n" +
                 "Accept: */*\r\n" +
                 "Access-Token: "+ api_token +"\r\n\r\n";

You can see what exactly the curl command sends and receives, if you run it the -v or --verbose option:

curl --header 'Access-Token: <your_access_token_here>' \
     --data-urlencode active="true" \
     --data-urlencode modified_after="1.4e+09" \
     --get -v\
     https://api.pushbullet.com/v2/pushes

With this you would see:

* ... TLS stuff ...
> GET /v2/pushes?active=true&modified_after=1.4e%2B09 HTTP/1.1
> Host: api.pushbullet.com
> User-Agent: curl/7.42.1
> Accept: */*
> Access-Token: <your_access_token_here>
>
< ... Response headers ...