问:
Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations
I came across this question:
Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations.

I initially thought of using a min-heap data structure which has O(1) complexity for a get_min(). But push_rear() and pop_front() would be O(log(n)).

Does anyone know what would be the best way to implement such a queue which has O(1) push(), pop() and min()?

I googled about this, and wanted to point out this Algorithm Geeks thread. But it seems that none of the solutions follow constant time rule for all 3 methods: push(), pop() and min().

Thanks for all the suggestions.

答:
Java Implementation
    </p>

```<code>import java.io.*;
import java.util.*;

public class queueMin {
    static class stack {

        private Node<Integer> head;

        public void push(int data) {
            Node<Integer> newNode = new Node<Integer>(data);
            if(null == head) {
                head = newNode;
            } else {
                Node<Integer> prev = head;
                head = newNode;
                head.setNext(prev);
            }
        }

        public int pop() {
            int data = -1;
            if(null == head){
                System.out.println("Error Nothing to pop");
            } else {
                data = head.getData();
                head = head.getNext();
            }

            return data;
        }

        public int peek(){
            if(null == head){
                System.out.println("Error Nothing to pop");
                return -1;
            } else {
                return head.getData();
            }
        }

        public boolean isEmpty(){
            return null == head;
        }
    }

    static class stackMin extends stack {
        private stack s2;

        public stackMin(){
            s2 = new stack();
        }

        public void push(int data){
            if(data <= getMin()){
                s2.push(data);
            }

            super.push(data);
        }

        public int pop(){
            int value = super.pop();
            if(value == getMin()) {
                s2.pop();
            }
            return value;
        }

        public int getMin(){
            if(s2.isEmpty()) {
                return Integer.MAX_VALUE;
            }
            return s2.peek();
        }
    }

     static class Queue {

        private stackMin s1, s2;

        public Queue(){
            s1 = new stackMin();
            s2 = new stackMin();
        }

        public  void enQueue(int data) {
            s1.push(data);
        }

        public  int deQueue() {
            if(s2.isEmpty()) {
                while(!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }

            return s2.pop();
        }

        public int getMin(){
            return Math.min(s1.isEmpty() ? Integer.MAX_VALUE : s1.getMin(), s2.isEmpty() ? Integer.MAX_VALUE : s2.getMin());
        }

    }

   static class Node<T> {
        private T data;
        private T min;
        private Node<T> next;

        public Node(T data){
            this.data = data;
            this.next = null;
        }

        public void setNext(Node<T> next){
            this.next = next;
        }

        public T getData(){
            return this.data;
        }

        public Node<T> getNext(){
            return this.next;
        }

        public void setMin(T min){
            this.min = min;
        }

        public T getMin(){
            return this.min;
        }
    }

    public static void main(String args[]){
       try {
           FastScanner in = newInput();
           PrintWriter out = newOutput();
          // System.out.println(out);
           Queue q = new Queue();
           int t = in.nextInt();
           while(t-- > 0) {
               String[] inp = in.nextLine().split(" ");
               switch (inp[0]) {
                   case "+":
                       q.enQueue(Integer.parseInt(inp[1]));
                       break;
                   case "-":
                       q.deQueue();
                       break;
                   case "?":
                       out.println(q.getMin());
                   default:
                       break;
               }
           }
           out.flush();
           out.close();

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

    static class FastScanner {
        static BufferedReader br;
        static StringTokenizer st;

        FastScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        public FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }
        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDoulbe() {
            return Double.parseDouble(next());
        }
    }

    static FastScanner newInput() throws IOException {
        if (System.getProperty("JUDGE") != null) {
            return new FastScanner(new File("input.txt"));
        } else {
            return new FastScanner(System.in);
        }
    }
    static PrintWriter newOutput() throws IOException {
        if (System.getProperty("JUDGE") != null) {
            return new PrintWriter("output.txt");
        } else {
            return new PrintWriter(System.out);
        }
    }
}
</code>```

Body:
Java Implementation

import java.io.*;
import java.util.*;

public class queueMin {
    static class stack {

        private Node<Integer> head;

        public void push(int data) {
            Node<Integer> newNode = new Node<Integer>(data);
            if(null == head) {
                head = newNode;
            } else {
                Node<Integer> prev = head;
                head = newNode;
                head.setNext(prev);
            }
        }

        public int pop() {
            int data = -1;
            if(null == head){
                System.out.println("Error Nothing to pop");
            } else {
                data = head.getData();
                head = head.getNext();
            }

            return data;
        }

        public int peek(){
            if(null == head){
                System.out.println("Error Nothing to pop");
                return -1;
            } else {
                return head.getData();
            }
        }

        public boolean isEmpty(){
            return null == head;
        }
    }

    static class stackMin extends stack {
        private stack s2;

        public stackMin(){
            s2 = new stack();
        }

        public void push(int data){
            if(data <= getMin()){
                s2.push(data);
            }

            super.push(data);
        }

        public int pop(){
            int value = super.pop();
            if(value == getMin()) {
                s2.pop();
            }
            return value;
        }

        public int getMin(){
            if(s2.isEmpty()) {
                return Integer.MAX_VALUE;
            }
            return s2.peek();
        }
    }

     static class Queue {

        private stackMin s1, s2;

        public Queue(){
            s1 = new stackMin();
            s2 = new stackMin();
        }

        public  void enQueue(int data) {
            s1.push(data);
        }

        public  int deQueue() {
            if(s2.isEmpty()) {
                while(!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }

            return s2.pop();
        }

        public int getMin(){
            return Math.min(s1.isEmpty() ? Integer.MAX_VALUE : s1.getMin(), s2.isEmpty() ? Integer.MAX_VALUE : s2.getMin());
        }

    }

   static class Node<T> {
        private T data;
        private T min;
        private Node<T> next;

        public Node(T data){
            this.data = data;
            this.next = null;
        }

        public void setNext(Node<T> next){
            this.next = next;
        }

        public T getData(){
            return this.data;
        }

        public Node<T> getNext(){
            return this.next;
        }

        public void setMin(T min){
            this.min = min;
        }

        public T getMin(){
            return this.min;
        }
    }

    public static void main(String args[]){
       try {
           FastScanner in = newInput();
           PrintWriter out = newOutput();
          // System.out.println(out);
           Queue q = new Queue();
           int t = in.nextInt();
           while(t-- > 0) {
               String[] inp = in.nextLine().split(" ");
               switch (inp[0]) {
                   case "+":
                       q.enQueue(Integer.parseInt(inp[1]));
                       break;
                   case "-":
                       q.deQueue();
                       break;
                   case "?":
                       out.println(q.getMin());
                   default:
                       break;
               }
           }
           out.flush();
           out.close();

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

    static class FastScanner {
        static BufferedReader br;
        static StringTokenizer st;

        FastScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        public FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }
        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDoulbe() {
            return Double.parseDouble(next());
        }
    }

    static FastScanner newInput() throws IOException {
        if (System.getProperty("JUDGE") != null) {
            return new FastScanner(new File("input.txt"));
        } else {
            return new FastScanner(System.in);
        }
    }
    static PrintWriter newOutput() throws IOException {
        if (System.getProperty("JUDGE") != null) {
            return new PrintWriter("output.txt");
        } else {
            return new PrintWriter(System.out);
        }
    }
}


来源: stackexchange

问:
changing the href of anchor inside ajax return but then it is overwritten
Hello all i have a problem i have a table with a link in one of the columns
on the click of that link i send it to a function that uses ajax to get a different link for it to direct to.
inside the ajax function it is being changed correctly but then after it finishes the ajax it still redirects to the original page.
if i change it outside of the ajax return it works correctly and redirects to a different site

this is my code:

the php function for building the table

```<code>function populate()
{
$link = connectToDB();
$query = 'Select value1, value2
         from table1';
$data = read($query, $link);
$table = '<div id="table"><table id="links">
            <tr>
            <th>value1</th>
            <th>value2</th>
          </tr>';

$num =0;
while ($row = $data->fetch_assoc()) {
    $table .= '<tr>';
    $table .= '<td>' . $row['value1'] . '</td>';
    $table .= '<td><a id="redirection'.$num.'" onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '>' . $row['value1'] .'</td>';
    $table .= '</tr>';
    $num++;
}
$table .= '</table></div>';
mysqli_close($link);
return $table;
}
</code>```

the javascript to change the href

```<code>function redirect(num){
    var url = $("#redirection"+num).attr("href");
    var sub = url.split('?');
    var val1= sub[2];
    var test = "";
    $.ajax({
        url: 'getNewUrl.php',
        type:'POST',
        dataType: 'json',
        data: { name: val1},
        success: function(table){
            alert(table.val2);
            $("#redirection"+num).attr("href",table.val2);
            var check =$("#redirection"+num);
        },
        error: function () {
            alert("No value with that name");
        }
    });
}
</code>```

when i am alerting the value retured it is the correct one, and when i am checking the href value of check in debugger it is being changed correctly but then i am still redirected to the wrong site

thanks for the help

答:
Okay so i as going about this all wrong and just figured it out
instead of changing the href and then having it redirect me to a page
i just used
window.location
to redirect me from inside the ajax
and the href change was redundent

Thanks to all who tried to help me

ContentLicense: CC BY-SA 3.0

Body:
Hello all i have a problem i have a table with a link in one of the columns
on the click of that link i send it to a function that uses ajax to get a different link for it to direct to.
inside the ajax function it is being changed correctly but then after it finishes the ajax it still redirects to the original page.
if i change it outside of the ajax return it works correctly and redirects to a different site

this is my code:

the php function for building the table

function populate()
{
$link = connectToDB();
$query = 'Select value1, value2
         from table1';
$data = read($query, $link);
$table = '

            value1
            value2

';

$num =0;
while ($row = $data->fetch_assoc()) {
    $table .= '
';
    $table .= '' . $row['value1'] . '	';
    $table .= '' . $row['value1'] .'	';
    $table .= '
';
    $num++;
}
$table .= '

';
mysqli_close($link);
return $table;
}

the javascript to change the href

function redirect(num){
    var url = $("#redirection"+num).attr("href");
    var sub = url.split('?');
    var val1= sub[2];
    var test = "";
    $.ajax({
        url: 'getNewUrl.php',
        type:'POST',
        dataType: 'json',
        data: { name: val1},
        success: function(table){
            alert(table.val2);
            $("#redirection"+num).attr("href",table.val2);
            var check =$("#redirection"+num);
        },
        error: function () {
            alert("No value with that name");
        }
    });
}

when i am alerting the value retured it is the correct one, and when i am checking the href value of check in debugger it is being changed correctly but then i am still redirected to the wrong site

thanks for the help


问:
How to insert multiple rows of data from listview to linq to sql VB.Net
i'm a newbie in programming vb.net, I'm making a simple point of sale
I want to insert multiple rows of data from listview to linq to sql, here is the code:

```<code>Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click

    Dim db As New PenjualanDataContext
    For Each item As ListViewItem In ListView1.SelectedItems
        Dim TransaksiBaru As New Transaksi With {.Dibayar = Dibayar.Text, .Faktur = FakturTextBox.Text, .Harga = HargaComboBox.Text, .Jumlah = JumlahTextBox.Text, .Kembali = Kembali.Text, .Kode_Barang = Kode_BarangComboBox.Text, .Nama_Barang = Nama_BarangComboBox.Text, .SubTotal = SubTotalTextBox.Text, .Tanggal = TanggalDateTimePicker.Text, .Total = TotalTextBox.Text}
        db.Transaksis.InsertOnSubmit(TransaksiBaru)
        db.SubmitChanges()
    Next

End Sub
</code>```

I cannot save the data to linq to sql.....

答:
First, it is faster to Submit Changes one time when all record are inserted in the context.

Second, it is recommended to use Using method

Third, you are looping over ListView1.SelectedItems and not using item object returned by the loop. i think that you are missing something in your code

Try modifying your code to the following:

```<code>Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click

    Using db As New PenjualanDataContext

        For Each item As ListViewItem In ListView1.SelectedItems

            Dim TransaksiBaru As New Transaksi With {.Dibayar = Dibayar.Text, .Faktur = FakturTextBox.Text, .Harga = HargaComboBox.Text, .Jumlah = JumlahTextBox.Text, .Kembali = Kembali.Text, .Kode_Barang = Kode_BarangComboBox.Text, .Nama_Barang = Nama_BarangComboBox.Text, .SubTotal = SubTotalTextBox.Text, .Tanggal = TanggalDateTimePicker.Text, .Total = TotalTextBox.Text}

            db.Transaksis.InsertOnSubmit(TransaksiBaru)

        Next

         db.SubmitChanges()

     End Using

End Sub
</code>```

You can refer to the following MSDN article to read more about inserting Rows using Linq-to-SQL

Body:
i'm a newbie in programming vb.net, I'm making a simple point of sale
I want to insert multiple rows of data from listview to linq to sql, here is the code:

Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click

