答:
If you try to log the style property in Firefox :

```<code>console.log(document.getElementById(id).style);
</code>```

... you'll see that it does not have a background property. Instead, it separates all individual parameters in backgroundColor, backgroundImage, backgroundSize, etc. These split properties exist in all browsers, so you can do:

function onMouseDown(id) {
  var square = document.getElementById(id);

  if (square.style.backgroundColor === "red") {
    square.style.background = "none";
    square.style.color = "black";
  } else {
    square.style.background = "red";
    square.style.color = "white";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="a" onmousedown="onMouseDown('a')">Click me!</button></code>```

Or, as mentioned in the comments, you could use a class, which would be even simpler:

function onMouseDown(id) {
  document.getElementById(id).classList.toggle('red');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red{
  background: red;
  color: white;
}</code>```

<button id="a" onmousedown="onMouseDown('a')">Click me!</button>```

Title: Firefox ignoring document.getElementById(id).style.background?

Body:
If you try to log the style property in Firefox :

console.log(document.getElementById(id).style);

... you'll see that it does not have a background property. Instead, it separates all individual parameters in backgroundColor, backgroundImage, backgroundSize, etc. These split properties exist in all browsers, so you can do:

function onMouseDown(id) {
  var square = document.getElementById(id);

  if (square.style.backgroundColor === "red") {
    square.style.background = "none";
    square.style.color = "black";
  } else {
    square.style.background = "red";
    square.style.color = "white";
  }
}

<button id="a" onmousedown="onMouseDown('a')">Click me!</button>

Or, as mentioned in the comments, you could use a class, which would be even simpler:

function onMouseDown(id) {
  document.getElementById(id).classList.toggle('red');
}

.red{
  background: red;
  color: white;
}

<button id="a" onmousedown="onMouseDown('a')">Click me!</button>


来源: stackexchange

问:
MySQL & PHP: Selecting buyer records by product purchased
I have a somewhat complex MySQL query I'm attempting to derive but I'm just confusing the hell out of myself.

I have several tables: products, stores, buyer, payment and buyer_purchase.

buyer_purchase is basically made up of foreign keys. This table more or less links all the other together. The tables are filled up with junk data. The actual records themselves are not as important as the methods used to retrieve them.

I need to be able to select buyers who have purchased a specific product, how many of that item they've purchased, what store they bought it from, and the payment method used.

It will all be displayed in a webpage using PHP in the following manner:

```<code>Product1
name of buyer1
Payment method
Number Purchased
Store purchased From

product2
Name of buyer1
Payment
Number Purchased
Store Purchased from
Name of buyer2
Payment

etc.
</code>```

I have a query that somewhat works:

```<code>SELECT products.item, stores.seller_name, buyer.f_name, buyer.l_name, payment.company
FROM buyer_purchases
    INNER JOIN products
        ON products.id = buyer_purchases.product_listings_id
    INNER JOIN payment
        ON payment.id = buyer_purchases.buyer_id
    INNER JOIN buyer
        ON buyer.id = buyer_purchases.buyer_id
    INNER JOIN stores
        ON stores.id = buyer_purchases.product_listings_stores_id
    ORDER BY products.item
</code>```

This will return all the data I need in a joined table, but getting it formatted to display as I need is what is confusing me. Obviously, I need to invoke a COUNT to display how many of a given product someone bought, but I'm not sure how to implement it. Further, I think I need GROUP BY rather than ORDER BY, but GROUP BY eliminates all but one record for each product. I've not been able to implement a subquery that MySQL doesn't complain about.

Right now, I'm trying to pull all of the data from the tables in a single query, and store it as a PHP array I can iterate through. If this is not the best way to go about this process, I can find another way.

答:
I guess you just need more experience with MySQL, the trick is in the way you group the elements. In this case you want to group by multiple fields.</p>

```<code>SELECT
    products.item as product,
    concat(buyer.f_name,' ',buyer.l_name) as buyer,
    payment.company as payment,
    count(products.id) as number_purchased
    stores.seller_name as store,
FROM buyer_purchases
    INNER JOIN products
        ON products.id = buyer_purchases.product_listings_id
    INNER JOIN payment
        ON payment.id = buyer_purchases.buyer_id
    INNER JOIN buyer
        ON buyer.id = buyer_purchases.buyer_id
    INNER JOIN stores
        ON stores.id = buyer_purchases.product_listings_stores_id
GROUP BY buyer.id,stores.id,payment.id
ORDER BY products.item
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a somewhat complex MySQL query I'm attempting to derive but I'm just confusing the hell out of myself.

I have several tables: products, stores, buyer, payment and buyer_purchase.

buyer_purchase is basically made up of foreign keys. This table more or less links all the other together. The tables are filled up with junk data. The actual records themselves are not as important as the methods used to retrieve them.

I need to be able to select buyers who have purchased a specific product, how many of that item they've purchased, what store they bought it from, and the payment method used.

It will all be displayed in a webpage using PHP in the following manner:

Product1
name of buyer1
Payment method
Number Purchased
Store purchased From

product2
Name of buyer1
Payment
Number Purchased
Store Purchased from
Name of buyer2
Payment

etc.

I have a query that somewhat works:

SELECT products.item, stores.seller_name, buyer.f_name, buyer.l_name, payment.company
FROM buyer_purchases
    INNER JOIN products
        ON products.id = buyer_purchases.product_listings_id
    INNER JOIN payment
        ON payment.id = buyer_purchases.buyer_id
    INNER JOIN buyer
        ON buyer.id = buyer_purchases.buyer_id
    INNER JOIN stores
        ON stores.id = buyer_purchases.product_listings_stores_id
    ORDER BY products.item

This will return all the data I need in a joined table, but getting it formatted to display as I need is what is confusing me. Obviously, I need to invoke a COUNT to display how many of a given product someone bought, but I'm not sure how to implement it. Further, I think I need GROUP BY rather than ORDER BY, but GROUP BY eliminates all but one record for each product. I've not been able to implement a subquery that MySQL doesn't complain about.

Right now, I'm trying to pull all of the data from the tables in a single query, and store it as a PHP array I can iterate through. If this is not the best way to go about this process, I can find another way.

Body:
I guess you just need more experience with MySQL, the trick is in the way you group the elements. In this case you want to group by multiple fields.

SELECT
    products.item as product,
    concat(buyer.f_name,' ',buyer.l_name) as buyer,
    payment.company as payment,
    count(products.id) as number_purchased
    stores.seller_name as store,
FROM buyer_purchases
    INNER JOIN products
        ON products.id = buyer_purchases.product_listings_id
    INNER JOIN payment
        ON payment.id = buyer_purchases.buyer_id
    INNER JOIN buyer
        ON buyer.id = buyer_purchases.buyer_id
    INNER JOIN stores
        ON stores.id = buyer_purchases.product_listings_stores_id
GROUP BY buyer.id,stores.id,payment.id
ORDER BY products.item


问:
Compilation error - Inversions counting algorithm
I am struggling in my code with an error.

This is the error I got:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

The method recur(Integer[]) in the type D_and_con is not applicable for the arguments (int[])

at edu.uqu.algorithms.inversions.D_and_con.recur(D_and_con.java:27)

  at edu.uqu.algorithms.inversions.MainTest.main(MainTest.java:27)

The code computes the number of inversions.

It is:

```<code>package edu.uqu.algorithms.inversions;

import java.io.FileNotFoundException;
import java.util.Arrays;

import edu.uqu.algorithms.inversions.util.IOUtil;

public class MainTest {

    public static void main(String[] args) {

        try {

            /*//Inversions using BRUTE FORCE
            Integer[] tokens1 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime1 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions BRUTE FORCE..........................");
            System.out.println("Total nb of invertions BRUTE FORCE: " + Inversions.countInvertionsBruteForce(tokens1));
            long runningTime1 = (System.currentTimeMillis() - startTime1);
            System.out.println("BRUTE FORCE Running time: " + runningTime1);
            System.out.println("\n");*/

            //Inversions using DIVIDE & CONQUER
            Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime2 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions DIVIDE & CONQUER..........................");
            System.out.println("MMMMM" + D_and_con.recur(tokens2) );
            long runningTime2 = (System.currentTimeMillis() - startTime2);
            System.out.println("DIVIDE & CONQUER Running time: " + runningTime2);

            System.out.println("----------------------- FINISHED -------------------------");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}
----------------------------------------
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

/**
public class Inversions{

/**
 * Brute force inversions counting method.
 */
public static long countInvertionsBruteForce(Integer[] entries_p)
{
    long result = 0;
    for(int i = 0; i < entries_p.length; i++){
        for(int j = i+1; j < entries_p.length; j++){
            if(entries_p[i] > entries_p[j]) result++;
        }
        //System.out.println("BRUTE FORCE intermediate result for i = " + i + " IS: " + result);
    }
    return result;
}

}
--------------------------
Divide and conquer
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

import java.math.BigDecimal;

public class D_and_con{
    private static BigDecimal totalcount = new BigDecimal(0);
    public static Integer[] recur(Integer[] entries_p)
    {
    int n = entries_p.length;
    if(n == 1)
    {
    return entries_p;
    }
    int middel = n/2;
    int[] Larray = new int[middel];
    int[] Rarray = new int[n - middel];
    System.arraycopy(entries_p , 0 , Larray, 0 , Larray.length );
    System.arraycopy(entries_p , Larray.length , Rarray , 0 , Rarray.length);
    recur(Larray);\\ERROR APPEAR HERE
    recur(Rarray);\\ERROR APPEAR HERE
    comb(Larray , Rarray , entries_p );
    return entries_p;
    }

    private static void comb(int[] Larray, int[] Rarray, Integer[] newarray)
    {
        int LarrayL = Larray.length;
        int RarrayL = Rarray.length;
        int i=0 , j=0 , k=0 ;
        while(i< LarrayL && i<RarrayL)
            {
                if(Larray[i] < Rarray[i] )
                {
                newarray[k] = Larray[i];
                i++;
                }

                else
                {
                    newarray[k] = Rarray[j];
                    i++;
                totalcount = totalcount.add (new BigDecimal(Larray.length - 1));

                }
                k++;
            }
            while(i < LarrayL) {
            newarray[k] = Larray[i];
            i++;
            k++;
          }
          while(j < RarrayL) {
            newarray[k] = Rarray[j];
            j++;
            k++;
          }

    }
}
</code>```

答: Change your Integer[] arrays to int[] arrays!

Body:
I am struggling in my code with an error.

This is the error I got:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

The method recur(Integer[]) in the type D_and_con is not applicable for the arguments (int[])

at edu.uqu.algorithms.inversions.D_and_con.recur(D_and_con.java:27)

  at edu.uqu.algorithms.inversions.MainTest.main(MainTest.java:27)

The code computes the number of inversions.

It is:

package edu.uqu.algorithms.inversions;

import java.io.FileNotFoundException;
import java.util.Arrays;

import edu.uqu.algorithms.inversions.util.IOUtil;

public class MainTest {

    public static void main(String[] args) {

        try {

            /*//Inversions using BRUTE FORCE
            Integer[] tokens1 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime1 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions BRUTE FORCE..........................");
            System.out.println("Total nb of invertions BRUTE FORCE: " + Inversions.countInvertionsBruteForce(tokens1));
            long runningTime1 = (System.currentTimeMillis() - startTime1);
            System.out.println("BRUTE FORCE Running time: " + runningTime1);
            System.out.println("\n");*/

            //Inversions using DIVIDE & CONQUER
            Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime2 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions DIVIDE & CONQUER..........................");
            System.out.println("MMMMM" + D_and_con.recur(tokens2) );
            long runningTime2 = (System.currentTimeMillis() - startTime2);
            System.out.println("DIVIDE & CONQUER Running time: " + runningTime2);

            System.out.println("----------------------- FINISHED -------------------------");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}
----------------------------------------
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

/**
public class Inversions{

/**
 * Brute force inversions counting method.
 */
public static long countInvertionsBruteForce(Integer[] entries_p)
{
    long result = 0;
    for(int i = 0; i < entries_p.length; i++){
        for(int j = i+1; j < entries_p.length; j++){
            if(entries_p[i] > entries_p[j]) result++;
        }
        //System.out.println("BRUTE FORCE intermediate result for i = " + i + " IS: " + result);
    }
    return result;
}

}
--------------------------
Divide and conquer
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

import java.math.BigDecimal;

public class D_and_con{
    private static BigDecimal totalcount = new BigDecimal(0);
    public static Integer[] recur(Integer[] entries_p)
    {
    int n = entries_p.length;
    if(n == 1)
    {
    return entries_p;
    }
    int middel = n/2;
    int[] Larray = new int[middel];
    int[] Rarray = new int[n - middel];
    System.arraycopy(entries_p , 0 , Larray, 0 , Larray.length );
    System.arraycopy(entries_p , Larray.length , Rarray , 0 , Rarray.length);
    recur(Larray);\\ERROR APPEAR HERE
    recur(Rarray);\\ERROR APPEAR HERE
    comb(Larray , Rarray , entries_p );
    return entries_p;
    }

    private static void comb(int[] Larray, int[] Rarray, Integer[] newarray)
    {
        int LarrayL = Larray.length;
        int RarrayL = Rarray.length;
        int i=0 , j=0 , k=0 ;
        while(i< LarrayL && i<RarrayL)
            {
                if(Larray[i] < Rarray[i] )
                {
                newarray[k] = Larray[i];
                i++;
                }

                else
                {
                    newarray[k] = Rarray[j];
                    i++;
                totalcount = totalcount.add (new BigDecimal(Larray.length - 1));

                }
                k++;
            }
            while(i < LarrayL) {
            newarray[k] = Larray[i];
            i++;
            k++;
          }
          while(j < RarrayL) {
            newarray[k] = Rarray[j];
            j++;
            k++;
          }

    }
}


问:
Tp is not defined
im working on a program but it keeps giving the same: name ´Tp´is not defined. here is the programm:

```<code>def sim(N,C,u,Tp,Cm,Temp,ac,yc,ab,aco,yco,ae):
    if u==1:
        T=Temp[0]
        ct=0
        addTemp(Temp)
        newNmol(N)
        idmax=N
        while ct<Tp:
            firstev(c)
            return cond.count()
def addTemp(Temp):
    tT=Tp/len(Temp)
    j=0
    while j<len(Temp):
        t=tT+j*tT
        ev=event(t,"Temperature",0)
        c.addE(ev)
        j=j+1
</code>```

Note that one of simulations arguments is Tp, please help

答:
If you format it like this:

```<code>def sim(N,C,u,Tp,Cm,Temp,ac,yc,ab,aco,yco,ae):

    def addTemp(Temp):
        tT=Tp/len(Temp)
        j=0
        while j<len(Temp):
            t=tT+j*tT
            ev=event(t,"Temperature",0)
            c.addE(ev)
            j=j+1

    if u==1:
        T=Temp[0]
        ct=0
        addTemp(Temp)
        newNmol(N)
        idmax=N
        while ct<Tp:
            firstev(c)
            return cond.count()
</code>```

addTemp is only visible inside sim 's scope and should be able to access the parameters you give to sim. If you need it elsewhere, you need to provice Tp to addTemp and leave its indentation as is.

Title: Tp is not defined

Body:
im working on a program but it keeps giving the same: name ´Tp´is not defined. here is the programm:

def sim(N,C,u,Tp,Cm,Temp,ac,yc,ab,aco,yco,ae):
    if u==1:
        T=Temp[0]
        ct=0
        addTemp(Temp)
        newNmol(N)
        idmax=N
        while ct<Tp:
            firstev(c)
            return cond.count()
def addTemp(Temp):
    tT=Tp/len(Temp)
    j=0
    while j<len(Temp):
        t=tT+j*tT
        ev=event(t,"Temperature",0)
        c.addE(ev)
        j=j+1

Note that one of simulations arguments is Tp, please help

Body:
If you format it like this:

def sim(N,C,u,Tp,Cm,Temp,ac,yc,ab,aco,yco,ae):

    def addTemp(Temp):
        tT=Tp/len(Temp)
        j=0
        while j<len(Temp):
            t=tT+j*tT
            ev=event(t,"Temperature",0)
            c.addE(ev)
            j=j+1

    if u==1:
        T=Temp[0]
        ct=0
        addTemp(Temp)
        newNmol(N)
        idmax=N
        while ct<Tp:
            firstev(c)
            return cond.count()

addTemp is only visible inside sim 's scope and should be able to access the parameters you give to sim. If you need it elsewhere, you need to provice Tp to addTemp and leave its indentation as is.


问:
How to use token authentication while testing REST API
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

```<code>@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200
</code>```

and this is how I use it:

```<code>def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK
</code>```

It gives me 401 error. What is the correct way of using token?

答: The solution is simple and it's because of my inexperience with testing. The test_profile function doesn't register that a token has been asked in the test_authentification function. So I had to put both of them in the SetUp function for the token to be registered for every function in the class. </p>

Body:
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200

and this is how I use it:

def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK

It gives me 401 error. What is the correct way of using token?


问:
Use of getter-setter within class
Should one use under any circumstances getters-setters of a class within the class?</p>

答:
@GolezTrol

There is no PHP badge on topic and you are wrong. What you are describing has nothing to do with setters. You can force type on parameter (in PHP) by using any method not only a setter.

You can write:

```<code>setX( X $x ){ ...}
setY( Y $y ){ ...}
</code>```

or just:

```<code>  iAmMethodNotASetter( X $x, Y $y){

    //20lines of code here end then:

    $this->x = $x;
    $this->y = $y;
  }
</code>```

Like you see I didn't need setters to enforce type in object properties.

And throwing error in setter after checking variable type is bad idea anyway. It is common error of programmers who transitioned from the language statically typed to dynamically type language.

Setters and geters are CONVENTION and  they don't enforce anything!
Today we usually use them for creation of  Plain Old Java Objects. (POJO  - in php word POPO) So it is just a convetion (standard) for creation of object that can by use between libraries or projects.

You can combine setters with type checking or whatever but it dosn't make them somthing more than they are.

About Encapsulation:

@org.life.java - Jigar Joshi

"The main advantage/purpose is
  encapsulation of getter setters, "

@Peter Alexander

"You're supposed to use the getters
  and setter almost everywhere,
  including inside "the class. If you
  don't, then you are potentially
  breaking encapsulation" "Getters and
  setters are encapsulation"

Wrong, wrong, wrong. Encapsulation has nothing to do with getters and setters and it is very common mistake. I know there is many articles repeated it over and over all upside down...

Getters and setters don't help encapsulation even worse, they may break encapsulation. They do so when you use them to get some data from object instead of asking object to do something for you with its own data.

Encapsulation == object is taking full responsibility for its data and dosn't give it's row data. And getter on private property is nothig more than making that property public in complicated fashion == braking encapsulation.

Chceck paragraph encapsulation: http://en.wikipedia.org/wiki/C%2B%2B or http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29
Not even one word about setters or getters...

ContentLicense: CC BY-SA 2.5

Title: Use of getter-setter within class

Body:
@GolezTrol

There is no PHP badge on topic and you are wrong. What you are describing has nothing to do with setters. You can force type on parameter (in PHP) by using any method not only a setter.

You can write:

setX( X $x ){ ...}
setY( Y $y ){ ...}

or just:

  iAmMethodNotASetter( X $x, Y $y){

    //20lines of code here end then:

    $this->x = $x;
    $this->y = $y;
  }

Like you see I didn't need setters to enforce type in object properties.

And throwing error in setter after checking variable type is bad idea anyway. It is common error of programmers who transitioned from the language statically typed to dynamically type language.

Setters and geters are CONVENTION and  they don't enforce anything!
Today we usually use them for creation of  Plain Old Java Objects. (POJO  - in php word POPO) So it is just a convetion (standard) for creation of object that can by use between libraries or projects.

You can combine setters with type checking or whatever but it dosn't make them somthing more than they are.

About Encapsulation:

@org.life.java - Jigar Joshi

"The main advantage/purpose is
  encapsulation of getter setters, "

@Peter Alexander

"You're supposed to use the getters
  and setter almost everywhere,
  including inside "the class. If you
  don't, then you are potentially
  breaking encapsulation" "Getters and
  setters are encapsulation"

Wrong, wrong, wrong. Encapsulation has nothing to do with getters and setters and it is very common mistake. I know there is many articles repeated it over and over all upside down...

Getters and setters don't help encapsulation even worse, they may break encapsulation. They do so when you use them to get some data from object instead of asking object to do something for you with its own data.

Encapsulation == object is taking full responsibility for its data and dosn't give it's row data. And getter on private property is nothig more than making that property public in complicated fashion == braking encapsulation.

Chceck paragraph encapsulation: http://en.wikipedia.org/wiki/C%2B%2B or http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29
Not even one word about setters or getters...


问:
recursive directory listing in java
//The method doesn't run in the console.
I tried to initialize it in main too , but nothing worked
The purpose is to write a recursive method the finds and lists directories and sub directories, and stops when there is no directory.</p>

```<code>package Folders;

import java.io.File;
//lists
//isFile
/**/

public class Main {

    public static void main(String[] args) {
        // Object directoryName;
        // TODO Auto-generated method stub
        // String listFilesAndFilesSubDirectories a = new
        // listFilesAndFilesSubDirectories();
        /*
         * listFilesAndFilesSubDirectories a = new
         * listFilesAndFilesSubDirectories(); System.out.println(); File file1 =
         * new File("C:\\"); String[] files = file1.list(); for(String string :
         * files) { System.out.println(string); }
         */
    }

    public class listFilesAndFilesSubDirectories {
        public void listFilesAndFilesSubDirectories(String directoryName) {
            // directoryName = "C:\\";
            File file1 = new File("C:\\");
            String[] files = file1.list();
            for (String string : files) {
                System.out.println(string);
            }
            File directory = new File(directoryName);

            // get all the files from a directory
            File[] fList = directory.listFiles();
            for (File file : fList) {
                if (file.isFile()) {
                    System.out.println(file.getAbsolutePath());
                    System.out.println("fdadfa");
                } else if (file.isDirectory()) {
                    listFilesAndFilesSubDirectories(file.getAbsolutePath());
                } else {
                    break;
                }
            }
        }
    }
}
</code>```

答:
To recursively print file names inside directories, change your method as per given below: - </p>

```<code>public static void listFilesAndFilesSubDirectories(File directoryName) throws Exception {

    for(File file : directoryName.listFiles()) {
        if(file.isDirectory())
            listFilesAndFilesSubDirectories(file);
        else if(file.isFile())
            System.out.println(file.getName());
    }
}
</code>```

Title: recursive directory listing in java

Body:
//The method doesn't run in the console.
I tried to initialize it in main too , but nothing worked
The purpose is to write a recursive method the finds and lists directories and sub directories, and stops when there is no directory.

package Folders;

import java.io.File;
//lists
//isFile
/**/

public class Main {

    public static void main(String[] args) {
        // Object directoryName;
        // TODO Auto-generated method stub
        // String listFilesAndFilesSubDirectories a = new
        // listFilesAndFilesSubDirectories();
        /*
         * listFilesAndFilesSubDirectories a = new
         * listFilesAndFilesSubDirectories(); System.out.println(); File file1 =
         * new File("C:\\"); String[] files = file1.list(); for(String string :
         * files) { System.out.println(string); }
         */
    }

    public class listFilesAndFilesSubDirectories {
        public void listFilesAndFilesSubDirectories(String directoryName) {
            // directoryName = "C:\\";
            File file1 = new File("C:\\");
            String[] files = file1.list();
            for (String string : files) {
                System.out.println(string);
            }
            File directory = new File(directoryName);

            // get all the files from a directory
            File[] fList = directory.listFiles();
            for (File file : fList) {
                if (file.isFile()) {
                    System.out.println(file.getAbsolutePath());
                    System.out.println("fdadfa");
                } else if (file.isDirectory()) {
                    listFilesAndFilesSubDirectories(file.getAbsolutePath());
                } else {
                    break;
                }
            }
        }
    }
}

Body:
To recursively print file names inside directories, change your method as per given below: -

public static void listFilesAndFilesSubDirectories(File directoryName) throws Exception {

    for(File file : directoryName.listFiles()) {
        if(file.isDirectory())
            listFilesAndFilesSubDirectories(file);
        else if(file.isFile())
            System.out.println(file.getName());
    }
}


问:
centering content of iframe for a content body of a specific width
another Question maybe impossible to answer:
on my webside I have an iframe in a div-container:

div:

```<code><div id='frame'>
    <iframe id='content' name='contentfield' ></iframe>
</div>
</code>```

In the css file there is:

css:

```<code>div#frame{
position:absolute;
display:flex;
background-color:green;(just for my testing)
top:100px;
float:left;
width:calc(100vw - 200px);
height:calc(100vh - 100px);
}
iframe#content{
border:none;
width:100%;
height:100%;
}
</code>```

This iframe shows different sides of my webside, e.g. index.php (many index.php's)
so one is loaded by the javascript:

```<code>function start(id){active = id;
    document.getElementById('content').src='content/hallo/';
}
</code>```

so there is: content/hallo/index.php.
The index.php is a normal html document, but body is set to a specific width in px:

```<code><body style='width:1000px'>
    ...
</body>
</code>```

Now: If the browser window is larger then 1200px(100px from body and 200px from another div, see div#frame) the content of the iframe has the width of 1000px but floated left. I want it to be centered so that if the browser window is 1600px wide the content has a margin-left=margin-right of 200px a.s.o.

Edit:
screenshot that shows the unwished:
darkgray is the menu, light gray the iframe and, as you guess right, the pic i a part of me

答:
I had a similar experience when html5 didn't support the align attribute on the iframe that let you control position. I solved it with display:block and margin:auto on the iframe.

Since you have a width 1000px on the body then that will always pull left (causing everything inside to appear more to the left because it is centered within the body) unless you add margin to that as well to push it into the center.

.frame{
width:100vw;
height:100vh;
min-height:100vh;
}

iframe{
display:block;
margin:auto;
height:100vh;
min-height:100vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='frame'>
    <iframe id='content' name='contentfield' align="center"></iframe>
</div></code>```

Body:
another Question maybe impossible to answer:
on my webside I have an iframe in a div-container:

div:

In the css file there is:

css:

div#frame{
position:absolute;
display:flex;
background-color:green;(just for my testing)
top:100px;
float:left;
width:calc(100vw - 200px);
height:calc(100vh - 100px);
}
iframe#content{
border:none;
width:100%;
height:100%;
}

This iframe shows different sides of my webside, e.g. index.php (many index.php's)
so one is loaded by the javascript:

function start(id){active = id;
    document.getElementById('content').src='content/hallo/';
}

so there is: content/hallo/index.php.
The index.php is a normal html document, but body is set to a specific width in px:

    ...

Now: If the browser window is larger then 1200px(100px from body and 200px from another div, see div#frame) the content of the iframe has the width of 1000px but floated left. I want it to be centered so that if the browser window is 1600px wide the content has a margin-left=margin-right of 200px a.s.o.

Edit:
screenshot that shows the unwished:
darkgray is the menu, light gray the iframe and, as you guess right, the pic i a part of me

Body:
I had a similar experience when html5 didn't support the align attribute on the iframe that let you control position. I solved it with display:block and margin:auto on the iframe.

Since you have a width 1000px on the body then that will always pull left (causing everything inside to appear more to the left because it is centered within the body) unless you add margin to that as well to push it into the center.

.frame{
width:100vw;
height:100vh;
min-height:100vh;
}

iframe{
display:block;
margin:auto;
height:100vh;
min-height:100vh;
}

<div id='frame'>
    <iframe id='content' name='contentfield' align="center"></iframe>
</div>


问:
Haskell: Combinations (list of list)
I have a list of subjects and weekdays, on which the subject is taught.

```<code>subjectDays = [("maths", ["mon", "tue"]),
               ("science", ["mon", "wed"])]
</code>```

Now I would like to generate a list of combinations.
The result should look like as follows.

```<code>combinations = [[("maths", "mon"), ("science", "mon")],
                [("maths", "mon"), ("science", "wed")]
                -- etc.
               ]
</code>```

Could anyone please help me to write a function in Haskell to produce the above result?

Thank you very much in advance.

答:
write an expand function to work on a single pair

```<code>expand :: (a,[b]) -> [(a,b)]
expand (x,[]) = []
expand (x,(y:ys)) = (x,y): expand (x,ys)
</code>```

map to your structure and take the transpose (Data.List)

```<code>transpose $ map expand subjectDays
</code>```

Title: Haskell: Combinations (list of list)

Body:
I have a list of subjects and weekdays, on which the subject is taught.

subjectDays = [("maths", ["mon", "tue"]),
               ("science", ["mon", "wed"])]

Now I would like to generate a list of combinations.
The result should look like as follows.

combinations = [[("maths", "mon"), ("science", "mon")],
                [("maths", "mon"), ("science", "wed")]
                -- etc.
               ]

Could anyone please help me to write a function in Haskell to produce the above result?

Thank you very much in advance.

Body:
write an expand function to work on a single pair

expand :: (a,[b]) -> [(a,b)]
expand (x,[]) = []
expand (x,(y:ys)) = (x,y): expand (x,ys)

map to your structure and take the transpose (Data.List)

transpose $ map expand subjectDays


问:
Toggle mobile navigation and adress data
Sup guys,

for a while now I have been trying to get this to work in jQuery, but I have no idea how to accomplish that.
It's about the mobile navigation of a basic website.
Basically I am trying to achieve that the mobile navigation closes if we click on the 3 dots with the adress data and the other way around. You can see it in this example:

https://www.templatemonster.com/de/demo/62436.html
Choose the mobile version to see what I mean.

Does anyone know how to do this with jQuery or javascript?
Here is what I have currently:

```<code>Adress Data

$('.js--adress-icon').click(function() {
        var kont = $('.js--adress-nav');

        kont.slideToggle(200);
});

Mobile Navigation

var hamburger = $('#hamburger-icon');

hamburger.click(function() {
        var nav = $('.js--main-nav');
        nav.slideToggle(200);
        hamburger.toggleClass('active');
        return false;
});

if ($(window).width() < 768){
        $('.main-navigation li a').on('click', function(){
            $('.js--main-nav').hide();
            $('#hamburger-icon').removeClass('active');
        });
};
</code>```

Thx in advance!

答:
I don't know what your html looks like but this is a simple way to achieve this using css and javascript

```<code><script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</code>```

```<code><nav class="menu">
  <ul class="active">
    <li class="current-item"><a href="#">Home</a></li>
    <li><a href="#">Menu1</a></li>
    <li><a href="#">Menu2</a></li>
  </ul>

  <a class="toggle-nav" href="#">⁝</a>
</nav>
</body>
</code>```

then your javascript

```<code> jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
      jQuery(this).toggleClass('active');
      jQuery('.menu ul').toggleClass('active');

      e.preventDefault();
    });
  });
</code>```

then your css

```<code> /*----- Toggle Button -----*/

  /*----- Menu -----*/
  @media screen and (min-width: 860px) {
    .menu {
      width:100%;
      padding:10px 18px;
      box-shadow:0px 1px 1px rgba(0,0,0,0.15);
      border-radius:3px;
      background:#303030;
    }
  }

  .menu ul {
    display:inline-block;
  }

  .menu li {
    margin:0px 50px 0px 0px;
    float:left;
    list-style:none;
    font-size:17px;
  }

  .menu li:last-child {
    margin-right:0px;
  }

  .menu a {
    text-shadow:0px 1px 0px rgba(0,0,0,0.5);
    color:#777;
    transition:color linear 0.15s;
  }

  .menu a:hover, .menu .current-item a {
    text-decoration:none;
    color:#66a992;
  }
  /*----- Responsive -----*/
  @media screen and (max-width: 1150px) {
    .wrap {
      width:90%;
    }
  }

  @media screen and (max-width: 970px) {
    .search-form input {
      width:120px;
    }
  }

  @media screen and (max-width: 860px) {
    .menu {
      position:relative;
      display:inline-block;
    }

    .menu ul.active {
      display:none;
    }

    .menu ul {
      width:100%;
      position:absolute;
      top:120%;
      left:0px;
      padding:10px 18px;
      box-shadow:0px 1px 1px rgba(0,0,0,0.15);
      border-radius:3px;
      background:#303030;
    }

    .menu ul:after {
      width:0px;
      height:0px;
      position:absolute;
      top:0%;
      left:22px;
      content:'';
      transform:translate(0%, -100%);
      border-left:7px solid transparent;
      border-right:7px solid transparent;
      border-bottom:7px solid #303030;
    }

    .menu li {
      margin:5px 0px 5px 0px;
      float:none;
      display:block;
    }

    .menu a {
      display:block;
    }

    .toggle-nav {
      padding:20px;
      float:left;
      color:#777;
      font-size:20px;
    }

    .toggle-nav:hover, .toggle-nav.active {
      text-decoration:none;
      color:#66a992;
    }
</code>```

}

check this fiddle : https://jsfiddle.net/wggs8pf8/

Body:
Sup guys,

for a while now I have been trying to get this to work in jQuery, but I have no idea how to accomplish that.
It's about the mobile navigation of a basic website.
Basically I am trying to achieve that the mobile navigation closes if we click on the 3 dots with the adress data and the other way around. You can see it in this example:

https://www.templatemonster.com/de/demo/62436.html
Choose the mobile version to see what I mean.

Does anyone know how to do this with jQuery or javascript?
Here is what I have currently:

Adress Data

$('.js--adress-icon').click(function() {
        var kont = $('.js--adress-nav');

        kont.slideToggle(200);
});

Mobile Navigation

var hamburger = $('#hamburger-icon');

hamburger.click(function() {
        var nav = $('.js--main-nav');
        nav.slideToggle(200);
        hamburger.toggleClass('active');
        return false;
});

if ($(window).width() < 768){
        $('.main-navigation li a').on('click', function(){
            $('.js--main-nav').hide();
            $('#hamburger-icon').removeClass('active');
        });
};

Thx in advance!

Body:
I don't know what your html looks like but this is a simple way to achieve this using css and javascript

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>

<nav class="menu">
  <ul class="active">
    <li class="current-item"><a href="#">Home</a></li>
    <li><a href="#">Menu1</a></li>
    <li><a href="#">Menu2</a></li>
  </ul>

  <a class="toggle-nav" href="#">&#8285;</a>
</nav>
</body>

then your javascript

 jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
      jQuery(this).toggleClass('active');
      jQuery('.menu ul').toggleClass('active');

      e.preventDefault();
    });
  });

then your css

 /*----- Toggle Button -----*/

  /*----- Menu -----*/
  @media screen and (min-width: 860px) {
    .menu {
      width:100%;
      padding:10px 18px;
      box-shadow:0px 1px 1px rgba(0,0,0,0.15);
      border-radius:3px;
      background:#303030;
    }
  }

  .menu ul {
    display:inline-block;
  }

  .menu li {
    margin:0px 50px 0px 0px;
    float:left;
    list-style:none;
    font-size:17px;
  }

  .menu li:last-child {
    margin-right:0px;
  }

  .menu a {
    text-shadow:0px 1px 0px rgba(0,0,0,0.5);
    color:#777;
    transition:color linear 0.15s;
  }

  .menu a:hover, .menu .current-item a {
    text-decoration:none;
    color:#66a992;
  }
  /*----- Responsive -----*/
  @media screen and (max-width: 1150px) {
    .wrap {
      width:90%;
    }
  }

  @media screen and (max-width: 970px) {
    .search-form input {
      width:120px;
    }
  }

  @media screen and (max-width: 860px) {
    .menu {
      position:relative;
      display:inline-block;
    }

    .menu ul.active {
      display:none;
    }

    .menu ul {
      width:100%;
      position:absolute;
      top:120%;
      left:0px;
      padding:10px 18px;
      box-shadow:0px 1px 1px rgba(0,0,0,0.15);
      border-radius:3px;
      background:#303030;
    }

    .menu ul:after {
      width:0px;
      height:0px;
      position:absolute;
      top:0%;
      left:22px;
      content:'';
      transform:translate(0%, -100%);
      border-left:7px solid transparent;
      border-right:7px solid transparent;
      border-bottom:7px solid #303030;
    }

    .menu li {
      margin:5px 0px 5px 0px;
      float:none;
      display:block;
    }

    .menu a {
      display:block;
    }

    .toggle-nav {
      padding:20px;
      float:left;
      color:#777;
      font-size:20px;
    }

    .toggle-nav:hover, .toggle-nav.active {
      text-decoration:none;
      color:#66a992;
    }

}

check this fiddle : https://jsfiddle.net/wggs8pf8/


问:
for loop condition in 2nd clause and no condition in 3rd clause
```<code>for(i=5;--i;)
 printf("%d ",i);
</code>```

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?

答:
```<code>for(i=5;--i;)
 printf("%d ",i);
</code>```

Is equivalent to:

```<code>for(i=5; --i; i )
     printf("%d ",i);

for(expression1; expression2; expression3 )
     do_something
</code>```

The for statement evaluates expression2 for value 0 to continue executing do_soemthing  or not. It will continue till expression2 == 0;

Body:
for(i=5;--i;)
 printf("%d ",i);

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?

Body:
for(i=5;--i;)
 printf("%d ",i);

Is equivalent to:

for(i=5; --i; i )
     printf("%d ",i);

for(expression1; expression2; expression3 )
     do_something

The for statement evaluates expression2 for value 0 to continue executing do_soemthing  or not. It will continue till expression2 == 0;


问:
oracle insert statement with blob does not work
Hi I got a db dump from a mysql testdatabase and I want to insert it into an oracle database with the same table structure but I am getting the following error:

```<code>[42000][972] ORA-00972: identifier is too long
</code>```

this is the statement

```<code>INSERT INTO aic.keystore (id, alias, keystore_bytes, password, type, description) VALUES (61, 'test', hextoraw([encoded data, 5421 characters]), '123456', 'PKCS12', null);
</code>```

if I remove the keystore_bytes insertion the insert does complete successfully. So why am I getting an identifier is too long? I haven't any identifiers that exceed 30 characters...

答:
You can have a logic of something like below by using dbms_lob package.

```<code>if($stringlen >= 32000) {
        for(my $i = 1; $i <= int(($querylen/32000) + 0.99); $i++) {
            $temptext = substr($sql, 0 + (32000*($i-1)), 32000);
            $sqltext .= "dbms_lob.append(my_sqltext,'$temptext');" . "\n";
        }
    }
    else {
        $sqltext = "my_sqltext := '$sql';" . "\n";
    }
</code>```

Once you get the lob you can insert by using dbms_lob.write.

Body:
Hi I got a db dump from a mysql testdatabase and I want to insert it into an oracle database with the same table structure but I am getting the following error:

[42000][972] ORA-00972: identifier is too long

this is the statement

INSERT INTO aic.keystore (id, alias, keystore_bytes, password, type, description) VALUES (61, 'test', hextoraw([encoded data, 5421 characters]), '123456', 'PKCS12', null);

if I remove the keystore_bytes insertion the insert does complete successfully. So why am I getting an identifier is too long? I haven't any identifiers that exceed 30 characters...

Body:
You can have a logic of something like below by using dbms_lob package.

if($stringlen >= 32000) {
        for(my $i = 1; $i <= int(($querylen/32000) + 0.99); $i++) {
            $temptext = substr($sql, 0 + (32000*($i-1)), 32000);
            $sqltext .= "dbms_lob.append(my_sqltext,'$temptext');" . "\n";
        }
    }
    else {
        $sqltext = "my_sqltext := '$sql';" . "\n";
    }

Once you get the lob you can insert by using dbms_lob.write.


问:
Simulator iPhone Retina has wrong screen resolution
I'm trying to write a Universal Application.  The display should be slightly different for different screen resolutions.  But when I code like this:

```<code>- (void)viewDidLoad {
    SCREEN_WIDTH=[[UIScreen mainScreen] applicationFrame].size.width;
    SCREEN_HEIGHT=[[UIScreen mainScreen] applicationFrame].size.height;
    NSLog(@"w:%f h:%f",SCREEN_WIDTH,SCREEN_HEIGHT);
...
}
</code>```

I get output: w:320.000000 h:480.000000 even when the simulator is set to

Hardware->Device->iPhone (Retina)

Furthermore, images with this resolution display as full-screen images in the simulator.

I understand I should be getting w:640.000000 h:960.000000.

Is it like this for anyone else? And any ideas why/how to fix?
See the related thread: here

答:
Did you rename the images as img.png@2x? And you should enable retina display in your code.

Even if you set simulator to retina display BUT the code is not retina display enabled, the graphics displayed out would be 320x480.

Body:
I'm trying to write a Universal Application.  The display should be slightly different for different screen resolutions.  But when I code like this:

- (void)viewDidLoad {
    SCREEN_WIDTH=[[UIScreen mainScreen] applicationFrame].size.width;
    SCREEN_HEIGHT=[[UIScreen mainScreen] applicationFrame].size.height;
    NSLog(@"w:%f h:%f",SCREEN_WIDTH,SCREEN_HEIGHT);
...
}

I get output: w:320.000000 h:480.000000 even when the simulator is set to

Hardware->Device->iPhone (Retina)

Furthermore, images with this resolution display as full-screen images in the simulator.

I understand I should be getting w:640.000000 h:960.000000.

Is it like this for anyone else? And any ideas why/how to fix?
See the related thread: here


答: You can have multiple ORDER BY clauses which work in order, so looks like you want ORDER BY products.item, buyer.id which will list all records for item 1 first, ordered by customer, then all records for item 2 ordered by cutomer etc

Title: MySQL & PHP: Selecting buyer records by product purchased

Body:
I have a somewhat complex MySQL query I'm attempting to derive but I'm just confusing the hell out of myself.

I have several tables: products, stores, buyer, payment and buyer_purchase.

buyer_purchase is basically made up of foreign keys. This table more or less links all the other together. The tables are filled up with junk data. The actual records themselves are not as important as the methods used to retrieve them.

I need to be able to select buyers who have purchased a specific product, how many of that item they've purchased, what store they bought it from, and the payment method used.

It will all be displayed in a webpage using PHP in the following manner:

Product1
name of buyer1
Payment method
Number Purchased
Store purchased From

product2
Name of buyer1
Payment
Number Purchased
Store Purchased from
Name of buyer2
Payment

etc.

I have a query that somewhat works:

SELECT products.item, stores.seller_name, buyer.f_name, buyer.l_name, payment.company
FROM buyer_purchases
    INNER JOIN products
        ON products.id = buyer_purchases.product_listings_id
    INNER JOIN payment
        ON payment.id = buyer_purchases.buyer_id
    INNER JOIN buyer
        ON buyer.id = buyer_purchases.buyer_id
    INNER JOIN stores
        ON stores.id = buyer_purchases.product_listings_stores_id
    ORDER BY products.item

This will return all the data I need in a joined table, but getting it formatted to display as I need is what is confusing me. Obviously, I need to invoke a COUNT to display how many of a given product someone bought, but I'm not sure how to implement it. Further, I think I need GROUP BY rather than ORDER BY, but GROUP BY eliminates all but one record for each product. I've not been able to implement a subquery that MySQL doesn't complain about.

Right now, I'm trying to pull all of the data from the tables in a single query, and store it as a PHP array I can iterate through. If this is not the best way to go about this process, I can find another way.


问:
How can I customize error messages of Cerberus?
I want to localize the error messages Cerberus returns, e.g. I'd like to achieve the following:</p>

```<code>>>> validator.schema = {'animal': {'forbidden': ['Einhorn']}}
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}  # instead of 'unallowed value Einhorn'
</code>```

答:
You can simply subclass the default error handler BasicErrorhandler from the cerberus.errors module and adjust the message templates as you like:

```<code>>>> class CustomErrorHandler(errors.BasicErrorHandler):
...     messages = errors.BasicErrorHandler.messages.copy()
...     messages[errors.FORBIDDEN_VALUE.code] = 'VERBOTEN!'
...
>>> validator = Validator(schema, error_handler=CustomErrorHandler)
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}
</code>```

Have a look at the source code for available error codes and template variables.

Body:
I want to localize the error messages Cerberus returns, e.g. I'd like to achieve the following:

>>> validator.schema = {'animal': {'forbidden': ['Einhorn']}}
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}  # instead of 'unallowed value Einhorn'

Body:
You can simply subclass the default error handler BasicErrorhandler from the cerberus.errors module and adjust the message templates as you like:

>>> class CustomErrorHandler(errors.BasicErrorHandler):
...     messages = errors.BasicErrorHandler.messages.copy()
...     messages[errors.FORBIDDEN_VALUE.code] = 'VERBOTEN!'
...
>>> validator = Validator(schema, error_handler=CustomErrorHandler)
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}

Have a look at the source code for available error codes and template variables.


问:
.ts files always get recognized as text/vnd.trolltech.linguist and never as video/mp2t
I am streaming some HTTP Live Stream from Red Hat Enterprise Linux Server release 6.3. At the client side, when i do the Wireshark trace, i always get the video file ts as text/vnd.trolltech.linguist and never as video/mp2t.

IF i stream the same content with the Windows IIS server, i get the video/mp2t.

I am not if there is any requirement of changing the Apache MIME configuration so it streams the correct data type?

Can anyone suggest some quick-fix for the same?

I have found that some patch has been released for Ubuntu for this issue but i don't see anything for RHEL.

答:
For someone else who arrive to this page pinned first on Google engine and on StackOverflow after put "text/vnd.trolltech.linguist" ( in my case becasue Facebook say "text/vnd.trolltech.linguist is not allowed" when trying to upload TS file), you can try to change the extension file to ".MTS" or ".M2TS" , following the recommendation posted on the forum given by Wil Macaulay

.MTS and .M2TS file extensions should resolve to mime type video/MP2T

that work for me.
Hope this helps :-)


问:
Laravel 5.5 PHPUnit does not display descriptions
When I run phpunit its show the test is not passed. But It does not tell me why the test is not passing. I have attached two images to describe this.

Here is the result I get:

I want something I like this, to help me guide in Test Driven Development:

答:
You're seeing different results because you're running into two different categories of failures here:

1. The code executed, but your assertion failed.

This happens when PHPUnit gets some assertion that isn't truthy, such as:

```<code>$this->assertEquals(1, 0);
</code>```

When this happens, PHPUnit only sees that you tried to compare 1 and 0 and that's everything PHPUnit knows about this. It can't tell you why the code failed, because you have a business logic error that isn't detectable by PHP.

2. Some code you executed raised an error or exception that wasn't caught.

If you attempt to do something that isn't allowed in PHP (such as referencing a class that doesn't exist), you have a runtime error. In these situations, PHP will offer up more information about the error or provide a call-stack with where an exception occurred, resulting in the more detailed message you're seeing.

Body:
You're seeing different results because you're running into two different categories of failures here:

1. The code executed, but your assertion failed.

This happens when PHPUnit gets some assertion that isn't truthy, such as:

$this->assertEquals(1, 0);

When this happens, PHPUnit only sees that you tried to compare 1 and 0 and that's everything PHPUnit knows about this. It can't tell you why the code failed, because you have a business logic error that isn't detectable by PHP.

2. Some code you executed raised an error or exception that wasn't caught.

If you attempt to do something that isn't allowed in PHP (such as referencing a class that doesn't exist), you have a runtime error. In these situations, PHP will offer up more information about the error or provide a call-stack with where an exception occurred, resulting in the more detailed message you're seeing.


问:
How to deselect selected cell in UITableView
Normally, when I touch UITableViewCell, then UITableViewCell is selected and highlighted.

But, again touch exactly same UITableViewCell, then nothing happen.

I want that if I touch selected UITableViewCell, then UITableVIewCell to deselect.

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        if cell.isSelected == true {
            cell.isSelected = false
        }
    }
</code>```

/////

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        if cell.isSelected == false {
            cell.isSelected = true
        } else {
            cell.isSelected = false
        }
    }
</code>```

Both source code does not working. How do I fix this method?

答:
Minimal working example (first 7 cells are selectable):</p>

```<code>import UIKit
import PlaygroundSupport

class MyTableViewController: UITableViewController {

    var selectedIndexPath: IndexPath? = nil

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectedIndexPath == indexPath {
            // it was already selected
            selectedIndexPath = nil
            tableView.deselectRow(at: indexPath, animated: false)
        } else {
            // wasn't yet selected, so let's remember it
            selectedIndexPath = indexPath
        }
    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyTableViewController()
</code>```

Body:
Normally, when I touch UITableViewCell, then UITableViewCell is selected and highlighted.

But, again touch exactly same UITableViewCell, then nothing happen.

I want that if I touch selected UITableViewCell, then UITableVIewCell to deselect.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        if cell.isSelected == true {
            cell.isSelected = false
        }
    }

/////

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        if cell.isSelected == false {
            cell.isSelected = true
        } else {
            cell.isSelected = false
        }
    }

Both source code does not working. How do I fix this method?

Body:
Minimal working example (first 7 cells are selectable):

import UIKit
import PlaygroundSupport

class MyTableViewController: UITableViewController {

    var selectedIndexPath: IndexPath? = nil

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectedIndexPath == indexPath {
            // it was already selected
            selectedIndexPath = nil
            tableView.deselectRow(at: indexPath, animated: false)
        } else {
            // wasn't yet selected, so let's remember it
            selectedIndexPath = indexPath
        }
    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyTableViewController()


问:
Delphi Get LocationSensor Speed on Android
I'm currently developing a Localization Android App on Delphi / RADStudio Tokyo 10.2

I'm pretty new to delphi programming, and I am looking for a way to get the speed property of the LocationSensor. Through the documentation I found this:

```<code>LocationSensor1.Sensor.Speed
</code>```

But it always returns NaN, so I did some digging and found this in System.Sensors:

```<code>function TCustomLocationSensor.GetDoubleProperty(Prop: TProperty): Double;
begin
  Result := NaN;
end;
</code>```

So I am confused, am I using the wrong property, or using it wrongly ? If so what should I use, or how should I use it?

EDIT

My question differs from Xe5 locationsensor distance doesn't work? as I have no problem with GPS precision (or at least it doesn't seem so), allthough they might not be unrelated.The application communicates with a Server, that will display it's position and it's trajectory on a web browser.

For optimal usage, I have to transmit the travelling speed of the device. I thought of using Accelerometer at first, but it didn't fit the situation. Then I stumbled upon this on the embarcadero documentation : http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Sensors.TCustomLocationSensor.Speed

This was precisely what I needed, but when i try to get the value it always returns NaN, as explained above. Whilst debugging, I finally found the code showed above in System.Sensors and I thought it was strange that the function always returns NaN no matter what happens, as I found no help online ( just a few websites in japanese or russian http://www.360doc.com/content/17/0502/18/9200790_650383719.shtml
http://www.cyberforum.ru/delphi-beginners/thread1386722.html) I posted here.

答:
Try to do not use standard firemonkey TLocationSensor. Instead of that try implement solution based on native java classes (JLocationListener).

```<code>  TAndroidLocationListener = class(TJavaLocal, JLocationListener)
  public
    constructor Create();
    procedure onLocationChanged(location: JLocation); cdecl;
    procedure onProviderDisabled(provider: JString); cdecl;
    procedure onProviderEnabled(provider: JString); cdecl;
    procedure onStatusChanged(provider: JString; status: Integer; extras: JBundle); cdecl;
  end;
</code>```

in onLocationChanged(location: JLocation); cdecl; you will get instance of current location object (java interface)

For test purposes create notification event with message location.getSpeed.ToString()

Here you got similar question
How to track the user location at full time with a delphi app under android/ios

Body:
I'm currently developing a Localization Android App on Delphi / RADStudio Tokyo 10.2

I'm pretty new to delphi programming, and I am looking for a way to get the speed property of the LocationSensor. Through the documentation I found this:

LocationSensor1.Sensor.Speed

But it always returns NaN, so I did some digging and found this in System.Sensors:

function TCustomLocationSensor.GetDoubleProperty(Prop: TProperty): Double;
begin
  Result := NaN;
end;

So I am confused, am I using the wrong property, or using it wrongly ? If so what should I use, or how should I use it?

EDIT

My question differs from Xe5 locationsensor distance doesn't work? as I have no problem with GPS precision (or at least it doesn't seem so), allthough they might not be unrelated.The application communicates with a Server, that will display it's position and it's trajectory on a web browser.

For optimal usage, I have to transmit the travelling speed of the device. I thought of using Accelerometer at first, but it didn't fit the situation. Then I stumbled upon this on the embarcadero documentation : http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Sensors.TCustomLocationSensor.Speed

This was precisely what I needed, but when i try to get the value it always returns NaN, as explained above. Whilst debugging, I finally found the code showed above in System.Sensors and I thought it was strange that the function always returns NaN no matter what happens, as I found no help online ( just a few websites in japanese or russian http://www.360doc.com/content/17/0502/18/9200790_650383719.shtml
http://www.cyberforum.ru/delphi-beginners/thread1386722.html) I posted here.

Body:
Try to do not use standard firemonkey TLocationSensor. Instead of that try implement solution based on native java classes (JLocationListener).

  TAndroidLocationListener = class(TJavaLocal, JLocationListener)
  public
    constructor Create();
    procedure onLocationChanged(location: JLocation); cdecl;
    procedure onProviderDisabled(provider: JString); cdecl;
    procedure onProviderEnabled(provider: JString); cdecl;
    procedure onStatusChanged(provider: JString; status: Integer; extras: JBundle); cdecl;
  end;

in onLocationChanged(location: JLocation); cdecl; you will get instance of current location object (java interface)

For test purposes create notification event with message location.getSpeed.ToString()

Here you got similar question
How to track the user location at full time with a delphi app under android/ios


问:
AWS WAF with cloudfront
I am trying to block my ip address via WAF and using cloudfront.

It should block the IP address

I need to know whether it is neccessary to change dns configuration file with the new domain name cloudfront provides ?

答:
Yes, you should update your DNS cname record to the CloudFront distribution.

You will need to have the WAF apply to the CF distribution and not the ALB of the origin if you use one.

Title: AWS WAF with cloudfront


问:
React Router v4 Google Analytics react-ga
Hey everyone I have been trying to follow along with the docs to use react-ga in my React site. I am using the React Router v 4. I keep getting an error on my Google Analytics saying it can't find it, that there is not a valid tracking code, but I  do use my Tracking ID. Maybe there is a piece to the puzzle that I need that I am missing? Below is my index.js
https://www.npmjs.com/package/react-ga</p>

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route} from "react-router-dom";
import './index.css';
import Home from './containers/home.js'

import AllExplore from './containers/allexplore.js';

import Explore from './containers/explore.js';
let ReactGA = require('react-ga');

ReactGA.initialize('UA-MYIDNUMBER-1');

function logPageView() {
  ReactGA.set({ page: window.location.pathname +
window.location.search });
 ReactGA.pageview(window.location.pathname + window.location.search);
}

class App extends React.Component{
  render(){
        return(
 <BrowserRouter onUpdate={logPageView}>
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route exact path="/allexplore" component={AllExplore} />

    </Switch>
  </BrowserRouter>

    );
  }
}
 ReactDOM.render(<App />, document.getElementById('root'));
</code>```

答:
Here is my ReactGA Setup. I am not sure that it is ideal but it is working in multiple production applications. I also use ReactRouter4.

GoogleAnalyticsTracking.js

```<code>import React from 'react';
import GoogleAnalytics from 'react-ga';

import settings from './../../config/settings'

GoogleAnalytics.initialize(settings.GOOGLE_ANALYTICS_KEY /*, {debug : true}*/);

const GoogleAnalyticsTracking = (WrappedComponent) => {
    const trackPage = (page) => {
        GoogleAnalytics.set({ page });
        GoogleAnalytics.pageview(page);
    };

    const HOC = (props) => {
        const page = props.location.pathname;
        //Disable on dev
        if (!settings.dev){
            trackPage(page);
        }

        return (
            <WrappedComponent {...props} />
        );
    };

    return HOC;
};

export default GoogleAnalyticsTracking;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import ReduxThunk from 'redux-thunk';

import GoogleAnalyticsTracking from './component/GoogleAnalyticsTracking'
import App from './App';
import reducers from './reducers';

const history = createHistory()
const store = createStore(reducers, applyMiddleware(routerMiddleware(history), ReduxThunk))

const element = (
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <Route component={GoogleAnalyticsTracking(App)} />
        </ConnectedRouter>
    </Provider>
)

ReactDOM.render(element, document.getElementById('root'));
registerServiceWorker();
</code>```

I tried to clean this down some to just code relevant to your question about GA. I just wanted to give you an accurate picture of what is working for me.

Body:
Hey everyone I have been trying to follow along with the docs to use react-ga in my React site. I am using the React Router v 4. I keep getting an error on my Google Analytics saying it can't find it, that there is not a valid tracking code, but I  do use my Tracking ID. Maybe there is a piece to the puzzle that I need that I am missing? Below is my index.js
https://www.npmjs.com/package/react-ga

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route} from "react-router-dom";
import './index.css';
import Home from './containers/home.js'