    Dim db As New PenjualanDataContext
    For Each item As ListViewItem In ListView1.SelectedItems
        Dim TransaksiBaru As New Transaksi With {.Dibayar = Dibayar.Text, .Faktur = FakturTextBox.Text, .Harga = HargaComboBox.Text, .Jumlah = JumlahTextBox.Text, .Kembali = Kembali.Text, .Kode_Barang = Kode_BarangComboBox.Text, .Nama_Barang = Nama_BarangComboBox.Text, .SubTotal = SubTotalTextBox.Text, .Tanggal = TanggalDateTimePicker.Text, .Total = TotalTextBox.Text}
        db.Transaksis.InsertOnSubmit(TransaksiBaru)
        db.SubmitChanges()
    Next

End Sub

I cannot save the data to linq to sql.....

Body:
First, it is faster to Submit Changes one time when all record are inserted in the context.

Second, it is recommended to use Using method

Third, you are looping over ListView1.SelectedItems and not using item object returned by the loop. i think that you are missing something in your code

Try modifying your code to the following:

Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click

    Using db As New PenjualanDataContext

        For Each item As ListViewItem In ListView1.SelectedItems

            Dim TransaksiBaru As New Transaksi With {.Dibayar = Dibayar.Text, .Faktur = FakturTextBox.Text, .Harga = HargaComboBox.Text, .Jumlah = JumlahTextBox.Text, .Kembali = Kembali.Text, .Kode_Barang = Kode_BarangComboBox.Text, .Nama_Barang = Nama_BarangComboBox.Text, .SubTotal = SubTotalTextBox.Text, .Tanggal = TanggalDateTimePicker.Text, .Total = TotalTextBox.Text}

            db.Transaksis.InsertOnSubmit(TransaksiBaru)

        Next

         db.SubmitChanges()