import AllExplore from './containers/allexplore.js';

import Explore from './containers/explore.js';
let ReactGA = require('react-ga');

ReactGA.initialize('UA-MYIDNUMBER-1');

function logPageView() {
  ReactGA.set({ page: window.location.pathname +
window.location.search });
 ReactGA.pageview(window.location.pathname + window.location.search);
}

class App extends React.Component{
  render(){
        return(
 <BrowserRouter onUpdate={logPageView}>
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route exact path="/allexplore" component={AllExplore} />

    </Switch>
  </BrowserRouter>

    );
  }
}
 ReactDOM.render(<App />, document.getElementById('root'));

Body:
Here is my ReactGA Setup. I am not sure that it is ideal but it is working in multiple production applications. I also use ReactRouter4.

GoogleAnalyticsTracking.js

import React from 'react';
import GoogleAnalytics from 'react-ga';

import settings from './../../config/settings'

GoogleAnalytics.initialize(settings.GOOGLE_ANALYTICS_KEY /*, {debug : true}*/);

const GoogleAnalyticsTracking = (WrappedComponent) => {
    const trackPage = (page) => {
        GoogleAnalytics.set({ page });
        GoogleAnalytics.pageview(page);
    };

    const HOC = (props) => {
        const page = props.location.pathname;
        //Disable on dev
        if (!settings.dev){
            trackPage(page);
        }

        return (
            <WrappedComponent {...props} />
        );
    };

    return HOC;
};

export default GoogleAnalyticsTracking;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import ReduxThunk from 'redux-thunk';

import GoogleAnalyticsTracking from './component/GoogleAnalyticsTracking'
import App from './App';
import reducers from './reducers';

const history = createHistory()
const store = createStore(reducers, applyMiddleware(routerMiddleware(history), ReduxThunk))

const element = (
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <Route component={GoogleAnalyticsTracking(App)} />
        </ConnectedRouter>
    </Provider>
)

ReactDOM.render(element, document.getElementById('root'));
registerServiceWorker();

I tried to clean this down some to just code relevant to your question about GA. I just wanted to give you an accurate picture of what is working for me.


问:
How do you set specific values to a dynamic array?
Apparently I'm misunderstanding this, but I'm trying to simply set specific numbers to a dynamic memory array.</p>

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int [4][5]
    {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr [1][3]<< endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    delete x;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return;
}
</code>```

答:
Using operator new is tricky. Your program has a number of errors regarding the use of new and delete. There is a standard implementation of dynamic arrays that hides all the trickiness and cleans up after itself, namely, std::vector.  Also, avoid the use of "using namespace std;" You can get puzzling name conflicts that way.

Works good --

```<code>#include <iostream>
#include <cstdlib>
#include <vector>

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

int main () {
    vector<vector<int>> arr
    { { 3, 6, 9, 23, 16 },
    { 24, 12, 9, 13, 5 },
    { 37, 19, 43, 17, 11 },
    { 71, 32, 8, 4, 7 } };

    cout<< arr[1][3]<< endl<< endl;
    int x = arr[2][1];
    cout<< x<<  endl;
    cout<< x<< endl << endl;
    x = arr[0][3];
    cout<< x<< endl;
    return 0;
}
</code>```

P.s. There's nothing dynamic about the way you used arr. You could have instead declared it thus:

```<code>int arr[4][5]
{ { 3, 6, 9, 23, 16 },
{ 24, 12, 9, 13, 5 },
{ 37, 19, 43, 17, 11 },
{ 71, 32, 8, 4, 7 } };
</code>```

Body:
Apparently I'm misunderstanding this, but I'm trying to simply set specific numbers to a dynamic memory array.

#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int [4][5]
    {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr [1][3]<< endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    delete x;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return;
}

Body:
Using operator new is tricky. Your program has a number of errors regarding the use of new and delete. There is a standard implementation of dynamic arrays that hides all the trickiness and cleans up after itself, namely, std::vector.  Also, avoid the use of "using namespace std;" You can get puzzling name conflicts that way.

Works good --

#include <iostream>
#include <cstdlib>
#include <vector>

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

int main () {
    vector<vector<int>> arr
    { { 3, 6, 9, 23, 16 },
    { 24, 12, 9, 13, 5 },
    { 37, 19, 43, 17, 11 },
    { 71, 32, 8, 4, 7 } };

    cout<< arr[1][3]<< endl<< endl;
    int x = arr[2][1];
    cout<< x<<  endl;
    cout<< x<< endl << endl;
    x = arr[0][3];
    cout<< x<< endl;
    return 0;
}

P.s. There's nothing dynamic about the way you used arr. You could have instead declared it thus:

int arr[4][5]
{ { 3, 6, 9, 23, 16 },
{ 24, 12, 9, 13, 5 },
{ 37, 19, 43, 17, 11 },
{ 71, 32, 8, 4, 7 } };


问:
Moving Angularjs project to ReactJS
I have an AngularJS project with a NodeJS (<6) backend.

The files (including angular's libraries) are stored in a src/js directory that served from the server from an HTML script tags.

The app use plain CSS.

I want to convert this app to a react app.

I saw that a lot of guides recommend to first move to Webpack, and then to react
but they are relying on the fact that your app is pre-built like the angular pack app, with all the libraries coming from node_modules and pre loaded.

min isn't that way as you see.

What are the best methods to convert the app slowly to React?
I want to use the React with JSX and all the new stuff.

Will it be easier to rebuild the app from scratch, or to migrate slowly?

答: It depends on the needs of the project.  Is this a personal project where you're the only stakeholder?  Then i'd say just rewrite from scratch.  If this is an app for a company you work for, migrating slowly could be the best option.  The React app can basically be a "separate" app, separated by a route, or you could even use React components inside an angular component with ngReact.  The benefit is that you can build the React app separately, and just pull it into your current Angular build.  </p>

Title: Moving Angularjs project to ReactJS


问:
Mysql addition, result not as expected
Can someone tell me why this isn't working? I'd like to get the sum of two different columns and add them together. The test data is 10 in one column and 10 in the other, totaling 20 which is what I'm expecting.</p>

```<code>Sum(col1 + col2) as total
</code>```

答:
Probably you have some NULL values in one or both of the columns. The aggregate function SUM ignores NULL values, but the addition operator does not - the value of (1 + NULL) is NULL (not 1 as you might expect). As a result the sum will be lower than expected.

To get the correct sum, you can SUM over each column separately and add the results:

```<code>SUM(col1) + SUM(col2) AS total
</code>```

If one of the columns could be entirely NULL this still won't work. Then you can try this:

```<code>SUM(IFNULL(col1, 0)) + IFNULL(col2, 0)) AS total
</code>```

For example, imagine you have this table:

```
col1 | col2
-----+----
5    | NULL
5    | 10
```

Then try these different queries:

```<code>SELECT SUM(col1), SUM(col2)        FROM yourtable;    -- Returns 10, 10
SELECT SUM(col1 + col2)            FROM yourtable;    -- Returns 15
SELECT SUM(col1) + SUM(col2)       FROM yourtable;    -- Returns 20
SELECT SUM(col1 + IFNULL(col2, 0)) FROM yourtable;    -- Returns 20
</code>```

Test data:

```<code>CREATE TABLE yourtable (col1 INT NOT NULL, col2 INT NULL);
INSERT INTO yourtable (col1, col2) VALUES (5, NULL), (5, 10);
</code>```

Title: Mysql addition, result not as expected

Body:
Can someone tell me why this isn't working? I'd like to get the sum of two different columns and add them together. The test data is 10 in one column and 10 in the other, totaling 20 which is what I'm expecting.

Sum(col1 + col2) as total

Body:
Probably you have some NULL values in one or both of the columns. The aggregate function SUM ignores NULL values, but the addition operator does not - the value of (1 + NULL) is NULL (not 1 as you might expect). As a result the sum will be lower than expected.

To get the correct sum, you can SUM over each column separately and add the results:

SUM(col1) + SUM(col2) AS total

If one of the columns could be entirely NULL this still won't work. Then you can try this:

SUM(IFNULL(col1, 0)) + IFNULL(col2, 0)) AS total

For example, imagine you have this table:

col1 | col2
-----+----
5    | NULL
5    | 10

Then try these different queries:

SELECT SUM(col1), SUM(col2)        FROM yourtable;    -- Returns 10, 10
SELECT SUM(col1 + col2)            FROM yourtable;    -- Returns 15
SELECT SUM(col1) + SUM(col2)       FROM yourtable;    -- Returns 20
SELECT SUM(col1 + IFNULL(col2, 0)) FROM yourtable;    -- Returns 20

Test data:

CREATE TABLE yourtable (col1 INT NOT NULL, col2 INT NULL);
INSERT INTO yourtable (col1, col2) VALUES (5, NULL), (5, 10);


问:
Adding columns with two data types in SQL Server
I need to achieve the output like this can anyone please help me. Thanks in advance

答:
Create a function like

Create Function dbo.GetNumbers(@Data VarChar(8000))
Returns VarChar(8000)
AS
Begin

    Return Left(
             SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000),
             PatIndex('%[^0-9.-]%', SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000) + 'X')-1)
End

Source Solved Already

If you want more control (multiple numbers in a string) would be better to create a CLR function.

Use below T-SQL to get aggregated results without function:

```<code>DROP TABLE IF EXISTS #splitString
    CREATE TABLE #splitString(
    [columnA] [nchar](10) NULL,
    [columnB] [nchar](10) NULL) ON [PRIMARY]
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a10', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a05', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'b20', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a5', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'b9', NULL)
GO