     End Using

End Sub

You can refer to the following MSDN article to read more about inserting Rows using Linq-to-SQL


问:
C++ pointer/for-loop confusion
I'm trying to write a program that reads values from cin using a pointer, and then outputs the values alongside their position in the array. I can't figure out why printNumbers1 works but printNumbers2 doesn't. Here is the program (relevant code near the bottom):

```<code>#include <iostream>

using namespace std;

int *readNumbers(int);
void printNumbers1(int*);
void printNumbers2(int*);

int main()
{
    int *numbers = readNumbers(5);
    printNumbers1(numbers);
    printNumbers2(numbers);
    return 0;
}

int *readNumbers(int n)
{
    int a[n];
    int *numbers;
    numbers = &a[0];
    for (int i=0; i<n; i++)
    {
        cin >> *(numbers+i);
    }

    return numbers;
}

void printNumbers1(int *numbers)
{
    cout << 0 << ' ' << *(numbers) << endl
         << 1 << ' ' << *(numbers+1) << endl
         << 2 << ' ' << *(numbers+2) << endl
         << 3 << ' ' << *(numbers+3) << endl
         << 4 << ' ' << *(numbers+4) << endl;
}

void printNumbers2(int *numbers)
{
    for (int i=0; i<5; i++)
    {
        cout << i << ' ' << *(numbers+i) << endl;
    }
}
</code>```

When I run the program, it works as intended for printNumbers1 but outputs a combination of seemingly random numbers and 0s for printNumbers2. I feel like the two printNumbers functions should should function identically, but they don't. What am I missing?

答:
Here you have created the array a[n] inside the function, so it is a local variable, Hence this array may or may not be deleted after the scope of the function ends.Never use the address of a local variable outside the funcrtion. This code is working:</p>

```<code>#include <iostream>

using namespace std;

int *readNumbers(int);
void printNumbers1(int*);
void printNumbers2(int*);

int main()
{
    int *numbers = readNumbers(5);
    printNumbers1(numbers);
    printNumbers2(numbers);
    return 0;
}

int *numbers;

int *readNumbers(int n)
{

    numbers = new int[n];
    for (int i=0; i<n; i++)
    {
         cin >> *(numbers+i);
    }

    return numbers;
}

void printNumbers1(int *numbers)
{
cout << 0 << ' ' << *(numbers) << endl
     << 1 << ' ' << *(numbers+1) << endl
     << 2 << ' ' << *(numbers+2) << endl
     << 3 << ' ' << *(numbers+3) << endl
     << 4 << ' ' << *(numbers+4) << endl;
}

void printNumbers2(int *numbers)
{
for (int i=0; i<5; i++)
{
    cout << i << ' ' << *(numbers+i) << endl;
}
}
</code>```

Title: C++ pointer/for-loop confusion

Body:
I'm trying to write a program that reads values from cin using a pointer, and then outputs the values alongside their position in the array. I can't figure out why printNumbers1 works but printNumbers2 doesn't. Here is the program (relevant code near the bottom):

#include <iostream>

using namespace std;

int *readNumbers(int);
void printNumbers1(int*);
void printNumbers2(int*);

int main()
{
    int *numbers = readNumbers(5);
    printNumbers1(numbers);
    printNumbers2(numbers);
    return 0;
}

int *readNumbers(int n)
{
    int a[n];
    int *numbers;
    numbers = &a[0];
    for (int i=0; i<n; i++)
    {
        cin >> *(numbers+i);
    }

    return numbers;
}

void printNumbers1(int *numbers)
{
    cout << 0 << ' ' << *(numbers) << endl
         << 1 << ' ' << *(numbers+1) << endl
         << 2 << ' ' << *(numbers+2) << endl
         << 3 << ' ' << *(numbers+3) << endl
         << 4 << ' ' << *(numbers+4) << endl;
}

void printNumbers2(int *numbers)
{
    for (int i=0; i<5; i++)
    {
        cout << i << ' ' << *(numbers+i) << endl;
    }
}

When I run the program, it works as intended for printNumbers1 but outputs a combination of seemingly random numbers and 0s for printNumbers2. I feel like the two printNumbers functions should should function identically, but they don't. What am I missing?

Body:
Here you have created the array a[n] inside the function, so it is a local variable, Hence this array may or may not be deleted after the scope of the function ends.Never use the address of a local variable outside the funcrtion. This code is working:

#include <iostream>

using namespace std;

int *readNumbers(int);
void printNumbers1(int*);
void printNumbers2(int*);

int main()
{
    int *numbers = readNumbers(5);
    printNumbers1(numbers);
    printNumbers2(numbers);
    return 0;
}

int *numbers;

int *readNumbers(int n)
{

    numbers = new int[n];
    for (int i=0; i<n; i++)
    {
         cin >> *(numbers+i);
    }

    return numbers;
}

void printNumbers1(int *numbers)
{
cout << 0 << ' ' << *(numbers) << endl
     << 1 << ' ' << *(numbers+1) << endl
     << 2 << ' ' << *(numbers+2) << endl
     << 3 << ' ' << *(numbers+3) << endl
     << 4 << ' ' << *(numbers+4) << endl;
}

void printNumbers2(int *numbers)
{
for (int i=0; i<5; i++)
{
    cout << i << ' ' << *(numbers+i) << endl;
}
}


问:
Minecraft Forge: Can the update emerald be activated by code?
You know that emerald icon that looks like the realms update icon? The one that appears when forge has an update? Does anyone know how to activate this with one's own mod?</p>

答:
Nevermind, found it:
https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate

P.S: Random words to go up to the limit.


问:
ReferenceError: bookshelf is not defined
I am running unit tests  using karma-jasmine, webpact.
I tried to insert a record inside a mysql database using bookshelf.
I received the following error message :

ReferenceError: bookshelf is not defined
        at module.exports.addCategoryWithProducts (app_serv/order/test/order.util.spec.js:94215:2)
        at Object. (app_serv/order/test/order.util.spec.js:94059:3)
        at ContextKarma.loaded (http://localhost:9876/context.js:151:12)
    TypeError: Cannot read property 'then' of undefined
        at Object. (app_serv/order/test/order.util.spec.js:94074:4)

TypeError: _this.driver.createConnection is not a function

My code :

```<code>var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : 'localhost',
    user     : 'user1',
    password : 'toto',
    database : 'totoDb',
    charset  : 'utf8'
  }
});

module.exports = require('bookshelf')(knex);

module.exports.addCategoryWithProducts = function(categoryToAdd) {

  bookshelf.transaction(function(t) {
    var products = categoryToAdd.products;
    var tableProd = [];

    //if (!req.params.idCategory || req.params.idCategory ==0) {
    Category.forge({
      name: categoryToAdd.name,
      code: categoryToAdd.code,
      tax_percentage: categoryToAdd.tax_percentage,
      description: categoryToAdd.description
    })
      .save(null, { transacting: t })
      .then(function(category) {
        for (var i = 0; i < products.length; i++) {
          tableProd.push({
            barcode: products[ i ].barcode,
            cip_13: products[ i ].cip_13,
            category_id: category.id,
            quantity: products[ i ].quantity,
            retail_price: products[ i ].retail_price,
            description: products[ i ].description,
            name: products[ i ].name,
            inn: products[ i ].inn,
            kind: products[ i ].kind,
            comment: products[ i ].comment,
            status: products[ i ].status,
            critical_threshold: products[ i ].critical_threshold,
            max_threshold: products[ i ].max_threshold,
            date_end: products[ i ].date_end
          });
        }

        Products.forge(tableProd)
          .invokeThen('save', null, { transacting: t })
          .then(function(products) {

            //console.log('inside insert of collection '+ JSON.stringify({category : category.toJSON(), produits: products}))
            //res.json({error : false, data: {category : category.toJSON(), products: products}});

            t.commit();

            return Promise.resolve(category.related('products'));
          })
          .catch(function(err) {
            return Promise.reject(err.message);
            //console.log('Erreur dans  Products.forge: ' + err.message);
            res.status(500)
              .json({ error: true, code: err.code, message: err.message });
          })

      })
      .catch(function(err) {
        return Promise.reject(err.message)
        //console.log('Erreur dans  Products.forge: ' + err.message);
        //res.status(500).json({error: true, code : err.code, message: err.message});
      })
  });
}
</code>```

UNIT TEST CODE:

```<code>it("addCategoryWithProducts", function(done){
    addCategoryWithProducts(categoryMock)
        .then(function(catWithPrds){
             expect(catWithPrds).toBeDefined();
             expect(catWithPrds.products).toBeDefined();
             expect(catWithPrds.products.length).toBe(3);
        })

);
</code>```

After trying unsuccessfully many solutions, I decided to ask for your help.

答:
It is not totally clear how your code base works but from TypeError: Cannot read property 'then' of undefined it seems you are not properly returning a promise to the unit test.

try changing

```<code>Products.forge(tableProd)
  .invokeThen('save', null, { transacting: t })
  .then(function(products) {
</code>```

to

```<code>return Products.forge(tableProd)
  .invokeThen('save', null, { transacting: t })
  .then(function(products) {
</code>```

Also you can simplify your promise and transaction handling:

You do not need to call t.commit() explicitly, since it is automatically called by Bookshelf if the promise resolves

You normally do not need to use Promise within another Promise. So instead of return Promise.resolve(category.related('products')) you could just return category.related('products') and instead of return Promise.reject(err.message) just return err.message (but it would be probably better to re-throw)

Body:
I am running unit tests  using karma-jasmine, webpact.
I tried to insert a record inside a mysql database using bookshelf.
I received the following error message :

ReferenceError: bookshelf is not defined
        at module.exports.addCategoryWithProducts (app_serv/order/test/order.util.spec.js:94215:2)
        at Object. (app_serv/order/test/order.util.spec.js:94059:3)
        at ContextKarma.loaded (http://localhost:9876/context.js:151:12)
    TypeError: Cannot read property 'then' of undefined
        at Object. (app_serv/order/test/order.util.spec.js:94074:4)

TypeError: _this.driver.createConnection is not a function

My code :

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : 'localhost',
    user     : 'user1',
    password : 'toto',
    database : 'totoDb',
    charset  : 'utf8'
  }
});

module.exports = require('bookshelf')(knex);

module.exports.addCategoryWithProducts = function(categoryToAdd) {

  bookshelf.transaction(function(t) {
    var products = categoryToAdd.products;
    var tableProd = [];

    //if (!req.params.idCategory || req.params.idCategory ==0) {
    Category.forge({
      name: categoryToAdd.name,
      code: categoryToAdd.code,
      tax_percentage: categoryToAdd.tax_percentage,
      description: categoryToAdd.description
    })
      .save(null, { transacting: t })
      .then(function(category) {
        for (var i = 0; i < products.length; i++) {
          tableProd.push({
            barcode: products[ i ].barcode,
            cip_13: products[ i ].cip_13,
            category_id: category.id,
            quantity: products[ i ].quantity,
            retail_price: products[ i ].retail_price,
            description: products[ i ].description,
            name: products[ i ].name,
            inn: products[ i ].inn,
            kind: products[ i ].kind,
            comment: products[ i ].comment,
            status: products[ i ].status,
            critical_threshold: products[ i ].critical_threshold,
            max_threshold: products[ i ].max_threshold,
            date_end: products[ i ].date_end
          });
        }

        Products.forge(tableProd)
          .invokeThen('save', null, { transacting: t })
          .then(function(products) {

            //console.log('inside insert of collection '+ JSON.stringify({category : category.toJSON(), produits: products}))
            //res.json({error : false, data: {category : category.toJSON(), products: products}});

            t.commit();

            return Promise.resolve(category.related('products'));
          })
          .catch(function(err) {
            return Promise.reject(err.message);
            //console.log('Erreur dans  Products.forge: ' + err.message);
            res.status(500)
              .json({ error: true, code: err.code, message: err.message });
          })

      })
      .catch(function(err) {
        return Promise.reject(err.message)
        //console.log('Erreur dans  Products.forge: ' + err.message);
        //res.status(500).json({error: true, code : err.code, message: err.message});
      })
  });
}

UNIT TEST CODE:

it("addCategoryWithProducts", function(done){
    addCategoryWithProducts(categoryMock)
        .then(function(catWithPrds){
             expect(catWithPrds).toBeDefined();
             expect(catWithPrds.products).toBeDefined();
             expect(catWithPrds.products.length).toBe(3);
        })

);

After trying unsuccessfully many solutions, I decided to ask for your help.

Body:
It is not totally clear how your code base works but from TypeError: Cannot read property 'then' of undefined it seems you are not properly returning a promise to the unit test.

try changing

Products.forge(tableProd)
  .invokeThen('save', null, { transacting: t })
  .then(function(products) {

to

return Products.forge(tableProd)
  .invokeThen('save', null, { transacting: t })
  .then(function(products) {

Also you can simplify your promise and transaction handling:

You do not need to call t.commit() explicitly, since it is automatically called by Bookshelf if the promise resolves

You normally do not need to use Promise within another Promise. So instead of return Promise.resolve(category.related('products')) you could just return category.related('products') and instead of return Promise.reject(err.message) just return err.message (but it would be probably better to re-throw)


问:
Deleting the first child using a push() key in Firebase
I am currently working on an app that strictly uses Firebase for the backend. In my app, I want to delete the first message that was written after 30 messages. In other words, I want to allow only 30 messages to be stored. In my firebase database, I have a node called "users", then a node for the user IDs, then under one of the user IDs, I have another node called items. However, I am wanting to delete the first child under the items node, but I don't know the name of that child since I am using the .push() method to set they key for it. Does anybody know how to only delete that first child?

I know HOW to delete a child in Firebase, I just don't know how to access that one child. I've tried something along the lines of:

```<code>DatabaseReference firstMessage = mDatabase.child("users").child(mUserId).child("items").getRef();
</code>```

Then do this to delete the child.

```<code>firstMessage.removeValue();
</code>```

I know right after the .child("items") that there should be an additional child but how do i get that key?

Edit: I have come up with a solution, but instead of deleting the first child in the items node, it deletes the first child in the users node

```<code>DatabaseReference firstMessage = mDatabase.child("users").child(mUserId).child("items").orderByPriority().limitToFirst(1).getRef();
</code>```

答:
You can try this in your onDataChange,

```<code>for (DataSnapshot p : dataSnapshot.getChildren()) {
    String childKey = p.getKey();
}
</code>```

You can get all the key of all child by this.
you can add them in arraylist or do something else.

If you want to delete some child,
use

```<code>myRef.child("item").child("childKey_0").setValue(null);
</code>```

==================================

EDIT on 3/4/2017:

I cannot get your new question. Just some example on using the arrayList.

```<code>ArrayList<String> childKey_list = new ArrayList<>();

for (DataSnapshot p : dataSnapshot.getChildren()) {
    childKey_list.clear();    //clear the arrayList everytime the firebase refresh
    String childKey = p.getKey();
    childKey_list.add(childKey);
}

If (some_method_of_time) {
    String delete_childID = childKey_list.get(0);
    myRef.child("item").child(delete_childID).setValue(null);
}
</code>```

Body:
I am currently working on an app that strictly uses Firebase for the backend. In my app, I want to delete the first message that was written after 30 messages. In other words, I want to allow only 30 messages to be stored. In my firebase database, I have a node called "users", then a node for the user IDs, then under one of the user IDs, I have another node called items. However, I am wanting to delete the first child under the items node, but I don't know the name of that child since I am using the .push() method to set they key for it. Does anybody know how to only delete that first child?

I know HOW to delete a child in Firebase, I just don't know how to access that one child. I've tried something along the lines of:

DatabaseReference firstMessage = mDatabase.child("users").child(mUserId).child("items").getRef();

Then do this to delete the child.

firstMessage.removeValue();

I know right after the .child("items") that there should be an additional child but how do i get that key?

Edit: I have come up with a solution, but instead of deleting the first child in the items node, it deletes the first child in the users node

DatabaseReference firstMessage = mDatabase.child("users").child(mUserId).child("items").orderByPriority().limitToFirst(1).getRef();

Body:
You can try this in your onDataChange,

for (DataSnapshot p : dataSnapshot.getChildren()) {
    String childKey = p.getKey();
}

You can get all the key of all child by this.
you can add them in arraylist or do something else.

If you want to delete some child,
use

myRef.child("item").child("childKey_0").setValue(null);

==================================

EDIT on 3/4/2017:

I cannot get your new question. Just some example on using the arrayList.

ArrayList<String> childKey_list = new ArrayList<>();

for (DataSnapshot p : dataSnapshot.getChildren()) {
    childKey_list.clear();    //clear the arrayList everytime the firebase refresh
    String childKey = p.getKey();
    childKey_list.add(childKey);
}

If (some_method_of_time) {
    String delete_childID = childKey_list.get(0);
    myRef.child("item").child(delete_childID).setValue(null);
}


问:
How does the current() method works in xslt and what its effects are
How can I understand the current() in xslt 1.0?

Documentation:

xml

```<code><xml>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>
</code>```

xsl

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">
    <!---The effects of using the period vs using current() -->
      <xsl:value-of select="//xml/listitems[@status=current()/@id]" />
  </xsl:template>

  <xsl:template match="listitems">
    <xsl:value-of select="@status"/>
  </xsl:template>

</xsl:stylesheet>
</code>```

I'd be interested in a smaller example that can demo this better.

答:
You are getting both "yes" and "no" in your output not because of the use of . or current(), but because you have two templates in your XSLT that match listitems

```<code><xsl:template match="listitems">
</code>```

This is an error according to the XSLT specification at http://www.w3.org/TR/xslt/#conflict....

It is an error if this [The Conflict Resolution for Template Rules] leaves more than one matching template rule. An
  XSLT processor may signal the error; if it does not signal the error,
  it must recover by choosing, from amongst the matching template rules
  that are left, the one that occurs last in the stylesheet.

In your case, the XSLT processor is simply handing the last template in the stylesheet, which will output both "yes" and "no". If you delete the first template, you would get the same results.

If you want to see a case where . and current() are different, consider this XML

```<code><xml>
  <lists>
      <listitems status="Yes" id="13" />
      <listitems status="No" id="12" />
  </lists>
  <tests>
     <test name="Bob" testid="1" itemid="13" />
     <test name="Kate" testid="2" itemid="12" />
  </tests>
</xml>
</code>```

And this XSLT

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="/*">
      <xsl:apply-templates select="tests" />
  </xsl:template>

  <xsl:template match="test">
    <xsl:value-of select="./@name" />
    <xsl:text> - </xsl:text>
    <!-- In this line, "." and "current()" are the same -->
    <xsl:value-of select="current()/@testid" />
    <xsl:text> - </xsl:text>
    <!-- In this line, they are not the same. Only "current()" will give the result needed -->
    <xsl:value-of select="//xml/lists/listitems[@id = current()/@itemid]/@status" />
  </xsl:template>
</xsl:stylesheet>
</code>```

So, in this line, the current() function is being used in a condition that applies to a node

```<code><xsl:value-of select="//xml/lists/listitems[@id = current()/@itemid]/@status" />
</code>```

current() refers to the current node that was matched by the template; namely test

. refers to the "context" item, which in this case is the listitems element being selected.

ContentLicense: CC BY-SA 4.0

Body:
How can I understand the current() in xslt 1.0?

Documentation:

xml

<xml>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>

xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">

      <xsl:value-of select="//xml/listitems[@status=current()/@id]" />
  </xsl:template>

  <xsl:template match="listitems">
    <xsl:value-of select="@status"/>
  </xsl:template>

</xsl:stylesheet>

I'd be interested in a smaller example that can demo this better.

Body:
You are getting both "yes" and "no" in your output not because of the use of . or current(), but because you have two templates in your XSLT that match listitems

<xsl:template match="listitems">

This is an error according to the XSLT specification at http://www.w3.org/TR/xslt/#conflict....

It is an error if this [The Conflict Resolution for Template Rules] leaves more than one matching template rule. An
  XSLT processor may signal the error; if it does not signal the error,
  it must recover by choosing, from amongst the matching template rules
  that are left, the one that occurs last in the stylesheet.

In your case, the XSLT processor is simply handing the last template in the stylesheet, which will output both "yes" and "no". If you delete the first template, you would get the same results.

If you want to see a case where . and current() are different, consider this XML

<xml>
  <lists>
      <listitems status="Yes" id="13" />
      <listitems status="No" id="12" />
  </lists>
  <tests>
     <test name="Bob" testid="1" itemid="13" />
     <test name="Kate" testid="2" itemid="12" />
  </tests>
</xml>

And this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="/*">
      <xsl:apply-templates select="tests" />
  </xsl:template>

  <xsl:template match="test">
    <xsl:value-of select="./@name" />
    <xsl:text> - </xsl:text>
    <!-- In this line, "." and "current()" are the same -->
    <xsl:value-of select="current()/@testid" />
    <xsl:text> - </xsl:text>
    <!-- In this line, they are not the same. Only "current()" will give the result needed -->
    <xsl:value-of select="//xml/lists/listitems[@id = current()/@itemid]/@status" />
  </xsl:template>
</xsl:stylesheet>

So, in this line, the current() function is being used in a condition that applies to a node

<xsl:value-of select="//xml/lists/listitems[@id = current()/@itemid]/@status" />

current() refers to the current node that was matched by the template; namely test

. refers to the "context" item, which in this case is the listitems element being selected.


问:
How do I aggregate with group by in mysql withou setting sql mode?
This query gets the output I want.  In order to run it I have to run

```<code>SET sql_mode = '';
</code>```

Because otherwise I get an error:

SELECT list is not in GROUP BY clause and contains nonaggregated column 'knownLoss.t1.loss' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

```<code>SELECT
  t1.klDate AS LDate
  , t1.Category
  , t1.reason AS Reason
  , sum(t1.loss) AS Loss
  , round(t1.loss / t2.loss,2) AS Percentage
FROM
  deptkl t1
JOIN (
  SELECT
      Store
    , sum(loss) AS loss
  FROM
    deptkl
  WHERE
    klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
    klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
    Store = 19
AND
    Department = 80
) t2 ON t1.Store = t2.Store

WHERE
  klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
  AND
  klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
  AND
  t1.Store = 19
AND
  Department = 80
GROUP BY
  klDate
, Category
, reason
</code>```

When I place this into the Dataset and Query Dialog of Jasper Studio, I get the same error and I am unable to use the SET sql_mode = ''; command. Any thoughts?  If there is a way to achieve this without using SET sql_mode = '';?

答:
I think you want to do this :

```<code>round(sum(t1.loss / t2.loss)/count(*),2)  AS Percentage
</code>```

this will calculate the sum of the average loss for every records in the result then divide it on the the count of the record of the group it's like average of average.

EDITS:

sorry i made a syntax error now ,it should give the th wanted result and the error is because you are  not using aggregate function on a column that is not in group by clause

Body:
This query gets the output I want.  In order to run it I have to run

SET sql_mode = '';

Because otherwise I get an error:

SELECT list is not in GROUP BY clause and contains nonaggregated column 'knownLoss.t1.loss' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

SELECT
  t1.klDate AS LDate
  , t1.Category
  , t1.reason AS Reason
  , sum(t1.loss) AS Loss
  , round(t1.loss / t2.loss,2) AS Percentage
FROM
  deptkl t1
JOIN (
  SELECT
      Store
    , sum(loss) AS loss
  FROM
    deptkl
  WHERE
    klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
    klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
    Store = 19
AND
    Department = 80
) t2 ON t1.Store = t2.Store

WHERE
  klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
  AND
  klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
  AND
  t1.Store = 19
AND
  Department = 80
GROUP BY
  klDate
, Category
, reason

When I place this into the Dataset and Query Dialog of Jasper Studio, I get the same error and I am unable to use the SET sql_mode = ''; command. Any thoughts?  If there is a way to achieve this without using SET sql_mode = '';?

Body:
I think you want to do this :

round(sum(t1.loss / t2.loss)/count(*),2)  AS Percentage

this will calculate the sum of the average loss for every records in the result then divide it on the the count of the record of the group it's like average of average.

EDITS:

sorry i made a syntax error now ,it should give the th wanted result and the error is because you are  not using aggregate function on a column that is not in group by clause


问:
AJAX/prototype reset call
I have an AJAX / prototype related question. I have an AJAX call currently placed inline, in the onclick (i promise i'll move it out of there :) event, looking like this:

```<code>onclick="var pn = $('yards').value; $('inventory').update('Working...');
new Ajax.Updater('inventory','ajax.php?ac=checkInventory&productID='.$someproductid.'&yards='+pn,{method:'get', evalScripts: true, asynchronous: true, onComplete:function(tr){$('inventory').update(tr.responseText);}});"
</code>```

File called ajax.php then gets the data from $_GET[], displays a small text input field. When filled in and clicked on a submit button, it calls a function which reads the relevant data from the file, and prints a result on the screen. The purpose of all this code is inventory check.

So, when a user clicks on the "get inventory" button with the onclick defined as above, everything works nice, the user fills the yardage, the right result pops up, everybody happy. But what makes it less usable is the fact that in case a user wants to do another inventory check, the entire page needs to be refreshed. If it's not, then when clicking on "get inventory" button, the user will be getting the same result of the last check again, not the text input field.

So, my question is, how do I make that after one inventory check, the whole thing sort of resets itself so that the next time a user clicks on "get inventory" button, he'll be offered to fill the text input field again, and hence get the new result.

I'm sorry if I didn't make myself clear enough. I'm very new to AJAX and prototype, and this is my colleague's work I need to finish...Thanks!

答:
Ah I see,

I don't think Ajax.Updater works like that; have a look at the doc:
http://www.prototypejs.org/api/ajax/updater

```<code>new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items', {
  parameters: { text: $F('text') },
  insertion: Insertion.Bottom
});

var pn = $('yards').value;
    $('inventory').update('Working...');
    new Ajax.Updater('inventory','/ajax.php
,{
     parameters: { ac: 'checkInventory'
                  , productId: /*put productId here*/
                  , yards:/*put yards here too*/
                 }
, method:'get'
, evalScripts: true
, asynchronous: true
, onSuccess:  function(tr){
            //try an alert(tr.repsonseText); just to see what you get back
            $('inventory').update(tr.responseText);
            }
});
</code>```

Things to try:

Clear the text input field before your repopulate it when the onComplete event fires in your ajax.updater call.

Alert the response to make sure your getting a different response from the server.

*Use Fiddler to make sure your passing in a different productId

Change onComplete to onSuccess

Hope this helps

ContentLicense: CC BY-SA 2.5

Title: AJAX/prototype reset call

Body:
I have an AJAX / prototype related question. I have an AJAX call currently placed inline, in the onclick (i promise i'll move it out of there :) event, looking like this:

onclick="var pn = $('yards').value; $('inventory').update('Working...');
new Ajax.Updater('inventory','ajax.php?ac=checkInventory&productID='.$someproductid.'&yards='+pn,{method:'get', evalScripts: true, asynchronous: true, onComplete:function(tr){$('inventory').update(tr.responseText);}});"

File called ajax.php then gets the data from $_GET[], displays a small text input field. When filled in and clicked on a submit button, it calls a function which reads the relevant data from the file, and prints a result on the screen. The purpose of all this code is inventory check.

So, when a user clicks on the "get inventory" button with the onclick defined as above, everything works nice, the user fills the yardage, the right result pops up, everybody happy. But what makes it less usable is the fact that in case a user wants to do another inventory check, the entire page needs to be refreshed. If it's not, then when clicking on "get inventory" button, the user will be getting the same result of the last check again, not the text input field.

So, my question is, how do I make that after one inventory check, the whole thing sort of resets itself so that the next time a user clicks on "get inventory" button, he'll be offered to fill the text input field again, and hence get the new result.

I'm sorry if I didn't make myself clear enough. I'm very new to AJAX and prototype, and this is my colleague's work I need to finish...Thanks!

Body:
Ah I see,

I don't think Ajax.Updater works like that; have a look at the doc:
http://www.prototypejs.org/api/ajax/updater

new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items', {
  parameters: { text: $F('text') },
  insertion: Insertion.Bottom
});

var pn = $('yards').value;
    $('inventory').update('Working...');
    new Ajax.Updater('inventory','/ajax.php
,{
     parameters: { ac: 'checkInventory'
                  , productId: /*put productId here*/
                  , yards:/*put yards here too*/
                 }
, method:'get'
, evalScripts: true
, asynchronous: true
, onSuccess:  function(tr){
            //try an alert(tr.repsonseText); just to see what you get back
            $('inventory').update(tr.responseText);
            }
});

Things to try:

Clear the text input field before your repopulate it when the onComplete event fires in your ajax.updater call.

Alert the response to make sure your getting a different response from the server.

*Use Fiddler to make sure your passing in a different productId

Change onComplete to onSuccess

Hope this helps


问:
Python: command "python -m pip install --upgrade pip" doesn't work
I want to upgrade my pip, but if I type in "python -m pip install --upgrade pip", then my command shell says "cannot find 'python'". Python is already installed and my command shell can't detect the command "python", though.</p>

答:
It depends on which version of python you are using:

```<code>pip3 install --upgrade pip
</code>```

Or:

```<code>python3 -m pip install --upgrade pip
</code>```

Try that as I suspect you are using python 3 which is why it doesn't work.

Body:
It depends on which version of python you are using:

pip3 install --upgrade pip

Or:

python3 -m pip install --upgrade pip

Try that as I suspect you are using python 3 which is why it doesn't work.


问:
Component with local state not updating on React Redux
I'm trying to create a standalone component MultiSelect (I know there are components out there but I want to learn how to do one).

I created it in a way it will store the selected values in its state.

I call it like this from my container:

```<code><MultiSelect
  items={ this.props.boards }
  label="Boards"
  value={ this.props.selectedBoards }
  onChange={ e => this.onChange(e) } />
</code>```

When I dispatch an action I get the correct values for the container's props. My MultiSelect even display the correct options. However for some reason it doesn't update the selected values. In the container this.props.selectedBoards has the correct value, but the component doesn't get this update.

```<code>export default class MultiSelect extends React.Component {
  constructor(props) {
    super(props); // props.items = all options to select

    this.state = {
      selectedItems: props.value || [], // selected options (problem)
      search: '',
      hidden: true,
    };
  }

  render() {
    return (<div>
      ...
      this.state.selectedItems
</code>```

The options to select is on the props (which works) and the selected options is on the state (which doesn't get updated).

How can I make the MultiSelect component update with a new value for selectedItems which is in the state? Or what would be the recommended way to create a component like this?

答:
I end up moving selectedItems from the state to the props, and then on the onChange event where elements get selected I'm getting the value from the props, adding/removing the changed item and calling this.props.onChange with the modified array.

Then on the container I'm dispatching an action with the new array so I can get a new state.

I solved it by delegating the task to keep track of selected items to the container.

MultiSelect:

```<code>export default class MultiSelect extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      search: '',
      hidden: true,
    };
  }

  onChange(item) {
    const selectedItems = [ ...this.props.selectedItems ];

    const index = selectedItems.findIndex(element => element.value === item.value);

    if (index !== -1) {
      selectedItems.splice(index, 1);
    }
    else {
      selectedItems.push(item);
    }

    this.props.onChange(selectedItems); // container
  }

  render() {
    return (<div>
      ...
      this.props.selectedItems
</code>```

Container:

```<code>onChange(data) {
  this.props.dispatch({ type: 'SetSelectedBoards', data });
}

<MultiSelect
  items={ this.props.boards }
  label="Boards"
  selectedItems={ this.props.selectedBoards }
  onChange={ e => this.onChange(e) } />
</code>```

Body:
I'm trying to create a standalone component MultiSelect (I know there are components out there but I want to learn how to do one).

I created it in a way it will store the selected values in its state.

I call it like this from my container:

<MultiSelect
  items={ this.props.boards }
  label="Boards"
  value={ this.props.selectedBoards }
  onChange={ e => this.onChange(e) } />

When I dispatch an action I get the correct values for the container's props. My MultiSelect even display the correct options. However for some reason it doesn't update the selected values. In the container this.props.selectedBoards has the correct value, but the component doesn't get this update.

export default class MultiSelect extends React.Component {
  constructor(props) {
    super(props); // props.items = all options to select

    this.state = {
      selectedItems: props.value || [], // selected options (problem)
      search: '',
      hidden: true,
    };
  }

  render() {
    return (

      ...
      this.state.selectedItems

The options to select is on the props (which works) and the selected options is on the state (which doesn't get updated).

How can I make the MultiSelect component update with a new value for selectedItems which is in the state? Or what would be the recommended way to create a component like this?

Body:
I end up moving selectedItems from the state to the props, and then on the onChange event where elements get selected I'm getting the value from the props, adding/removing the changed item and calling this.props.onChange with the modified array.

Then on the container I'm dispatching an action with the new array so I can get a new state.

I solved it by delegating the task to keep track of selected items to the container.

MultiSelect:

export default class MultiSelect extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      search: '',
      hidden: true,
    };
  }

  onChange(item) {
    const selectedItems = [ ...this.props.selectedItems ];

    const index = selectedItems.findIndex(element => element.value === item.value);

    if (index !== -1) {
      selectedItems.splice(index, 1);
    }
    else {
      selectedItems.push(item);
    }

    this.props.onChange(selectedItems); // container
  }

  render() {
    return (<div>
      ...
      this.props.selectedItems

Container:

onChange(data) {
  this.props.dispatch({ type: 'SetSelectedBoards', data });
}

<MultiSelect
  items={ this.props.boards }
  label="Boards"
  selectedItems={ this.props.selectedBoards }
  onChange={ e => this.onChange(e) } />


问:
Got problems with webhook to Telegram Bot API
Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:

I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn't work (despite it says that webhook was set I do not get any data).

I am making a webhook to my script on my website in this form:

```<code>https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php
</code>```

I get this text in response:

```<code>{"ok":true,"result":true,"description":"Webhook was set"}
</code>```

So it must be working, but it actually doesn't.

Here is my script code:

```<code><?php

ini_set('error_reporting', E_ALL);

$botToken = "<token>";
$website = "https://api.telegram.org/bot".$botToken;

$update = file_get_contents('php://input');
$update = json_decode($update);

print_r($update); // this is made to check if i get any data or not

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

switch ($message) {
    case "/test":
        sendMessage($chatId,"test complete");
        break;
    case "/hi":
        sendMessage($chatId,"hey there");
        break;
    default:
        sendMessage($chatId,"nono i dont understand you");
}

function sendMessage ($chatId, $message) {
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
    file_get_contents($url);
}

?>
</code>```

I don't actually receive any data to $update. So webhook is not working. Why?

答:
This may help who works with Laravel Telegram SDK.
I had a problem with self-signed webhook in Laravel 5.3.
After setup and getting OK result from Telegram with "Webhook was set" message, it didn't work.

The problem was related to CSRF verification. So I added the webhook url to CSRF exceptions and now everything works like a charm.

Body:
Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:

I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn't work (despite it says that webhook was set I do not get any data).

I am making a webhook to my script on my website in this form:

https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php

I get this text in response:

{"ok":true,"result":true,"description":"Webhook was set"}

So it must be working, but it actually doesn't.

Here is my script code:

<?php

ini_set('error_reporting', E_ALL);

$botToken = "<token>";
$website = "https://api.telegram.org/bot".$botToken;

$update = file_get_contents('php://input');
$update = json_decode($update);

print_r($update); // this is made to check if i get any data or not

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

switch ($message) {
    case "/test":
        sendMessage($chatId,"test complete");
        break;
    case "/hi":
        sendMessage($chatId,"hey there");
        break;
    default:
        sendMessage($chatId,"nono i dont understand you");
}

function sendMessage ($chatId, $message) {
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
    file_get_contents($url);
}

?>

I don't actually receive any data to $update. So webhook is not working. Why?


问:
how to make realtime message or character counter in java
In messages apps, as you type a counter label on the corner gets updated showing the number of characters being entered. How do I create the same thing in Java?</p>

答:
Retrieve a IntegerBinding from the TextField's text property containing it's length and convert this to a StringBinding in a way that suits your needs. Bind the text property of the output Label to the result:

```<code>@Override
public void start(Stage primaryStage) {
    TextField textField = new TextField();
    Label label = new Label();
    label.textProperty().bind(textField.textProperty()
                                       .length()
                                       .asString("Character Count: %d"));
    VBox root = new VBox(label, textField);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

Body:
Retrieve a IntegerBinding from the TextField's text property containing it's length and convert this to a StringBinding in a way that suits your needs. Bind the text property of the output Label to the result:

@Override
public void start(Stage primaryStage) {
    TextField textField = new TextField();
    Label label = new Label();
    label.textProperty().bind(textField.textProperty()
                                       .length()
                                       .asString("Character Count: %d"));
    VBox root = new VBox(label, textField);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}


问:
UITableView leaking?
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}
</code>```

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

答:
if self.tableview already exists, you don't want to initialize it again. Either initialize it once (which I'm guessing you already did, maybe by loading from a nib) and then if need be, reset the frame here.

Or just alloc/init the tableview here.

Title: UITableView leaking?

Body:
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?


问:
Arranging different height divs around a circle with a radius
So, I have been trying to create a large number of divs (we can call them bars) and have them rotated and positioned so that it creates a circle in the center. I am bad at explaining so here is an example where all bars have the same width and height.

JSFiddle Here:

Everything looks good here. However, the problem arises when I change the height of the bars. JSFiddle Here:

I assume my troubles arise from my positioning and rotating functions are messed up or the nature of the absolute positioning. Here is an example of my js for the second JSFiddle.

```<code>var $bars = [];
var viz = document.getElementById('viz');

function create(num) {
    for(var i = 0; i < num; i++) {
        var a = document.createElement('div');
        a.classList.add('bar');
        viz.appendChild(a);
        $bars.push($(a));
    }
}

create(256);

$(document).ready(function(){
    var step = Math.PI * 2 / $bars.length;
    var radius = 200;
    var angle = 0;

    for (var i = 0; i < $bars.length; i++) {
        var x = Math.round(radius * Math.cos(angle));
        var y = Math.round(radius * Math.sin(angle));
        $bars[i].css('left', x + 'px');
        $bars[i].css('top', y + 'px');
        $bars[i].css('height', i + 1);
        var rot = 90 + (1.4025 * i);
        $bars[i].css('transform', 'rotate(' + rot + 'deg)');
        angle += step;
    }
});
</code>```

Is there a way to maintain the circle radius with all divs/bars even if the heights are different from my example?
(I am relatively new a js so please forgive my poor code)

答:
I have added

```<code>transform-origin: center top;
</code>```

to your styles. This way, the element grows only in one direction:

fiddle

Body:
So, I have been trying to create a large number of divs (we can call them bars) and have them rotated and positioned so that it creates a circle in the center. I am bad at explaining so here is an example where all bars have the same width and height.

JSFiddle Here:

Everything looks good here. However, the problem arises when I change the height of the bars. JSFiddle Here:

I assume my troubles arise from my positioning and rotating functions are messed up or the nature of the absolute positioning. Here is an example of my js for the second JSFiddle.

var $bars = [];
var viz = document.getElementById('viz');

function create(num) {
    for(var i = 0; i < num; i++) {
        var a = document.createElement('div');
        a.classList.add('bar');
        viz.appendChild(a);
        $bars.push($(a));
    }
}

create(256);

$(document).ready(function(){
    var step = Math.PI * 2 / $bars.length;
    var radius = 200;
    var angle = 0;

    for (var i = 0; i < $bars.length; i++) {
        var x = Math.round(radius * Math.cos(angle));
        var y = Math.round(radius * Math.sin(angle));
        $bars[i].css('left', x + 'px');
        $bars[i].css('top', y + 'px');
        $bars[i].css('height', i + 1);
        var rot = 90 + (1.4025 * i);
        $bars[i].css('transform', 'rotate(' + rot + 'deg)');
        angle += step;
    }
});

Is there a way to maintain the circle radius with all divs/bars even if the heights are different from my example?
(I am relatively new a js so please forgive my poor code)

Body:
I have added

transform-origin: center top;

to your styles. This way, the element grows only in one direction:

fiddle


问:
Nodejs to accept command line argument that contain ( or )
I have made a node application that take any text as argument and my application takes that text and stores that in the database.

When I am giving any text that contain the ( or ) in it then I get an error from bash as

-bash: syntax error near unexpected token `('

How can i accept arguments which contain ( or ) in the text

答:
Quote the argument(s), preferably using single quotes:</p>

```<code>node app.js 'foo ( or ) bar'
</code>```

Body:
Quote the argument(s), preferably using single quotes:

node app.js 'foo ( or ) bar'


问:
Parse string to Array PHP
How to convert this string to array in PHP?

```<code>   "["COLOR","SIZE","TYPE"]"
</code>```

I have read so many answers but they have a different string format  and also I found the eval() but Im not a fan of it. Thanks in advance.

答:
It's an easy way demo link</p>

```<code>$php_value = json_decode('["COLOR","SIZE","TYPE"]');
print_r($php_value);
</code>```

Title: Parse string to Array PHP

Body:
How to convert this string to array in PHP?

   "["COLOR","SIZE","TYPE"]"

I have read so many answers but they have a different string format  and also I found the eval() but Im not a fan of it. Thanks in advance.

Body:
It's an easy way demo link

$php_value = json_decode('["COLOR","SIZE","TYPE"]');
print_r($php_value);


问:
print python dictionary in ruby hash format
I have a simple python dict and it prints in below format,

```<code>{'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}
</code>```

But am looking way to print this in below format like ruby hash,

```<code>{'stats1'=> {'var'=> {'avail'=> 'yes'}, 'target'=> {'avail'=> 'no'}}}
</code>```

I tried Google to get the way to print python dict in ruby hash format but no luck.

答:
I found a simple workaround. if d is the dict

```<code>print(str(d).replace(': ', '=> '))
</code>```

This works given that there is no : anywhere in the strings in the dictionary.

Body:
I have a simple python dict and it prints in below format,

{'stats1': {'var': {'avail': 'yes'}, 'target': {'avail': 'no'}}}

But am looking way to print this in below format like ruby hash,

{'stats1'=> {'var'=> {'avail'=> 'yes'}, 'target'=> {'avail'=> 'no'}}}

I tried Google to get the way to print python dict in ruby hash format but no luck.

Body:
I found a simple workaround. if d is the dict

print(str(d).replace(': ', '=> '))

This works given that there is no : anywhere in the strings in the dictionary.


问:
convert all colors of a pdf file to blue using imagemagick
How can I convert all colors no matter what to blue color using imagemagick? or any other simple and fast solution?

I am out of black ink and want to convert a pdf that is in grayscale to only blue color and then print it.
My printer has limited options.

答:
Not certain of what you mean/expect, but try this:

```<code>convert input.pdf  +level-colors blue, blueResult.pdf
</code>```

It should convert all shades of black to their equivalent shades of blue. So, if you start with this:

you will get this as a result:

If your original document is colour, you may need to desaturate first:

```<code>convert input.pdf -modulate 100,0 +level-colors blue, blueResult.pdf
</code>```

Body:
Not certain of what you mean/expect, but try this:

convert input.pdf  +level-colors blue, blueResult.pdf

It should convert all shades of black to their equivalent shades of blue. So, if you start with this:

you will get this as a result:

If your original document is colour, you may need to desaturate first:

convert input.pdf -modulate 100,0 +level-colors blue, blueResult.pdf


问:
Is it possible to create an application WITHOUT a framework?
I was just thinking. C# has Winforms/WPF, Java has Swing and other frameworks, C++ has QT and so on; is it possible to create an application without using a Framework?

Putting aside the practicality of it, I'm just curious. How would one create an application that Just Works(tm) without needing external frameworks?

答:
Two options come to mind:

Classical Win32 applications written in C. I don't know if standard Windows SDK API also counts as an "external framework" in your book, but that's as low as it gets.

DirectX/OpenGL games written from scratch with your own homebrew framework (not external, right?) There you get to do all the drawing yourself - although again, you use a pretty big library of primitive drawing functions.

If you want even less "framework", you'll have to code your own OS and drivers. :P

OwnerDisplayName: delete


问:
Getting value of internal div when outside div is clicked
I have the following: A bunch of button div's which each have unique info

```<code><div class="button">
  <div id="first">
      Johny
  </div>
  <div id="second">
      Dog
  </div>
  <div id="third">
      Pasta
  </div>
</div>
<div class="button">
  <div id="first">
      Bob
  </div>
  <div id="second">
      Cat
  </div>
  <div id="third">
      Noodles
  </div>
</div>
   .
   .
   .
</code>```

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

```<code>$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});
</code>```

答:
First of all you cannot use same id for multiple elements in a page.So,Instead use class for that.Ex:

```<code><div class="button">
  <div class="first">
      Johny
  </div>
  <div class="second">
      Dog
  </div>
  <div class="third">
      Pasta
  </div>
</div>
<div class="button">
  <div class="first">
      Bob
  </div>
  <div class="second">
      Cat
  </div>
  <div class="third">
      Noodles
  </div>
</div>
</code>```

Now in the javascript:

```<code>$('.button').on('click', function () {
     var first=this.getElementsByClassName("first")[0];//gets first element of this button

var second=this.getElementsByClassName("second")[0];

var third=this.getElementsByClassName("third")[0];

//Now you do what ever you want
});
</code>```

Body:
I have the following: A bunch of button div's which each have unique info

      Johny

      Dog

      Pasta

      Bob

      Cat

      Noodles

   .
   .
   .

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});

Body:
First of all you cannot use same id for multiple elements in a page.So,Instead use class for that.Ex:

<div class="button">
  <div class="first">
      Johny
  </div>
  <div class="second">
      Dog
  </div>
  <div class="third">
      Pasta
  </div>
</div>
<div class="button">
  <div class="first">
      Bob
  </div>
  <div class="second">
      Cat
  </div>
  <div class="third">
      Noodles
  </div>
</div>

Now in the javascript:

$('.button').on('click', function () {
     var first=this.getElementsByClassName("first")[0];//gets first element of this button

var second=this.getElementsByClassName("second")[0];

var third=this.getElementsByClassName("third")[0];

//Now you do what ever you want
});


问:
Firebase Admin Nodejs cannot find module service_account.json
I start my node with "node firebasedb.js". My firebasedb.js contains this code:

```<code>var admin = require("firebase-admin");

var serviceAccount = require("service_account.json");

// Initialize Firebase
var config = {
    credential: admin.credential.cert(serviceAccount),
    apiKey: "<api key>",
    authDomain: "<auth domain>",
    databaseURL: "<database url>",
    storageBucket: "<storage bucket>",
};

admin.initializeApp(config);
</code>```

When I run node, I am in the directory where the .json file exists.
But it says

```<code>Error: Cannot find module 'service_account.json'
</code>```

答:
You are missing the relative portion of the required path. That is, you should doing something like this:

```<code>var serviceAccount = require("./service_account.json");
</code>```

If it's not a relative path, require will be looking in node_modules for a module named service_account.json.

Body:
I start my node with "node firebasedb.js". My firebasedb.js contains this code:

var admin = require("firebase-admin");

var serviceAccount = require("service_account.json");

// Initialize Firebase
var config = {
    credential: admin.credential.cert(serviceAccount),
    apiKey: "<api key>",
    authDomain: "<auth domain>",
    databaseURL: "<database url>",
    storageBucket: "<storage bucket>",
};

admin.initializeApp(config);

When I run node, I am in the directory where the .json file exists.
But it says

Error: Cannot find module 'service_account.json'

Body:
You are missing the relative portion of the required path. That is, you should doing something like this:

var serviceAccount = require("./service_account.json");

If it's not a relative path, require will be looking in node_modules for a module named service_account.json.


问:
How to check github API is unable to connected to github
Is there any way to check from github api that its unable to connect to github or internet is not connected so when i initialize the api by this :

  GitHubApi = require("github");
        github = new GitHubApi({
            version: "3.0.0"
        });

it should tell by handled exception that unable to connect to github or internet not connected to allow me to stop using other operations of this API.
as currently i am getting this exception.

```<code>2//Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:118 [Extension Host] Error: getaddrinfo ENOTFOUND api.github.com api.github.com:443
    at global.sendError (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:783:19)
    at /Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:792:29
    at callCallback (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:667:17)
    at ClientRequest.<anonymous> (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:739:17)
    at emitOne (events.js:90:13)
    at ClientRequest.emit (events.js:182:7)
    at TLSSocket.socketErrorListener (_http_client.js:295:9)
    at emitOne (events.js:90:13)
    at TLSSocket.emit (events.js:182:7)
    at connectErrorNT (net.js:996:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)(anonymous function) @ //Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:118 //Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:93 Error Logged In Console (Help menu > Toggle Developer Tools). You may open an issue using 'Sync : Open Issue' from advance setting command.
</code>```

答:
I have checked an exception to check </p>

```<code> if (error.code == 500) {
            message = "Sync : Internet Not Connected or Unable to Connect to Github. Exception Logged in Console";
            msgBox = false;
        }
</code>```

Body:
Is there any way to check from github api that its unable to connect to github or internet is not connected so when i initialize the api by this :

  GitHubApi = require("github");
        github = new GitHubApi({
            version: "3.0.0"
        });

it should tell by handled exception that unable to connect to github or internet not connected to allow me to stop using other operations of this API.
as currently i am getting this exception.

2//Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:118 [Extension Host] Error: getaddrinfo ENOTFOUND api.github.com api.github.com:443
    at global.sendError (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:783:19)
    at /Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:792:29
    at callCallback (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:667:17)
    at ClientRequest.<anonymous> (/Users/fronteed/.vscode/extensions/Shan.code-settings-sync-2.2.3/node_modules/github/lib/index.js:739:17)
    at emitOne (events.js:90:13)
    at ClientRequest.emit (events.js:182:7)
    at TLSSocket.socketErrorListener (_http_client.js:295:9)
    at emitOne (events.js:90:13)
    at TLSSocket.emit (events.js:182:7)
    at connectErrorNT (net.js:996:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)(anonymous function) @ //Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:118 //Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.main.js:93 Error Logged In Console (Help menu > Toggle Developer Tools). You may open an issue using 'Sync : Open Issue' from advance setting command.

Body:
I have checked an exception to check

 if (error.code == 500) {
            message = "Sync : Internet Not Connected or Unable to Connect to Github. Exception Logged in Console";
            msgBox = false;
        }


问:
How to create a 2d list from a input data?
I was trying this

```<code>n = int(input())
m = int(input())
print(n,m)
for i in range(0,n):
    for j in range(0,m):
        ar[i][j] = int(input())
for i in range(0,n):
    for j in range(0,m):
        print (ar[i][j])
</code>```

But it was showing an error

```<code>Traceback (most recent call last):
  File "C:/Users/shivansh/Desktop/test.py", line 6, in <module>
    ar[i][j] = int(input())
NameError: name 'ar' is not defined
</code>```

I used to do the same in C language but it works. So, how to this in Python?

答:
You haven't declared ar yet. In Python, you don't have to perform separate declaration and initialization; nevertheless, you can't perform operations on names willy-nilly.

Start off with something like this:

```<code>ar = [[0 for j in range(m)] for i in range(n)]
</code>```

Body:
I was trying this

n = int(input())
m = int(input())
print(n,m)
for i in range(0,n):
    for j in range(0,m):
        ar[i][j] = int(input())
for i in range(0,n):
    for j in range(0,m):
        print (ar[i][j])

But it was showing an error

Traceback (most recent call last):
  File "C:/Users/shivansh/Desktop/test.py", line 6, in <module>
    ar[i][j] = int(input())
NameError: name 'ar' is not defined

I used to do the same in C language but it works. So, how to this in Python?

Body:
You haven't declared ar yet. In Python, you don't have to perform separate declaration and initialization; nevertheless, you can't perform operations on names willy-nilly.

Start off with something like this:

ar = [[0 for j in range(m)] for i in range(n)]


问:
Vagrant and PHP "mkdir"
If having some problems with PHPs mkdir function when in a Vagrant box.

What happens is the following, I create a folder:

```<code>mkdir('path/to/directory', 0775, true);
</code>```

This succesfully creates the folder with the following permissions on my Vagrant box:

```<code>drwxrwxr-x 1 www-data vagrant directory
</code>```

and the following on my local machine:

```<code>drwxr-xr-x  3 root staff directory
</code>```

On my local machine however (where I'm actually going to do stuff with the file) I can't edit the files within the folder and PHPStorm shows a lock at the directory.

When I do something like file_put_contents() to create a file and chmod that file to 0664 or 0775  I can edit it.

Any help would be appreciated.

I already tried an extra chmod on the directory, didn't work.

答: Turned out my Vagrant box was build with sudo, hence the directory was from root instead of my own user.</p>

Title: Vagrant and PHP "mkdir"

Body:
If having some problems with PHPs mkdir function when in a Vagrant box.

What happens is the following, I create a folder:

mkdir('path/to/directory', 0775, true);

This succesfully creates the folder with the following permissions on my Vagrant box:

drwxrwxr-x 1 www-data vagrant directory

and the following on my local machine:

drwxr-xr-x  3 root staff directory

On my local machine however (where I'm actually going to do stuff with the file) I can't edit the files within the folder and PHPStorm shows a lock at the directory.

When I do something like file_put_contents() to create a file and chmod that file to 0664 or 0775  I can edit it.

Any help would be appreciated.

I already tried an extra chmod on the directory, didn't work.


问:
How do I view the size of npm packages?
When I search for packages on NPM, I would like to see package sizes (in KB or MB, etc). NPM doesn’t seem to show this information.

How can I determine how much bloat an NPM package will add to my project?

答:
What you probably want to measure is the impact a package has if you were to add it to your app bundle. Most of the other answers will  estimate the size of the source files only, which maybe inaccurate due to inline comments, long var names etc.

There is a small utility I made that'll tell you the min + gzipped size of the package after it gets into you bundle -

https://bundlephobia.com

Title: How do I view the size of npm packages?


问:
ReactJS Require Is Not Working
I am new in reactJS and i can not find why react can not load authorApi using this statement

var AuthorApi = require('../../api/authorApi');

Here is A snips from my project

src/components/authors/author.js code

```<code>'use strict';

var React = require('react');
var AuthorApi = require('../api/authorApi');

var Authors = React.createClass({
  getInitialState: function () {
    return {
      authors: []
    };
  },

  componentWillMount: function () {
    this.setState({ authors: AuthorApi.getAllAuthors() });
  },

  render: function () {
    var createAuthorRow = function (author) {
      return (
        <tr key={author.id}>
          <td>
            <a href={"/#authors/" + author.id}>{author.id}</a>
          </td>
          <td>
            {author.firstName} {author.lastName}
          </td>
        </tr>
      );
    };

    return (
      <div>
        <h1>Authors</h1>
                <table className="table">
                    <thead>
                        <th>ID</th>
                        <th>Name</th>
                    </thead>
                    <tbody>
                        {this.state.authors.map(createAuthorRow, this)}
                    </tbody>
                </table>
            </div>
    );
  }
});

module.exports = Authors;
</code>```

src/api/authorApi.js code

```<code>"use strict";

//This file is mocking a web API by hitting hard coded data.
var authors = require('./authorData').authors;
var _ = require('lodash');

//This would be performed on the server in a real app. Just stubbing in.
var _generateId = function(author) {
    return author.firstName.toLowerCase() + '-' + author.lastName.toLowerCase();
};

var _clone = function(item) {
    return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference
};

var AuthorApi = {
    getAllAuthors: function() {
        return _clone(authors);
    },

    getAuthorById: function(id) {
        var author = _.find(authors, {id: id});
        return _clone(author);
    },

    saveAuthor: function(author) {
        //pretend an ajax call to web api is made here
        console.log('Pretend this just saved the author to the DB via AJAX call...');

        if (author.id) {
            var existingAuthorIndex = _.indexOf(authors, _.find(authors, {id: author.id}));
            authors.splice(existingAuthorIndex, 1, author);
        } else {
            //Just simulating creation here.
            //The server would generate ids for new authors in a real app.
            //Cloning so copy returned is passed by value rather than by reference.
            author.id = _generateId(author);
            authors.push(author);
        }

        return _clone(author);
    },

    deleteAuthor: function(id) {
        console.log('Pretend this just deleted the author from the DB via an AJAX call...');
        _.remove(authors, { id: id});
    }
};
</code>```

and here is src/api/authorData.js code

```<code>module.exports = {
authors:
[
    {
        id: 'cory-house',
        firstName: 'Cory',
        lastName: 'House'
    },
    {
        id: 'scott-allen',
        firstName: 'Scott',
        lastName: 'Allen'
    },
    {
        id: 'dan-wahlin',
        firstName: 'Dan',
        lastName: 'Wahlin'
    }
]
</code>```

};

Error in chrome is :-
  Uncaught TypeError: AuthorApi.getAllAuthors is not a function

答:
You are not exporting your AuthorApi function. Try adding:

module.exports = AuthorApi at the end of authorApi.js file.

Title: ReactJS Require Is Not Working

Body:
I am new in reactJS and i can not find why react can not load authorApi using this statement

var AuthorApi = require('../../api/authorApi');

Here is A snips from my project

src/components/authors/author.js code

'use strict';

var React = require('react');
var AuthorApi = require('../api/authorApi');

var Authors = React.createClass({
  getInitialState: function () {
    return {
      authors: []
    };
  },

  componentWillMount: function () {
    this.setState({ authors: AuthorApi.getAllAuthors() });
  },

  render: function () {
    var createAuthorRow = function (author) {
      return (

            {author.id}

            {author.firstName} {author.lastName}

      );
    };

    return (

Authors

                        ID
                        Name

                        {this.state.authors.map(createAuthorRow, this)}

    );
  }
});

module.exports = Authors;

src/api/authorApi.js code

"use strict";

//This file is mocking a web API by hitting hard coded data.
var authors = require('./authorData').authors;
var _ = require('lodash');

//This would be performed on the server in a real app. Just stubbing in.
var _generateId = function(author) {
    return author.firstName.toLowerCase() + '-' + author.lastName.toLowerCase();
};

var _clone = function(item) {
    return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference
};

var AuthorApi = {
    getAllAuthors: function() {
        return _clone(authors);
    },

    getAuthorById: function(id) {
        var author = _.find(authors, {id: id});
        return _clone(author);
    },

    saveAuthor: function(author) {
        //pretend an ajax call to web api is made here
        console.log('Pretend this just saved the author to the DB via AJAX call...');

        if (author.id) {
            var existingAuthorIndex = _.indexOf(authors, _.find(authors, {id: author.id}));
            authors.splice(existingAuthorIndex, 1, author);
        } else {
            //Just simulating creation here.
            //The server would generate ids for new authors in a real app.
            //Cloning so copy returned is passed by value rather than by reference.
            author.id = _generateId(author);
            authors.push(author);
        }

        return _clone(author);
    },

    deleteAuthor: function(id) {
        console.log('Pretend this just deleted the author from the DB via an AJAX call...');
        _.remove(authors, { id: id});
    }
};

and here is src/api/authorData.js code

module.exports = {
authors:
[
    {
        id: 'cory-house',
        firstName: 'Cory',
        lastName: 'House'
    },
    {
        id: 'scott-allen',
        firstName: 'Scott',
        lastName: 'Allen'
    },
    {
        id: 'dan-wahlin',
        firstName: 'Dan',
        lastName: 'Wahlin'
    }
]

};

Error in chrome is :-
  Uncaught TypeError: AuthorApi.getAllAuthors is not a function


答:
You can initialize matrix in nested loop like this:</p>

```<code>n = int(input()) # columns
m = int(input()) # rows
print(n,m)
matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)
        matrix[i][j] = int(input())
print matrix
</code>```

Title: How to create a 2d list from a input data?

Body:
You can initialize matrix in nested loop like this:

n = int(input()) # columns
m = int(input()) # rows
print(n,m)
matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)
        matrix[i][j] = int(input())
print matrix


问:
AI scripting in Unity. Blocking Y rotation in code
I am creating a game where the world is 3D yet the characters are 2D. This means that my Y rotation must not change or else the 2D sprite rotates. I have a been scripting an AI and while the enemy does attract towards my player, he also rotates by 90 degrees. How can I modify my code to make it so that the sprite follows my player in the X and Z axis but the Y axis rotation stays zero. </p>

<pre class="lang-cs prettyprint-override"><code>//CODE STARTS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AISimple : MonoBehaviour
{
    public Transform player;
    float distancefrom_player;
    public float look_range = 20.0f;
    public float agro_range = 10.0f;
    public float move_speed = 5.0f;
    public float damping = 6.0f;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        distancefrom_player = Vector3.Distance(player.position, transform.position);

        if (distancefrom_player < look_range)
        {
            lookAt();
        }

        if (distancefrom_player < agro_range)

        {
            attack();
        }
    }

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void attack()
    {
        transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
    }

}
</code>```

答:
okay, then try to modify y rotation before you set it</p>

```<code>    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        var euler = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping).eulerAngles;
        euler.y = 0f;

        transform.rotation = Quaternion.Euler(euler);
    }
</code>```

Body:
I am creating a game where the world is 3D yet the characters are 2D. This means that my Y rotation must not change or else the 2D sprite rotates. I have a been scripting an AI and while the enemy does attract towards my player, he also rotates by 90 degrees. How can I modify my code to make it so that the sprite follows my player in the X and Z axis but the Y axis rotation stays zero.

//CODE STARTS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AISimple : MonoBehaviour
{
    public Transform player;
    float distancefrom_player;
    public float look_range = 20.0f;
    public float agro_range = 10.0f;
    public float move_speed = 5.0f;
    public float damping = 6.0f;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        distancefrom_player = Vector3.Distance(player.position, transform.position);

        if (distancefrom_player < look_range)
        {
            lookAt();
        }

        if (distancefrom_player < agro_range)

        {
            attack();
        }
    }

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void attack()
    {
        transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
    }

}

Body:
okay, then try to modify y rotation before you set it

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        var euler = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping).eulerAngles;
        euler.y = 0f;

        transform.rotation = Quaternion.Euler(euler);
    }