select * from #splitString
select a,sum(b) from (
select

             Left(
             SubString([columnA], PatIndex('%[a-z.-]%', [columnA]), 8000),
             PatIndex('%[^a-z.-]%', SubString([columnA], PatIndex('%[a-z.-]%', [columnA]), 8000) + 'X')-1) a,
             cast (Left( SubString([columnA], PatIndex('%[0-9.-]%', [columnA]), 8000),
             PatIndex('%[^0-9.-]%', SubString([columnA], PatIndex('%[0-9.-]%', [columnA]), 8000) + 'X')-1) as int) b
From #splitString )aTable group by a
</code>```

Explanation (Thanks the external link person)

Get the first character that is int (PatIndex(‘%[0-9.-]%’, Data))

Remove all characters left to int (SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000))

Find end of numbers (Select PatIndex(‘%[^0-9.-]%’, SubString(Data, PatIndex(‘%[0-9.-]%’, Data)+1, 8000)) )

Get all ints - (Select Left(SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000), PatIndex(‘%[^0-9.-]%’, SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000) + ‘X’)-1))

Repeat above procedure for strings.

Body:
Create a function like

Create Function dbo.GetNumbers(@Data VarChar(8000))
Returns VarChar(8000)
AS
Begin

    Return Left(
             SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000),
             PatIndex('%[^0-9.-]%', SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000) + 'X')-1)
End

Source Solved Already

If you want more control (multiple numbers in a string) would be better to create a CLR function.

Use below T-SQL to get aggregated results without function:

DROP TABLE IF EXISTS #splitString
    CREATE TABLE #splitString(
    [columnA] [nchar](10) NULL,
    [columnB] [nchar](10) NULL) ON [PRIMARY]
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a10', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a05', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'b20', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'a5', NULL)
GO
INSERT #splitString ([columnA], [columnB]) VALUES (N'b9', NULL)
GO

select * from #splitString
select a,sum(b) from (
select

             Left(
             SubString([columnA], PatIndex('%[a-z.-]%', [columnA]), 8000),
             PatIndex('%[^a-z.-]%', SubString([columnA], PatIndex('%[a-z.-]%', [columnA]), 8000) + 'X')-1) a,
             cast (Left( SubString([columnA], PatIndex('%[0-9.-]%', [columnA]), 8000),
             PatIndex('%[^0-9.-]%', SubString([columnA], PatIndex('%[0-9.-]%', [columnA]), 8000) + 'X')-1) as int) b
From #splitString )aTable group by a

Explanation (Thanks the external link person)

Get the first character that is int (PatIndex(‘%[0-9.-]%’, Data))

Remove all characters left to int (SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000))

Find end of numbers (Select PatIndex(‘%[^0-9.-]%’, SubString(Data, PatIndex(‘%[0-9.-]%’, Data)+1, 8000)) )

Get all ints - (Select Left(SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000), PatIndex(‘%[^0-9.-]%’, SubString(Data, PatIndex(‘%[0-9.-]%’, Data), 8000) + ‘X’)-1))

Repeat above procedure for strings.


问:
Cannot resolve symbol ViewHolder
I was trying to implement a recycler view. but i am not able to use viewHolder. Please find a solution. Thanks in advance

答:
You can try this way hope so it will be helpful for you. </p>

```<code>public class YourAdapter extends RecyclerView.Adapter<YourAdapter.MyViewHolder> {

            private List<String> myList;

            public class MyViewHolder extends RecyclerView.ViewHolder {
                public TextView title, year, genre;

                public MyViewHolder(View view) {
                    super(view);
                    title = (TextView) view.findViewById(R.id.title);
                    genre = (TextView) view.findViewById(R.id.genre);
                    year = (TextView) view.findViewById(R.id.year);
                }
            }

            public YourAdapter(List<String> list) {
                this.myList = list;
            }

            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_row, parent, false);

                return new MyViewHolder(itemView);
            }

            @Override
            public void onBindViewHolder(MyViewHolder holder, int position) {
                Movie movie = myList.get(position);
                holder.title.setText(myList.get(position).getTitle());

            }

            @Override
            public int getItemCount() {
                return myList.size();
            }
        }
</code>```

Title: Cannot resolve symbol ViewHolder

Body:
You can try this way hope so it will be helpful for you.

public class YourAdapter extends RecyclerView.Adapter<YourAdapter.MyViewHolder> {

            private List<String> myList;

            public class MyViewHolder extends RecyclerView.ViewHolder {
                public TextView title, year, genre;

                public MyViewHolder(View view) {
                    super(view);
                    title = (TextView) view.findViewById(R.id.title);
                    genre = (TextView) view.findViewById(R.id.genre);
                    year = (TextView) view.findViewById(R.id.year);
                }
            }

            public YourAdapter(List<String> list) {
                this.myList = list;
            }

            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_row, parent, false);

                return new MyViewHolder(itemView);
            }

            @Override
            public void onBindViewHolder(MyViewHolder holder, int position) {
                Movie movie = myList.get(position);
                holder.title.setText(myList.get(position).getTitle());

            }

            @Override
            public int getItemCount() {
                return myList.size();
            }
        }

ContentLicense: CC BY-SA 4.0


问:
installing urllib in Python3.6
I would like to import urllib to use the function 'request'. However, I encountered an error when trying to do so. I tried pip install urllib but still had the same error. I am using Python 3.6. Really appreciate any help.

i do import urllib.request using this code:

```<code>import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
</code>```

but it gives me this error: ModuleNotFoundError: No Module named 'urllib.parse'; 'urllib' is not a package

here is a screenshot for the error

答:
urllib is a standard python library (built-in) so you don't have to install it. just import it if you need to use request by:

```<code>import urllib.request
</code>```

if it's not work maybe you compiled python in wrong way, so be kind and give us more details.

Title: installing urllib in Python3.6

Body:
I would like to import urllib to use the function 'request'. However, I encountered an error when trying to do so. I tried pip install urllib but still had the same error. I am using Python 3.6. Really appreciate any help.

i do import urllib.request using this code:

import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

but it gives me this error: ModuleNotFoundError: No Module named 'urllib.parse'; 'urllib' is not a package

here is a screenshot for the error

Body:
urllib is a standard python library (built-in) so you don't have to install it. just import it if you need to use request by:

import urllib.request

if it's not work maybe you compiled python in wrong way, so be kind and give us more details.


问:
Why did `rails new myproject --webpack` not generate app/javascript or config/webpacker.yml?
I'm using Rails 5.1.4 with Ruby 2.4.2 and following this tutorial about Rails modern front end set up; https://evilmartians.com/chronicles/evil-front-part-1.

This instructs me to start a new rails project with;

rails new evil_chat --skip-coffee --skip-sprockets --skip-turbolinks --webpack --database=postgresql  -T

Having done so, though i do find gem 'webpacker' in my gemfile, I do not have app/javascript/... or config/webpacker.yml in my new app's directory.

Any ideas what I've done wrong?

答:
Visit the installation guide. Your command is correct and you need to now install Webpacker with the command

```<code>bundle exec rails webpacker:install
</code>```

Continue onto the README and review the development development guide. This will help you start your webpacker's development server.

If you want to include a specific JS framework with your initial installation you can pass it in the webpack option like so:

```<code>--webpack=vue
</code>```

Or if webpack was already installed use the command bundle exec rails webpacker:install:vue on the existing Rails app.

Body:
Visit the installation guide. Your command is correct and you need to now install Webpacker with the command

bundle exec rails webpacker:install

Continue onto the README and review the development development guide. This will help you start your webpacker's development server.

If you want to include a specific JS framework with your initial installation you can pass it in the webpack option like so:

--webpack=vue

Or if webpack was already installed use the command bundle exec rails webpacker:install:vue on the existing Rails app.


问:
PhpmyAdmin graphical insertion doubles foreign key values

I have 3 tables. Very simple stuff. customer, product, order.

order table has 2 foreign keys from customer and product.

customer table has 1 row(data) and product table has 5 rows.

I want to make some dummy orders in order table using phpmyadmin.

when I pull down the combo for product, instead of seeing 5 items, I see 10 items. and that's true for customer combo as well.

Please Open the images in new window

答: This is the intended behaviour of phpmyadmin. The dropdown lists the possible values twice - first with another field first and the foreign key second, then vice versa. It should make searching for the corresponding value easier.</p>


问:
Redirect form based on radio selection
So, i have a form with 3 radio buttons. Depending on which option the user selects (he can only choose one), there can be 3 situations:

if he selects the first one, when he submits the form, he gets redirected to a new URL.

if he selects the second one, a div appears (and then disappears).

if he selects the third one, a div appears (different from the previous one), and then it also disappears.

My HTML:

```<code><form>
      <div class="radio">
        <label><input type="radio" name="paypal" value="paypal"</label>
      </div>
      <div class="radio">
        <label><input type="radio" name="money" value="money"></label>
      </div>
      <div class="radio">
        <label><input type="radio" name="mastercard" value="mastercard"></label>
      </div>
</form>
<button type="button" id="button1" name="button">Check</button>
</code>```

My JQuery:

```<code>$('#button1').click(function() {
  var value = $(this).val();
  if (value == 'paypal') {
    window.location.assign("http://www.paypal.com");
}
  else if (value == 'money') {
    $('.div2').show('slow');
      $('.div2').fadeOut(4000);
}
}
  else if (value == 'mastercard') {
    $('.div1').show('slow');
       $('.div1').fadeOut(4000);
}
</code>```

But something is not working in here, and I can't figure out what or where.
EDIT: No error, the JQuery code just doesn't work. Whatever option I choose, when I submit nothing happens.

答:
I would suggest using submit button along with the submit form event like below to make it work exactly as you like, and group the radio buttons by assigning similar names, and try to reduce the if else and make it more readable like the code below

let formEvents = {
  paypal: function() {
    console.log('redirecting');
    //uncomment the following line when you use it in your script
    //window.location.assign("http://www.paypal.com");
  },
  money: function() {
    $('.div2').show('slow', function() {
      setTimeout("$('.div2').fadeOut(4000)", 500);
    });
  },
  mastercard: function() {
    $('.div1').show('slow', function() {
      $('.div1').fadeOut(4000);
    });
  }
}

$('form').on('submit', function(e) {
  e.preventDefault();
  var value = $(this).find('input:radio:checked').val();

  if (formEvents.hasOwnProperty(value)) {
    formEvents[value].call(this);
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div1,
.div2 {
  display: none;
  background: #c8c8c8;
  border: 2px dashed #000;
  text-align: center;
}</code>```

<form>

    <input type="radio" name="selection" value="paypal">paypal

    <input type="radio" name="selection" value="money">money

    <input type="radio" name="selection" value="mastercard">mastercard

  <button type="submit" id="button1" name="button">Check</button>
</form>

div 1

div 2
```

Title: Redirect form based on radio selection

Body:
So, i have a form with 3 radio buttons. Depending on which option the user selects (he can only choose one), there can be 3 situations:

if he selects the first one, when he submits the form, he gets redirected to a new URL.

if he selects the second one, a div appears (and then disappears).

if he selects the third one, a div appears (different from the previous one), and then it also disappears.

My HTML:

<form>

        <input type="radio" name="paypal" value="paypal"

        <input type="radio" name="money" value="money">

        <input type="radio" name="mastercard" value="mastercard">

</form>
<button type="button" id="button1" name="button">Check</button>

My JQuery:

$('#button1').click(function() {
  var value = $(this).val();
  if (value == 'paypal') {
    window.location.assign("http://www.paypal.com");
}
  else if (value == 'money') {
    $('.div2').show('slow');
      $('.div2').fadeOut(4000);
}
}
  else if (value == 'mastercard') {
    $('.div1').show('slow');
       $('.div1').fadeOut(4000);
}

But something is not working in here, and I can't figure out what or where.
EDIT: No error, the JQuery code just doesn't work. Whatever option I choose, when I submit nothing happens.

Body:
I would suggest using submit button along with the submit form event like below to make it work exactly as you like, and group the radio buttons by assigning similar names, and try to reduce the if else and make it more readable like the code below

let formEvents = {
  paypal: function() {
    console.log('redirecting');
    //uncomment the following line when you use it in your script
    //window.location.assign("http://www.paypal.com");
  },
  money: function() {
    $('.div2').show('slow', function() {
      setTimeout("$('.div2').fadeOut(4000)", 500);
    });
  },
  mastercard: function() {
    $('.div1').show('slow', function() {
      $('.div1').fadeOut(4000);
    });
  }
}

$('form').on('submit', function(e) {
  e.preventDefault();
  var value = $(this).find('input:radio:checked').val();

  if (formEvents.hasOwnProperty(value)) {
    formEvents[value].call(this);
  }

});

.div1,
.div2 {
  display: none;
  background: #c8c8c8;
  border: 2px dashed #000;
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="radio">
    <label><input type="radio" name="selection" value="paypal">paypal</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="selection" value="money">money</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="selection" value="mastercard">mastercard</label>
  </div>
  <button type="submit" id="button1" name="button">Check</button>
</form>

<div class="div1">div 1</div>
<div class="div2">div 2</div>


问:
Python: How to efficiently count the number of "1"s in the binary representation of 1 to n numbers?
E.g. For the input 5, the output should be 7.
(bin(1) = 1, bin(2) = 10 ... bin(5) = 101) --> 1 + 1 + 2 + 1 + 2 = 7

Here's what I've tried, but it isn't a very efficient algorithm, considering that I iterate the loop once for each integer. My code (Python 3):

```<code>i = int(input())
a = 0
for b in range(i+1):
  a = a + bin(b).count("1")
print(a)
</code>```

Thank you!

Body:
E.g. For the input 5, the output should be 7.
(bin(1) = 1, bin(2) = 10 ... bin(5) = 101) --> 1 + 1 + 2 + 1 + 2 = 7

Here's what I've tried, but it isn't a very efficient algorithm, considering that I iterate the loop once for each integer. My code (Python 3):

i = int(input())
a = 0
for b in range(i+1):
  a = a + bin(b).count("1")
print(a)

Thank you!

Body:
Here's a solution based on the recurrence relation from OEIS:

def onecount(n):
    if n == 0:
        return 0
    if n % 2 == 0:
        m = n/2
        return onecount(m) + onecount(m-1) + m
    m = (n-1)/2
    return 2*onecount(m)+m+1

>>> [onecount(i) for i in range(30)]
[0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71]