问:
Trying to get the sum of pairs that equal to a prime number
I am trying to get four input from the user and try to find pairs that equal to a prime number just by using user defined methods. i din reach the prime step yet. But before that i ran into a problem. So jus to check the sum I TRIED printing it out in the method called sumPair6 but it prints zero, so the sum is returning 0 for everything. don't know what mistake am i doing. I got rid of the initial 0 too but still doesn't not work </p>

```<code>import java.util.Scanner;
public class prime
{
    public static int  num1 = 0,  num2 = 0,  num3 = 0,  num4 = 0, sum1= 0,sum2,sum3,sum4,sum5,sum6,val1,stop;
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        input();
        sumPair1(num1, num2, sum1);
        sumPair2(num1, num3, sum2);
        sumPair3(num1, num4, sum3);
        sumPair4(num2, num3, sum4);
        sumPair5(num2, num4, sum5);
        sumPair6(num3, num4, sum6);
       // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
    }
    public static void input ()
    {
        System.out.print("Enter a positive integer: ");
        num1 = input.nextInt();
        if(num1==0 || num1 < 0)
            while(num1==0 || num1 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num1 = input.nextInt();
            }
        if(num1 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num2 = input.nextInt();
        if(num2==0 || num2 < 0)
            while(num2 == 0 || num2 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num2 = input.nextInt();
            }
        if(num2 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num3 = input.nextInt();
        while(num3 ==0 || num3 < 0)
        {
            System.out.print("Enter a positive integer: ");
            num3 = input.nextInt();
        }
        if(num3 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num4 = input.nextInt();
        if(num4==0 || num4 < 0)
            while(num4 == 0 || num4 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num4 = input.nextInt();
            }
        if(num4 > 0)

            System.out.println("Thank you.");

    }
    public static int sumPair1(int num1, int num2, int sum1)
     {
        sum1 = num1 + num2;
        return sum1;
    }

    public static int sumPair2(int num1,int num3,int sum2)
      {
        sum2 = num1 + num3;
         System.out.println(sum1);
        return sum2;
    }

    public static int sumPair3(int num1, int num4,int sum3)
    {
        sum3 = num1 + num4;
        return sum3;
    }

    public static int sumPair4(int num2, int num3,int sum4)
    {
        sum4 = num2 + num3;
        return sum4;
    }

    public static int sumPair5(int num2,int num4,int sum5)
    {
        sum5 = num2 + num4;
        return sum5;
    }

    public static int sumPair6(int num3, int num4,int sum6)
    {
        sum6 = num3 + num4;
        System.out.println(sum1);
        return sum6;
    }
}
</code>```

答:
Notice that you are printing sum1 which is NOT set at the time you are printing meaing it retuns the 0 it was default valued to, a quick fix is priting the one you summed in the method, but another fix is to do as i will propose here

To fix this code do something like

```<code>public static void main(String args[]) {
    input();
    sum1 = sumPair(num1, num2);
    sum2 = sumPair(num1, num3);
    sum3 = sumPair(num1, num4);
    sum4 = sumPair(num2, num3);
    sum5 = sumPair(num2, num4);
    sum6 = sumPair(num3, num4);
    // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
}
</code>```

and then

```<code>public static int sumPair(int num1, int num2) { // returns a sum of 2 numers
    return num1 + num2;
}
</code>```

This is because you are always adding 2 integers, so no need for more than 1 function for it.

Extra

Rewritten most the class to make it is easier to read and use

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {

    public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added

    private static Scanner input = new Scanner(System.in);

    public static void main(String args[]) {
        int inputs = 4; // inputs wanted
        input(inputs); // gives the method the inputs wanted
        for(int i = 0; i < inputs; i++){ // for every entry in the list (notice that we add to the list in the input()
            for(int j = 0+i; j < inputs; j++) // again for every element (to sum all numbers), notice +i to prevent duplicates
            {
                if(i != j) // if the numbers aren't the same entry
                    // print the number returned from the sum function
                    System.out.println("sum of " + numbers.get(i)+ " and " + numbers.get(j) + ": " + sumPair(numbers.get(i), numbers.get(j)));
            }
        }
    }

    public static void input(int inputNumbers) {

        while(numbers.size() < inputNumbers){ // while there is more inputs needed
            System.out.print("Enter a positive integer: ");
            int num = input.nextInt();
            if(num > 0) // if the input is valid
                numbers.add(num);
            else // if the input is not valid
                while (num <= 0) { // while the input is not valid
                    System.out.print("Enter a positive integer: ");
                    num = input.nextInt(); // get the next int if it wasn't valid
                    if(num > 0) { // if the input gets valid
                        numbers.add(num);
                    }
                }
            System.out.println("Thank you.");
        }
    }

    public static int sumPair(int num1, int num2) { // sums 2 integers given to the method and returns the sum
        return num1 + num2;
    }
}
</code>```

Now this isn't a perfect class, it is just simplified some, but it should show you how to search for a range, and how that a function can be re-used, if you have questions ask in the comments below

for input 1,2,3,4 this will print

sum of 1 and 2: 3

sum of 1 and 3: 4

sum of 1 and 4: 5

sum of 2 and 3: 5

sum of 2 and 4: 6

sum of 3 and 4: 7

Body:
I am trying to get four input from the user and try to find pairs that equal to a prime number just by using user defined methods. i din reach the prime step yet. But before that i ran into a problem. So jus to check the sum I TRIED printing it out in the method called sumPair6 but it prints zero, so the sum is returning 0 for everything. don't know what mistake am i doing. I got rid of the initial 0 too but still doesn't not work

import java.util.Scanner;
public class prime
{
    public static int  num1 = 0,  num2 = 0,  num3 = 0,  num4 = 0, sum1= 0,sum2,sum3,sum4,sum5,sum6,val1,stop;
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        input();
        sumPair1(num1, num2, sum1);
        sumPair2(num1, num3, sum2);
        sumPair3(num1, num4, sum3);
        sumPair4(num2, num3, sum4);
        sumPair5(num2, num4, sum5);
        sumPair6(num3, num4, sum6);
       // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
    }
    public static void input ()
    {
        System.out.print("Enter a positive integer: ");
        num1 = input.nextInt();
        if(num1==0 || num1 < 0)
            while(num1==0 || num1 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num1 = input.nextInt();
            }
        if(num1 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num2 = input.nextInt();
        if(num2==0 || num2 < 0)
            while(num2 == 0 || num2 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num2 = input.nextInt();
            }
        if(num2 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num3 = input.nextInt();
        while(num3 ==0 || num3 < 0)
        {
            System.out.print("Enter a positive integer: ");
            num3 = input.nextInt();
        }
        if(num3 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num4 = input.nextInt();
        if(num4==0 || num4 < 0)
            while(num4 == 0 || num4 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num4 = input.nextInt();
            }
        if(num4 > 0)

            System.out.println("Thank you.");

    }
    public static int sumPair1(int num1, int num2, int sum1)
     {
        sum1 = num1 + num2;
        return sum1;
    }

    public static int sumPair2(int num1,int num3,int sum2)
      {
        sum2 = num1 + num3;
         System.out.println(sum1);
        return sum2;
    }

    public static int sumPair3(int num1, int num4,int sum3)
    {
        sum3 = num1 + num4;
        return sum3;
    }

    public static int sumPair4(int num2, int num3,int sum4)
    {
        sum4 = num2 + num3;
        return sum4;
    }

    public static int sumPair5(int num2,int num4,int sum5)
    {
        sum5 = num2 + num4;
        return sum5;
    }

    public static int sumPair6(int num3, int num4,int sum6)
    {
        sum6 = num3 + num4;
        System.out.println(sum1);
        return sum6;
    }
}

Body:
Notice that you are printing sum1 which is NOT set at the time you are printing meaing it retuns the 0 it was default valued to, a quick fix is priting the one you summed in the method, but another fix is to do as i will propose here

To fix this code do something like

public static void main(String args[]) {
    input();
    sum1 = sumPair(num1, num2);
    sum2 = sumPair(num1, num3);
    sum3 = sumPair(num1, num4);
    sum4 = sumPair(num2, num3);
    sum5 = sumPair(num2, num4);
    sum6 = sumPair(num3, num4);
    // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
}

and then

public static int sumPair(int num1, int num2) { // returns a sum of 2 numers
    return num1 + num2;
}

This is because you are always adding 2 integers, so no need for more than 1 function for it.

Extra

Rewritten most the class to make it is easier to read and use

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {

    public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added

    private static Scanner input = new Scanner(System.in);

    public static void main(String args[]) {
        int inputs = 4; // inputs wanted
        input(inputs); // gives the method the inputs wanted
        for(int i = 0; i < inputs; i++){ // for every entry in the list (notice that we add to the list in the input()
            for(int j = 0+i; j < inputs; j++) // again for every element (to sum all numbers), notice +i to prevent duplicates
            {
                if(i != j) // if the numbers aren't the same entry
                    // print the number returned from the sum function
                    System.out.println("sum of " + numbers.get(i)+ " and " + numbers.get(j) + ": " + sumPair(numbers.get(i), numbers.get(j)));
            }
        }
    }

    public static void input(int inputNumbers) {

        while(numbers.size() < inputNumbers){ // while there is more inputs needed
            System.out.print("Enter a positive integer: ");
            int num = input.nextInt();
            if(num > 0) // if the input is valid
                numbers.add(num);
            else // if the input is not valid
                while (num <= 0) { // while the input is not valid
                    System.out.print("Enter a positive integer: ");
                    num = input.nextInt(); // get the next int if it wasn't valid
                    if(num > 0) { // if the input gets valid
                        numbers.add(num);
                    }
                }
            System.out.println("Thank you.");
        }
    }

    public static int sumPair(int num1, int num2) { // sums 2 integers given to the method and returns the sum
        return num1 + num2;
    }
}

Now this isn't a perfect class, it is just simplified some, but it should show you how to search for a range, and how that a function can be re-used, if you have questions ask in the comments below

for input 1,2,3,4 this will print

sum of 1 and 2: 3

sum of 1 and 3: 4

sum of 1 and 4: 5

sum of 2 and 3: 5

sum of 2 and 4: 6

sum of 3 and 4: 7


来源: stackexchange

问:
Performance Azure Elastic pool databases
We're running in to a similar issue as mentioned in Azure hits database cpu limits too easily.
We are also using the Azure Elastic pool and are creating a new database for each customer. We use EF6-code-first to handle the SQL stuff.

Using the web front-end an user can create a customer. They do this several times a week and sometimes (not always but certainly ones a week) the database is only created partially and we get Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement errors.
When we delete this client/db and create again it works fine.
Of course this is very annoying. We are now working on catching this error, delete the db and restart the creating in code. This anybody have similar experience and hopefully a better solution?

Also creating the database takes a long time: 3-5 minutes. We only have 18 tables per database. Can we speed this up?

Next step in the workflow is to parse XML-files the user has uploaded.
We use EF6 to fill our model and save it to the database. This is really slow.
The XML-file contains employee-data we need to fill into several tables (around 15 tables). For example we have a 9.7MB XML-file containing 4416 employees and the '.save()' step takes about 12 min. Taking into account that a client has around 25 XML-files each year and the user in uploading 5 years at once this saving takes too long.

We already looked at the code and withing the boundaries of EF6 we don't think we can optimize it more. We're now looking at the configuration of our Azure subscription but documentation is scares and we cannot figure out what to change to get a better performance.

Any guidance is much appreciated.

答:
I have a cloud application which very similarly creates new customer instances with a new database shard. I have found that the code which creates these Azure databases must be VERY fault tolerant. Here's what I do:

Use a very long timeout of at least 5 minutes when you create your database. It takes a long time to return.

Wait even longer because even though the script ran and execution returned to your application, the database still isn't available for use yet. I have a simple query that I run against the database every 10 seconds. At first, the query throws an exception when it runs; I catch the exception to prevent the error from bubbling up. After a while, the query will run successfully and you know the database is ready to receive requests. I stop after 50 attempts to prevent an indefinite loop if Azure never successfully creates the table.

Now, it's generally bad practice to use try/catches for regular program flow like this and to hit a resource over and over, however, this is the only approach that I've found that works 100% of the time for this problem.

ContentLicense: CC BY-SA 3.0


问:
Creating OS version specific RPM file in Hudson
I am a newbie in rpmbuild and Hudson CI tool. I have an RPM build file which is created using Hudson CI tool running on RHEL5 server. Now I want to install that same RPM file on a server with OS version RHEL7. I came to know that there are chances that the installation of the RPM file may fail due OS version incompatibility (as it is created on RHEL5 and will be getting deployed on RHEL7) though I am not sure about it and I cant take the risk of installing the RPM file on that RHEL7 server without proper knowledge. So here are my questions:
1) Are RPM builds specific to RHEL version ?
2) Is there any dynamic configuration changes that can be done in Hudson job to make final rpm build compatible to RHEL7
3) Or do I need to  make any dynamic changes in the SPEC file to  make it RHEL 7 compatible ?</p>

答: Yes, they are usually forward compatible. You will need to use something like mock, VMs, or Docker containers to build proper RPMs for different OSs.


问:
array, std::list, std::vector inserting time
I am making a test program to measure time for storage of each container. The following is my code for the test.

```<code>#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void insert(vector<short>& v, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 50000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        } catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    for (auto it = l.begin(); it != l.end(); it++) {
        if (value < *it) {
            l.insert(it, value);
            return;
        }
    }
    l.push_back(value);
}

void insert(vector<short>& v, const short& value) {
    for (auto it = v.begin(); it != v.end(); it++) {
        if (value < *it) {
            v.insert(it, value);
            return;
        }
    }
    v.push_back(value);
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    if (logicalSize == physicalSize) throw string("No spaces in array.");
    for (int i = 0; i < logicalSize; i++) {
        if (value < arr[i]) {
            for (int j = logicalSize - 1; j >= i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i] = value;
            logicalSize++;
            return;
        }
    }
    arr[logicalSize] = value;
    logicalSize++;
}
</code>```

However, when I execute the code, the result seems a little different from the theory. The list should be fastest, but the result said that insertion in the list is slowest. Can you tell me why?

答:
Insertion in a list is blisteringly fast, but first you have to find there you want to insert. This is where list comes out a loser.

It might be helpful to stop and read Why is it faster to process a sorted array than an unsorted array? sometime around now because it covers similar material and covers it really well.

With a vector or array each element comes one after the next. Prediction is dead easy, so the CPU can be loading the cache with values you won't need for a while at the same time as it is processing the current value.

With a list predictability is shot, you have to get the next node before you can load the node after that, and that pretty much nullifies the cache. Without the cache you can see an order of magnitude degradation in performance as the CPU sits around waiting for data to be retrieved from RAM.

Bjarne Stroustrup has a number of longer pieces on this topic. The keynote video is definitely worth watching.

One important take-away is take Big-O notation with a grain of salt because it is measuring a the efficiency of the algorithm, not how well the algorithm takes advantage of the hardware.

Body:
I am making a test program to measure time for storage of each container. The following is my code for the test.

#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void insert(vector<short>& v, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 50000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        } catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    for (auto it = l.begin(); it != l.end(); it++) {
        if (value < *it) {
            l.insert(it, value);
            return;
        }
    }
    l.push_back(value);
}

void insert(vector<short>& v, const short& value) {
    for (auto it = v.begin(); it != v.end(); it++) {
        if (value < *it) {
            v.insert(it, value);
            return;
        }
    }
    v.push_back(value);
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    if (logicalSize == physicalSize) throw string("No spaces in array.");
    for (int i = 0; i < logicalSize; i++) {
        if (value < arr[i]) {
            for (int j = logicalSize - 1; j >= i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i] = value;
            logicalSize++;
            return;
        }
    }
    arr[logicalSize] = value;
    logicalSize++;
}

However, when I execute the code, the result seems a little different from the theory. The list should be fastest, but the result said that insertion in the list is slowest. Can you tell me why?


问:
Haskell: Parsing Positive Integers
I am trying to parse positive integers in Haskell and I wrote this:

```<code>number ::  [Char] st Data.Functor.Identity.Identity [Char]
number =   do
           many1 digit
</code>```

But I am getting this error:

```<code> • Expecting three fewer arguments to ‘[Char]’
   Expected kind ‘k0 -> (* -> *) -> * -> *’, but ‘[Char]’ has kind ‘*’
 • In the type signature:
    number :: [Char] st Identity [Char]
    Failed, modules loaded: none.'
</code>```

Why is this error thrown and how can I fix it?

答:
Well it is simply the type that is wrong here.

If you write :t many1 digit in the terminal, you get:

```<code>Prelude Text.Parsec.Combinator Text.Parsec.Char Text.Parsec.Prim> :t many1 digit
many1 digit :: Stream s m Char => ParsecT s u m [Char]
</code>```

So you can write the type signature of your function as:

```<code>number :: <b>Stream s m Char => ParsecT s u m [Char]</b>
number =  many1 digit</code>```

(or simply omit a type signature).

I don't see why you want a less generic type signature because potentially in the future you want to use number for something else.

The reason why the compiler gives this error, is because the type [Char] has "no type parameters" you can fill in. So the compiler get confused why to call [Char] with st, and so on.

Title: Haskell: Parsing Positive Integers

Body:
I am trying to parse positive integers in Haskell and I wrote this:

number ::  [Char] st Data.Functor.Identity.Identity [Char]
number =   do
           many1 digit

But I am getting this error:

 • Expecting three fewer arguments to ‘[Char]’
   Expected kind ‘k0 -> (* -> *) -> * -> *’, but ‘[Char]’ has kind ‘*’
 • In the type signature:
    number :: [Char] st Identity [Char]
    Failed, modules loaded: none.'

Why is this error thrown and how can I fix it?

Body:
Well it is simply the type that is wrong here.

If you write :t many1 digit in the terminal, you get:

Prelude Text.Parsec.Combinator Text.Parsec.Char Text.Parsec.Prim> :t many1 digit
many1 digit :: Stream s m Char => ParsecT s u m [Char]

So you can write the type signature of your function as:

number :: Stream s m Char => ParsecT s u m [Char]
number =  many1 digit

(or simply omit a type signature).

I don't see why you want a less generic type signature because potentially in the future you want to use number for something else.

The reason why the compiler gives this error, is because the type [Char] has "no type parameters" you can fill in. So the compiler get confused why to call [Char] with st, and so on.


问:
Change select columns from character to integers
I have a dataframe as such:

```<code>sample = data.frame(
  beer_brewerId = c("8481", "8481", "8481"),
  rev_app = c("4/5","1/5", "2/5"),
  beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
  review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE
)
str(sample)
</code>```

I would like to convert only columns 2 and 4 from a character vector into an integer for analysis purposes. Normally, this would not be so difficult if all of the character columns I have I want to convert to  numeric with the following code, but this does not work as I want to keep column 3 as a chr type:

```<code>sample %>%
  select(2,4) %>%
  mutate_if(is.character, as.numeric)
</code>```

You can easily accomplish this with base r as:

```<code>#base approach
cols <- c("2","4")
data[cols] <- lapply(data[cols], as.numeric)
</code>```

Is there an easy way to do this using dplyr, and even within a pipe sequence? If you were to select only certain columns using select(), it would not allow you to save the results back into the dataframe

Something like this would work, but as my dataset has 15+ columns, this seems like its very cumbersome code:

```<code>cleandf <- sample %>%
#Use transform or mutate to convert each column manually
transform(rev_app = as.integer(rev_app)) %>%
transform(review_taste = as.integer(review_taste))
</code>```

Is mutate_at, or mutate_each meant to perform this task? Any help would be appreciated. Thanks.

```<code>#Maybe something like this:
cols <- c("2","4")
data %>%
  mutate_each(is.character[cols], as.numeric)
</code>```

答:
Easiest way to accomplish this is through using mutate_at with the specified column indexes:</p>

```<code>sample <- sample %>%
  #Do normal mutations on the data
  mutate(rev_app =  str_replace_all(rev_app, "/5", "")) %>%
  mutate(review_taste =  str_replace_all(review_taste, "/10", "")) %>%

  #Now add this one-liner onto your chain
  mutate_at(c(2,4), as.numeric) %>%
  glimpse(., n=5)
</code>```

Body:
I have a dataframe as such:

sample = data.frame(
  beer_brewerId = c("8481", "8481", "8481"),
  rev_app = c("4/5","1/5", "2/5"),
  beer_name = c("John Harvards Simcoe IPA", "John Harvards Simcoe IPA", "John Harvards American Brown Ale"),
  review_taste =c("6/10", "7/10", "6/10"), stringsAsFactors = FALSE
)
str(sample)

I would like to convert only columns 2 and 4 from a character vector into an integer for analysis purposes. Normally, this would not be so difficult if all of the character columns I have I want to convert to  numeric with the following code, but this does not work as I want to keep column 3 as a chr type:

sample %>%
  select(2,4) %>%
  mutate_if(is.character, as.numeric)

You can easily accomplish this with base r as:

#base approach
cols <- c("2","4")
data[cols] <- lapply(data[cols], as.numeric)

Is there an easy way to do this using dplyr, and even within a pipe sequence? If you were to select only certain columns using select(), it would not allow you to save the results back into the dataframe

Something like this would work, but as my dataset has 15+ columns, this seems like its very cumbersome code:

cleandf <- sample %>%
#Use transform or mutate to convert each column manually
transform(rev_app = as.integer(rev_app)) %>%
transform(review_taste = as.integer(review_taste))

Is mutate_at, or mutate_each meant to perform this task? Any help would be appreciated. Thanks.

#Maybe something like this:
cols <- c("2","4")
data %>%
  mutate_each(is.character[cols], as.numeric)

Body:
Easiest way to accomplish this is through using mutate_at with the specified column indexes:

sample <- sample %>%
  #Do normal mutations on the data
  mutate(rev_app =  str_replace_all(rev_app, "/5", "")) %>%
  mutate(review_taste =  str_replace_all(review_taste, "/10", "")) %>%

  #Now add this one-liner onto your chain
  mutate_at(c(2,4), as.numeric) %>%
  glimpse(., n=5)


问:
React Native NativeBase ListView with separators
I currently use React Native's ListView to display a list with section headers (renderSectionHeader):

```<code><ListView
  dataSource={this.state.dataSource}
  renderRow={(rowData) => <JobListDetail firstOccurrence={rowData} />}
  renderSectionHeader={(sectionData, sectionId) => <ListSectionHeader sectionId={sectionId} />}
/>
</code>```

The dataSource contains an Array of objects with the section header in the key and and an array of list items as the value like so

```<code>{
  Section 1: [{firstName: 'A', lastName: 'B'}, {firstName: 'C', lastName: 'D'}],
  Section 2: [{firstName: 'E', lastName: 'F'}, {firstName: 'G', lastName: 'H'}]
}
</code>```

I was wondering whether I could achieve the same (and with a nicer looking layout) using NativeBase's List component. However, I couldn't find any info on how to pass in section headers:

```<code><List dataArray={items} renderRow={(data) =>
    <ListItem>
        <Text>{data}</Text>
    </ListItem>
} />
</code>```

Is that possible and if yes, are there are downsides to using it instead of React Native's ListView?

答:
In theory NativeBase's List should accept the props that React Native's ListView supports.

The section header could be rendered with the itemHeader prop:

```<code><ListItem itemHeader>
  <Text>ACTION</Text>
</ListItem>
</code>```

Body:
I currently use React Native's ListView to display a list with section headers (renderSectionHeader):

<ListView
  dataSource={this.state.dataSource}
  renderRow={(rowData) => <JobListDetail firstOccurrence={rowData} />}
  renderSectionHeader={(sectionData, sectionId) => <ListSectionHeader sectionId={sectionId} />}
/>

The dataSource contains an Array of objects with the section header in the key and and an array of list items as the value like so

{
  Section 1: [{firstName: 'A', lastName: 'B'}, {firstName: 'C', lastName: 'D'}],
  Section 2: [{firstName: 'E', lastName: 'F'}, {firstName: 'G', lastName: 'H'}]
}

I was wondering whether I could achieve the same (and with a nicer looking layout) using NativeBase's List component. However, I couldn't find any info on how to pass in section headers:

<List dataArray={items} renderRow={(data) =>
    <ListItem>
        <Text>{data}</Text>
    </ListItem>
} />

Is that possible and if yes, are there are downsides to using it instead of React Native's ListView?

Body:
In theory NativeBase's List should accept the props that React Native's ListView supports.

The section header could be rendered with the itemHeader prop:

<ListItem itemHeader>
  <Text>ACTION</Text>
</ListItem>


问:
How to set the working directory when running an executable in Eclipse CDT to be the same as the executable?
I have several build dirs for different configurations (using an external build system from the CLI), so the executable name duplicates the desired cwd:

path/to/build1/executable

path/to/build1 (desired cwd)

path/to/build2/executable

path/to/build2 (desired cwd)

Is there a more convenient way to run the executable from the directory containing it, without typing the path twice?

The most likely solution would be with a variable like ${workspace_loc} under "Arguments -> Working directory", but I could not find a suitable variable.

Tested on Eclipse 4.6.3.

答:
If you use managed build you can get away with specifying config_name appended to workspace_loc, i.e. if you project is called "test" this should work (tested on linux)

${workspace_loc:test}/${config_name:test}

My app prints
Current working dir: /home/elaskavaia/workspace/test/Debug


问:
Access vm local website without dns
I have a windows server 2012 vm (from azure) with a web node.js app running on it in port 3000.

I want to access that website from my computer, how can I do that?

答: your URL should be something like http://Azure URL or Public IP Address:3000 or  URL or Public IP Address:3000</p>

Title: Access vm local website without dns


问:
How can the client connect to the server when the server is in a busy loop?
Server looks like this:

```<code>public class Server {
public static void main(String[] args) {
    Server server = new Server();
    server.start(5006);
}

private void start(int port) {
    try(ServerSocket serverSocket = new ServerSocket(port);
        Socket clientSocket = serverSocket.accept();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));) {
        String line;
        while (true) {
            while((line = bufferedReader.readLine())!=null){
                System.out.println("line = " + line);
            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
</code>```

The client looks like this:

```<code>public class Client {
public static void main(String[] args) {
    Client client = new Client();
    client.start("localhost", 5006);
}

private void start(String localhost, int port) {
    Random random = new Random();
    try (Socket socket = new Socket(localhost, port);
         BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"))) {
        while (true) {
            int i = random.nextInt();
            bufferedWriter.write(String.valueOf(i));
            bufferedWriter.newLine();
            System.out.println("i = " + i);

            //sleep(bufferedWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void sleep(BufferedWriter bufferedWriter) throws Exception{
        //bufferedWriter.flush(); //Has to enabled if the wait below is to work
        TimeUnit.SECONDS.sleep(3);
}
</code>```

Context:

As is evident from the code, the server is single threaded. It accepts a connection from the client and goes into a busy loop processing data from the client socket. The server is intentionally handicapped.

Running one instance of the client program works as intended. The client ends random integers and the same are printed on the server's console.

Questions:

1) While one instance of the client is still running, spin up another instance of the client program.

How is this instance of the client able to connect to the server when the server is still in the busy loop (while(true))?
The client goes so far as to fill up the buffered writer and then just hangs; waiting for the server to consume the stream.

2) In the client program, uncomment the 'sleep' method and re-run.

The client program hangs. The server does not receive anything. Why? I just want to write to the buffer every 3 seconds. Nonsensical but let's suppose it is a sane thing to do for arguments sake. I also put in the sleep after we send the new line to the server just to make sure the server prints its input.

If you uncomment the flush in the sleep method, it starts working again. Why?

答:
How is this instance of the client able to connect to the server when the server is still in the busy loop (while(true))? The client goes so far as to fill up the buffered writer and then just hangs; waiting for the server to consume the stream.

Because of the listen backlog queue. The operating system completes the inbound connection and places it on the backlog queue. accept() blocks while the backlog queue is empty and then removes the first connection from it. The client's connect operation is complete before the corresponding accept() is called, and because the client now has a connection it can now write a certain amount of data to it.

2) In the client program, uncomment the 'sleep' method and re-run. The client program hangs.

It sleeps for three seconds. It doesn't 'hang'. Because of the much slower output, it takes much (much) longer for the BufferedWriter's buffer to fill and output to be flushed to the server.

The server does not receive anything. Why?

Because you haven't flushed the buffer.

I just want to write to the buffer every 3 seconds. Nonsensical but let's suppose it is a sane thing to do for arguments sake. I also put in the sleep after we send the new line to the server just to make sure the server prints its input.

If you uncomment the flush in the sleep method, it starts working again. Why?

See above.

Body:
Server looks like this:

public class Server {
public static void main(String[] args) {
    Server server = new Server();
    server.start(5006);
}

private void start(int port) {
    try(ServerSocket serverSocket = new ServerSocket(port);
        Socket clientSocket = serverSocket.accept();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));) {
        String line;
        while (true) {
            while((line = bufferedReader.readLine())!=null){
                System.out.println("line = " + line);
            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

The client looks like this:

public class Client {
public static void main(String[] args) {
    Client client = new Client();
    client.start("localhost", 5006);
}

private void start(String localhost, int port) {
    Random random = new Random();
    try (Socket socket = new Socket(localhost, port);
         BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"))) {
        while (true) {
            int i = random.nextInt();
            bufferedWriter.write(String.valueOf(i));
            bufferedWriter.newLine();
            System.out.println("i = " + i);

            //sleep(bufferedWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void sleep(BufferedWriter bufferedWriter) throws Exception{
        //bufferedWriter.flush(); //Has to enabled if the wait below is to work
        TimeUnit.SECONDS.sleep(3);
}

Context:

As is evident from the code, the server is single threaded. It accepts a connection from the client and goes into a busy loop processing data from the client socket. The server is intentionally handicapped.

Running one instance of the client program works as intended. The client ends random integers and the same are printed on the server's console.

Questions:

1) While one instance of the client is still running, spin up another instance of the client program.

How is this instance of the client able to connect to the server when the server is still in the busy loop (while(true))?
The client goes so far as to fill up the buffered writer and then just hangs; waiting for the server to consume the stream.

2) In the client program, uncomment the 'sleep' method and re-run.

The client program hangs. The server does not receive anything. Why? I just want to write to the buffer every 3 seconds. Nonsensical but let's suppose it is a sane thing to do for arguments sake. I also put in the sleep after we send the new line to the server just to make sure the server prints its input.

If you uncomment the flush in the sleep method, it starts working again. Why?


问:
Timezone in datetime string
I have the following string in an XML file:

```<code><Platform FeedLastUpdated="2017-03-29 19:37:05">StackOverflow</Platform>
</code>```

What is the best way to convey that it is in UTC tz? For example:

```<code>"2017-03-29 19:37:05 UTC"
</code>```

Is there a standard way that we should use?

答:
Your format is already quite close to ISO 8601 and its cousin RFC 3339; by using T instead of   as separator, you're there. ISO 8601 and RFC 3339 specify the timezone offset (or Z for UTC), like this:

```<code>2017-03-29T19:37:05+00:00 # UTC
2017-03-29T19:37:05-05:00 # New York time
2017-03-29T19:37:05Z      # Shortcut for UTC
</code>```

Title: Timezone in datetime string

Body:
I have the following string in an XML file:

<Platform FeedLastUpdated="2017-03-29 19:37:05">StackOverflow</Platform>

What is the best way to convey that it is in UTC tz? For example:

"2017-03-29 19:37:05 UTC"

Is there a standard way that we should use?

Body:
Your format is already quite close to ISO 8601 and its cousin RFC 3339; by using T instead of   as separator, you're there. ISO 8601 and RFC 3339 specify the timezone offset (or Z for UTC), like this:

2017-03-29T19:37:05+00:00 # UTC
2017-03-29T19:37:05-05:00 # New York time
2017-03-29T19:37:05Z      # Shortcut for UTC


问:
Tables with same structure and other tables with foreign keys
I want to create 3 Tables (I will call them Elements), that have nearly the same structure, and 4 tables (Informations) for each Elements that are linked with foreign keys.
The Informations have the same structure

```<code>CREATE TABLE Information (
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);
</code>```

The problem is that i want to create a unique table for all informations instead of having 12 tables (4 for each Elements), like that :

```<code>CREATE TABLE Information (
     --
     element_type VARCHAR(10),
     information_type VARCHAR(10),
     --
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);
</code>```

But foreign keys don't work like that.

While searching i found "polymorphic associations" but it lose the advantages of foreign keys that can cascade and that i am using. Or is there a way to mimic cascade without the foreign keys.

Also, is this better, in term of storage and performances to have the single table i want to create or the 12 tables (And do more (?) requests) knowing that each Elements can have more than 10 Information from each types of information.

答: You can try to make the insert, update and delete with triggers and the second table keep only with foreigns keys and put an identity for the primary key</p>

Body:
I want to create 3 Tables (I will call them Elements), that have nearly the same structure, and 4 tables (Informations) for each Elements that are linked with foreign keys.
The Informations have the same structure

CREATE TABLE Information (
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);

The problem is that i want to create a unique table for all informations instead of having 12 tables (4 for each Elements), like that :

CREATE TABLE Information (
     --
     element_type VARCHAR(10),
     information_type VARCHAR(10),
     --
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);

But foreign keys don't work like that.

While searching i found "polymorphic associations" but it lose the advantages of foreign keys that can cascade and that i am using. Or is there a way to mimic cascade without the foreign keys.

Also, is this better, in term of storage and performances to have the single table i want to create or the 12 tables (And do more (?) requests) knowing that each Elements can have more than 10 Information from each types of information.


问:
Nodejs -- req and res arguments of callback function in createServer()

I am confused about 'parser = this' mean, because I can't find there is calling about this function, so what 'this' mean in this native code?

This is the link of github: https://github.com/nodejs/node/blob/v0.12/lib/_http_common.js

答:
The value of this depends on how the function is called. It appears that it is supposed to be called as a method of an HTTPParser instance:

```<code>var parsers = new FreeList('parsers', 1000, function() {
  var parser = new HTTPParser(HTTPParser.REQUEST);
  // ^^^ parser object is created

  parser._headers = [];
  parser._url = '';

  parser[kOnHeaders] = parserOnHeaders;
  parser[kOnHeadersComplete] = parserOnHeadersComplete;
  parser[kOnBody] = parserOnBody;
  parser[kOnMessageComplete] = parserOnMessageComplete;
  // ^^^ function is assigned to parser instance

  return parser;
});
</code>```

Therefore we can assume that this will most likely refer to an instance of HTTPParser.

Body:
The value of this depends on how the function is called. It appears that it is supposed to be called as a method of an HTTPParser instance:

var parsers = new FreeList('parsers', 1000, function() {
  var parser = new HTTPParser(HTTPParser.REQUEST);
  // ^^^ parser object is created

  parser._headers = [];
  parser._url = '';

  parser[kOnHeaders] = parserOnHeaders;
  parser[kOnHeadersComplete] = parserOnHeadersComplete;
  parser[kOnBody] = parserOnBody;
  parser[kOnMessageComplete] = parserOnMessageComplete;
  // ^^^ function is assigned to parser instance

  return parser;
});

Therefore we can assume that this will most likely refer to an instance of HTTPParser.


问:
Assign element specific boolean values to determine if element has been previously clicked - current code blanket updates all elements
I am attempting to log whenever a county on a d3.js map has been clicked for the first time. The following code updates all elements and I haven't been able to find a way to only assign a true/false to only the element that was clicked.

If I click a county, it turns true and fills it in, if I select that county again, it returns false. If I then select an entirely different county, the value is set to false, and remains false. It never resets back to true.

I feel like I need to be using self or this to help define the element-specific boolean but no combination seems to be working.

```<code>var noFill = true;

var mousedown = function() {
    var self = d3.select(this);
    var color = document.getElementById('selcolor').value;

    if (noFill) {
        console.log(noFill);
        self.style("fill", color);
        //do some stuff
        noFill = false;
    } else {
        console.log(noFill);
        //do some stuff
    }
}
</code>```

答:
Your problem right now is that noFill is a single variable, and it's the same for all elements you click. As yourself have said, you have to define an element-specific boolean.

A simple solution is creating a datum property named noFill for each element you click, and toggling it on the click event. Something like this:

```<code>selection.on("click", function(d) {
    d.noFill = d.noFill || false;
    if (!d.noFill) {
        d3.select(this).attr("fill", "teal");
    } else {
        d3.select(this).attr("fill", "none");
    }
    d.noFill = !d.noFill;
})
</code>```

Here is a demo:

var svg = d3.select("svg");

var data = d3.range(6).map(d => ({
  id: d
}));

var circles = svg.selectAll("foo")
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 40)
  .attr("r", 16)
  .attr("cx", (d, i) => 40 + 45 * i)
  .attr("stroke", "gray")
  .attr("stroke-width", 2)
  .attr("fill", "none")
  .attr("pointer-events", "all")
  .attr("cursor", "pointer");

circles.on("click", function(d) {
  d.noFill = d.noFill || false;
  if (!d.noFill) {
    d3.select(this).attr("fill", "teal");
  } else {
    d3.select(this).attr("fill", "none");
  }
  d.noFill = !d.noFill;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg></code>```

Notice that in the anonymous function I'm using function(d), which uses the datum (d) of each element as a parameter, not just function().

Body:
I am attempting to log whenever a county on a d3.js map has been clicked for the first time. The following code updates all elements and I haven't been able to find a way to only assign a true/false to only the element that was clicked.

If I click a county, it turns true and fills it in, if I select that county again, it returns false. If I then select an entirely different county, the value is set to false, and remains false. It never resets back to true.

I feel like I need to be using self or this to help define the element-specific boolean but no combination seems to be working.

var noFill = true;

var mousedown = function() {
    var self = d3.select(this);
    var color = document.getElementById('selcolor').value;

    if (noFill) {
        console.log(noFill);
        self.style("fill", color);
        //do some stuff
        noFill = false;
    } else {
        console.log(noFill);
        //do some stuff
    }
}

Body:
Your problem right now is that noFill is a single variable, and it's the same for all elements you click. As yourself have said, you have to define an element-specific boolean.

A simple solution is creating a datum property named noFill for each element you click, and toggling it on the click event. Something like this:

selection.on("click", function(d) {
    d.noFill = d.noFill || false;
    if (!d.noFill) {
        d3.select(this).attr("fill", "teal");
    } else {
        d3.select(this).attr("fill", "none");
    }
    d.noFill = !d.noFill;
})

Here is a demo:

var svg = d3.select("svg");

var data = d3.range(6).map(d => ({
  id: d
}));

var circles = svg.selectAll("foo")
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 40)
  .attr("r", 16)
  .attr("cx", (d, i) => 40 + 45 * i)
  .attr("stroke", "gray")
  .attr("stroke-width", 2)
  .attr("fill", "none")
  .attr("pointer-events", "all")
  .attr("cursor", "pointer");

circles.on("click", function(d) {
  d.noFill = d.noFill || false;
  if (!d.noFill) {
    d3.select(this).attr("fill", "teal");
  } else {
    d3.select(this).attr("fill", "none");
  }
  d.noFill = !d.noFill;
})

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Notice that in the anonymous function I'm using function(d), which uses the datum (d) of each element as a parameter, not just function().


问:
How to get external data without CORS headers with Firebase hosted webapp?
I have my Ionic2 app hosted on Firebase. What I need is to get external data from an API service where

No 'Access-Control-Allow-Origin' header is present on the requested
  resource

I can work around it locally by using proxies in ionic.config.json file:

```<code>"proxies": [
{
"path":"/api",
"proxyUrl": "https://api.somwhere.com/"
}
]
</code>```

But I have no idea how to deal with this after deploying my app to Firebase. Is it somehow possible?

答:
This is probably not a firebase related issue. Your api needs to send CORS in header. Either accept all(*) or your specific firebase hosted app.
Easy fix for API written in .net
See link https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api</p>

Body:
I have my Ionic2 app hosted on Firebase. What I need is to get external data from an API service where

No 'Access-Control-Allow-Origin' header is present on the requested
  resource

I can work around it locally by using proxies in ionic.config.json file:

"proxies": [
{
"path":"/api",
"proxyUrl": "https://api.somwhere.com/"
}
]

But I have no idea how to deal with this after deploying my app to Firebase. Is it somehow possible?


问:
Writing into a text file line by line
I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.

```<code>using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
    dest.WriteLine(line.TrimStart());
}
</code>```

Any suggestion?

答:
try this</p>

```<code>File.AppendAllText(Path.Combine(_logFolderPath, "a.txt",
    line.Trim() + Environment.NewLine));
</code>```

Title: Writing into a text file line by line

Body:
I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.

using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
    dest.WriteLine(line.TrimStart());
}

Any suggestion?

Body:
try this

File.AppendAllText(Path.Combine(_logFolderPath, "a.txt",
    line.Trim() + Environment.NewLine));

ContentLicense: CC BY-SA 2.5


问:
How to display JSON in a UILabel
I am trying to display retrieved JSON data as a UILabel. Currently I have the data successfully displaying in the debugger but I am unsure how to set the data equivalent to a UILabel. Any help would be appreciated. </p>

```<code>import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad()
{
    super.viewDidLoad()

    let url = URL(string: "http://cgi.soic.indiana.edu/~team10/index.php")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        print(myJson)

                }
                catch
                {

                }
            }
        }
    }
    task.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

答:
You can try the code below (data is a parameter from callback method in URLSession dataTask):

```<code>let body = try? JSONSerialization.jsonObject(with: data!, options: []) as AnyObject
var jsonString = String()
do {
    let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
    jsonString = String(data: jsonData, encoding: .utf8)!
    print("jsonString: \(jsonString)")
} catch let error as NSError {
    print(error)
}
DispatchQueue.main.async {
    self.sampleLabel.text = jsonString
}
</code>```

Title: How to display JSON in a UILabel

Body:
I am trying to display retrieved JSON data as a UILabel. Currently I have the data successfully displaying in the debugger but I am unsure how to set the data equivalent to a UILabel. Any help would be appreciated.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad()
{
    super.viewDidLoad()

    let url = URL(string: "http://cgi.soic.indiana.edu/~team10/index.php")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        print(myJson)

                }
                catch
                {

                }
            }
        }
    }
    task.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Body:
You can try the code below (data is a parameter from callback method in URLSession dataTask):

let body = try? JSONSerialization.jsonObject(with: data!, options: []) as AnyObject
var jsonString = String()
do {
    let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
    jsonString = String(data: jsonData, encoding: .utf8)!
    print("jsonString: \(jsonString)")
} catch let error as NSError {
    print(error)
}
DispatchQueue.main.async {
    self.sampleLabel.text = jsonString
}


问:
How to avoid eslint rule no-unneeded-ternary violation: 'Unnecessary use of conditional expression for default assignment'
This is my code

```<code>class Message extends Component {

  render() {
    const { message, timeToRedirect } = this.props;
    const time = timeToRedirect ? timeToRedirect : TIME_TO_REDIRECT  // eslint flags this line
</code>```

The idea is that if the parameter timeToRedirect is zero or undefined, I will assign a constant TIME_TO_REDIRECT to variable time

However eslint flags this as a violation of the rule no-unneeded-ternary: 'Unnecessary use of conditional expression for default assignment'.

I can certainly rewrite it to

```<code>let time = timeToRedirect;
if (!timeToRedirect) {
   time = TIME_TO_REDIRECT;
 }
</code>```

but it is less elegant in my opinion.

Is there a better way to rewrite the ternary expression?

I am currently using these npm packages

```<code>"babel-eslint": "7.1.0",
"eslint": "3.9.1",
"eslint-config-airbnb": "12.0.0",
"eslint-plugin-import": "1.16.0",
"eslint-plugin-jsx-a11y": "2.2.3",
"eslint-plugin-react": "6.5.0",
</code>```

答:
They want you to use the OR operator:

```<code>const time = timeToRedirect || TIME_TO_REDIRECT;
</code>```

Notice that to catch undefined values you could also just use a default intialiser in the destructuring:

```<code>render() {
    const { message, timeToRedirect: time = TIME_TO_REDIRECT } = this.props;
    …
</code>```

Body:
This is my code

class Message extends Component {

  render() {
    const { message, timeToRedirect } = this.props;
    const time = timeToRedirect ? timeToRedirect : TIME_TO_REDIRECT  // eslint flags this line

The idea is that if the parameter timeToRedirect is zero or undefined, I will assign a constant TIME_TO_REDIRECT to variable time

However eslint flags this as a violation of the rule no-unneeded-ternary: 'Unnecessary use of conditional expression for default assignment'.

I can certainly rewrite it to

let time = timeToRedirect;
if (!timeToRedirect) {
   time = TIME_TO_REDIRECT;
 }

but it is less elegant in my opinion.

Is there a better way to rewrite the ternary expression?

I am currently using these npm packages

"babel-eslint": "7.1.0",
"eslint": "3.9.1",
"eslint-config-airbnb": "12.0.0",
"eslint-plugin-import": "1.16.0",
"eslint-plugin-jsx-a11y": "2.2.3",
"eslint-plugin-react": "6.5.0",

Body:
They want you to use the OR operator:

const time = timeToRedirect || TIME_TO_REDIRECT;

Notice that to catch undefined values you could also just use a default intialiser in the destructuring:

render() {
    const { message, timeToRedirect: time = TIME_TO_REDIRECT } = this.props;
    …


问:
Should you fork your own Project and submit pull request?
Hi I started a project on github with other people contributing, should I fork my own project and do updates via pull request. I've only been pushing changes to branches so far, and I am wondering if that is a bad practice.

What is the Git etiquette here?

答:
I'd suggest keeping on using branches for the work you do. Keeps stuff stable but I wouldn't bother forking my own repository.

Maybe adding some contributors to your repository so that you can have more people help with reviewing the Pull Requests if your project gets big enough.


问:
Gravitational attraction calculation
I am trying to do a simple 2d gravitational attraction problem where each player controls a particle. The math seems to make sense before I try to modify the speed of the particle. As soon as I move the particle and the angle becomes non 0, the particles move quickly to 0,0 and then all the values become NaN. Any Ideas on why this happens? </p>

```<code>for(var i in Player.list){
        var player = Player.list[i];
        if(player.id !== self.id){
            var xDisp = self.x - player.x;
            var yDisp = self.y - player.y;
            var distance = Math.sqrt(Math.pow(xDisp, 2) + Math.pow(yDisp, 2));
            var angle = Math.atan2(yDisp, xDisp);
            console.log("angle:" + angle);
            if(distance !== 0){
                attractionAcceleration = GRAVITATIONAL_ATTRACTION_CONSTANT / Math.pow(distance^2); //add mass calculation later when mass is variable
                self.spdX += attractionAcceleration * Math.cos(angle);
                console.log("self.spdX :" + self.spdX);
                self.spdY -= attractionAcceleration * Math.sin(angle);
                console.log("self.spdy:" + self.spdY);
            }
        }
    }
</code>```

答: The issue is with Math.pow(distance^2) which should be Math.pow(distance,2). That explains why the result became NaN.

Title: Gravitational attraction calculation

Body:
I am trying to do a simple 2d gravitational attraction problem where each player controls a particle. The math seems to make sense before I try to modify the speed of the particle. As soon as I move the particle and the angle becomes non 0, the particles move quickly to 0,0 and then all the values become NaN. Any Ideas on why this happens?

for(var i in Player.list){
        var player = Player.list[i];
        if(player.id !== self.id){
            var xDisp = self.x - player.x;
            var yDisp = self.y - player.y;
            var distance = Math.sqrt(Math.pow(xDisp, 2) + Math.pow(yDisp, 2));
            var angle = Math.atan2(yDisp, xDisp);
            console.log("angle:" + angle);
            if(distance !== 0){
                attractionAcceleration = GRAVITATIONAL_ATTRACTION_CONSTANT / Math.pow(distance^2); //add mass calculation later when mass is variable
                self.spdX += attractionAcceleration * Math.cos(angle);
                console.log("self.spdX :" + self.spdX);
                self.spdY -= attractionAcceleration * Math.sin(angle);
                console.log("self.spdy:" + self.spdY);
            }
        }
    }


问:
Ruby on rails - Sort data with SQL/ActiveRecord instead of ruby
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

```<code>@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }
</code>```

Is their a way to do the same thing only with SQL/ActiveRecord?

答:
Since you don’t have the same columns in each model you could create a polymorphic relationship with a new model called media. Your Videos and Pictures would be associated with this new model and when you need to work on only your media you don’t need to worry about whether it is a video or a picture. I’m not sure if this fits into your schema and design since there is not much info to go on from your post but this might work if you wanted to take the time to restructure your schema. This would allow you to use the query interface to access media. See the Rails Guide here:

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

You can create a media model with all the fields need to satisfy a Video or Picture object. The media model will also have a type field to keep track of what kind of media it is: Video or Picture.

Body:
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }

Is their a way to do the same thing only with SQL/ActiveRecord?


问:
How to replace certain value in the String Using arrays
```<code>String[] enc=new String[]{"w","e","l","c","o","m"};
    String[] cod=new String[] {"111","10","00","110","010","011"};
    String real="";
    int sindex=0;
    int eindex=1;
    String cdd="111100011001001110";
    StringBuilder code=new StringBuilder(cdd);

    String temp;
    for(int i=0;i<code.length();i++){
        temp=code.substring(sindex, eindex++);
        if(Arrays.asList(cod).contains(temp)){
            int j=Arrays.asList(cod).indexOf(temp);
            int z=code.indexOf(temp);
            StringBuilder y = code.delete(z, z+temp.length());
        temp=y.toString();
        real+=enc[j];
        System.out.println(y);

        }
    }
</code>```

I have these two arrays enc[] and cod[], contains characters and codes respectively what i want to do is just check each value of cod array in cdd string and replace it with its respective String from enc[]...
By running this code i am getting only "w" while the result was suppose to be "welcome".

答:
Try this code - i have refactored yours :)

public class enc {

```<code>    private static boolean valueFound=false;

    public static void main(String[] args) {
        String[] enc=new String[]{"w","e","l","c","o","m"};
        String[] cod=new String[] {"111","10","00","110","010","011"};
        String real="";
        int sindex=0;
        int eindex=1;
        String cdd="111100011001001110";

        do {
            for (int i = 0; i < cod.length; i++) {
                if (cdd.startsWith(cod[i])) {
                    real += enc[i];
                    cdd = cdd.substring(cod[i].length());
                    valueFound = true;
                } else {
                    valueFound = false;
                }

            }
        }
        while(valueFound);
        System.out.println(real);

            }
        }
</code>```

Body:
String[] enc=new String[]{"w","e","l","c","o","m"};
    String[] cod=new String[] {"111","10","00","110","010","011"};
    String real="";
    int sindex=0;
    int eindex=1;
    String cdd="111100011001001110";
    StringBuilder code=new StringBuilder(cdd);

    String temp;
    for(int i=0;i<code.length();i++){
        temp=code.substring(sindex, eindex++);
        if(Arrays.asList(cod).contains(temp)){
            int j=Arrays.asList(cod).indexOf(temp);
            int z=code.indexOf(temp);
            StringBuilder y = code.delete(z, z+temp.length());
        temp=y.toString();
        real+=enc[j];
        System.out.println(y);

        }
    }

I have these two arrays enc[] and cod[], contains characters and codes respectively what i want to do is just check each value of cod array in cdd string and replace it with its respective String from enc[]...
By running this code i am getting only "w" while the result was suppose to be "welcome".

Body:
Try this code - i have refactored yours :)

public class enc {

    private static boolean valueFound=false;

    public static void main(String[] args) {
        String[] enc=new String[]{"w","e","l","c","o","m"};
        String[] cod=new String[] {"111","10","00","110","010","011"};
        String real="";
        int sindex=0;
        int eindex=1;
        String cdd="111100011001001110";

        do {
            for (int i = 0; i < cod.length; i++) {
                if (cdd.startsWith(cod[i])) {
                    real += enc[i];
                    cdd = cdd.substring(cod[i].length());
                    valueFound = true;
                } else {
                    valueFound = false;
                }

            }
        }
        while(valueFound);
        System.out.println(real);

            }
        }


问:
Java TreeSet contains() gives false results
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

```<code>C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9
</code>```

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

```<code>cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false
</code>```

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?

答:
As I often say, if you have a bug in your program, use a debugger. This showed me your problem very quickly.

TreeSet is a binary tree.  When searching it navigates down the tree based on whether the element you are looking for is before or after (or the same) as the one it is examining. If you add the following to you compareTo()

```<code>System.out.println("Comparing, "+this+" to "+c);
</code>```

it will print out

```<code>Comparing, C9 to C1
Comparing, C9 to C5
Comparing, C9 to C7
</code>```

The problem is that C9 is after every element which it doesn't match. So when it gets to C5 on the tree, your compareTo to says it is after it, when actually it needs to look before (to get to C3) and the search goes down the wrong path of the tree.

Body:
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?

Body:
As I often say, if you have a bug in your program, use a debugger. This showed me your problem very quickly.

TreeSet is a binary tree.  When searching it navigates down the tree based on whether the element you are looking for is before or after (or the same) as the one it is examining. If you add the following to you compareTo()

System.out.println("Comparing, "+this+" to "+c);

it will print out

Comparing, C9 to C1
Comparing, C9 to C5
Comparing, C9 to C7

The problem is that C9 is after every element which it doesn't match. So when it gets to C5 on the tree, your compareTo to says it is after it, when actually it needs to look before (to get to C3) and the search goes down the wrong path of the tree.


问:
Unresolved external class member when linking static lib from dynamic dll
MS Visual Studio 2008. This seems to be a name mangling issue, but I can't find the right search terms to come up with an answer.

I have a dynamic lib that has a class in it, which is using a logging class from a static logging library. The dynamic lib imports the static library in the project settings. I use this static lib in other projects, so I know it compiles and links without error.

Sample code:

Dynamic.h:

```<code>extern "C"
{
  __declspec(dllexport) BYTE GetData();
};
</code>```

Dynamic.cpp:

```<code>#include "MyClass.h"

static MyClass g_Inst;

BYTE GetData() { return g_Inst.GetData(); }
</code>```

MyClass.h:

```<code>#include "Logging.h"

class MyClass
{
public:
  BYTE GetData() { CLogging::Instance().AddString("Test"); }
};
</code>```

Linker:

```<code>error LNK2019: unresolved external symbol "public: void __cdecl CLogging::AddString(class ATL::CStringT<wchar_t,class StrTraitMFC<wchar_t,class ATL::ChTraitsOS<wchar_t> > > const &)" (?AddString@CLogging@@QAAXABV?$CStringT@_WV?$StrTraitMFC@_WV?$ChTraitsOS@_W@ATL@@@@@ATL@@@Z) referenced in function "public: unsigned char __cdecl MyClass::GetData(void)" (?GetData@MyClass@@QAAEXZ)
</code>```

Edit: thinking maybe it was a Unicode or MFC issue, I checked on the project settings for the Dynamic project:

The Logging project:

And two other projects that also pull in Logging with no problems:

The only difference I can see is the one that doesn't work is built as a dynamic dll.

答:
While maybe incidental, the error seems to indicate that the linker cannot find the wide-character version of ATL::CStringT<> (note instances of wchar_t following):

error LNK2019: unresolved external symbol "public: void __cdecl CLogging::AddString(class ATL::CStringT<wchar_t,class StrTraitMFC<wchar_t,class ATL::ChTraitsOS<wchar_t> > > const &)" (?AddString@CLogging@@QAAXABV?$CStringT@_WV?$StrTraitMFC@_WV?$ChTraitsOS@_W@ATL@@@@@ATL@@@Z) referenced in function "public: unsigned char __cdecl MyClass::GetData(void)" (?GetData@MyClass@@QAAEXZ)

You might check your project settings, and try to build using a non-Unicode character set.

Body:
MS Visual Studio 2008. This seems to be a name mangling issue, but I can't find the right search terms to come up with an answer.

I have a dynamic lib that has a class in it, which is using a logging class from a static logging library. The dynamic lib imports the static library in the project settings. I use this static lib in other projects, so I know it compiles and links without error.

Sample code:

Dynamic.h:

extern "C"
{
  __declspec(dllexport) BYTE GetData();
};

Dynamic.cpp:

#include "MyClass.h"

static MyClass g_Inst;

BYTE GetData() { return g_Inst.GetData(); }

MyClass.h:

#include "Logging.h"

class MyClass
{
public:
  BYTE GetData() { CLogging::Instance().AddString("Test"); }
};

Linker:

error LNK2019: unresolved external symbol "public: void __cdecl CLogging::AddString(class ATL::CStringT<wchar_t,class StrTraitMFC<wchar_t,class ATL::ChTraitsOS<wchar_t> > > const &)" (?AddString@CLogging@@QAAXABV?$CStringT@_WV?$StrTraitMFC@_WV?$ChTraitsOS@_W@ATL@@@@@ATL@@@Z) referenced in function "public: unsigned char __cdecl MyClass::GetData(void)" (?GetData@MyClass@@QAAEXZ)

Edit: thinking maybe it was a Unicode or MFC issue, I checked on the project settings for the Dynamic project:

The Logging project:

And two other projects that also pull in Logging with no problems:

The only difference I can see is the one that doesn't work is built as a dynamic dll.


问:
Using babel/i18n with webapp2 and deferred tasks in google appengine
I have a relatively expensive email-a-set-of-people tasks for which I am trying to use the "deferred" library in Google AppEngine. I'd like to send the handler just the list of recipients and some details, and have the handler format the emails to the correct language for each person. I'm using Babel.

If I do this without deferring, works great - the translations for the content load and all is good. But if I defer and move the fetching of the content to the handler, the i18n library isn't loaded properly - i18n.get_i18n().translations is a NullTranslations object. So the deferred task handler apparently don't get the context when it kicks off - is there a way to intialize i18n to get it to reload properly? Or some way to tell the AppEngine to preserve some context?

thanks!

答: Ah. If I use the regular task queue instead of the deferred library, it works fine. The 'deferred' library is supposed to just be a wrapper around the task queue system, but it apparently acts differently to the i18n libray. i18n does want the 'request' object; maybe the deferred handler does something weird with it. No matter - using the queue directly is almost as easy.</p>


问:
Why isn't 18:9 ratio just called 2:1?
Two of the most common screen ratios are 4:3 and 16:9. 4:3 could have just been called 16:12, but I guess how it works is that they always round down without decimal point, which explains why 16:9 isn't called 8:4.5. Why isn't this the case with 18:9?

答:
Um, basically because people are used to hearing "16:9" and 18:9 has two more on one side than 16. So from a marketing standpoint, it's 16:9 ... but two bigger.

In short, "Most blokes, you know, will be viewing at 16. Where can you go from there? 18. Two bigger."

...These go to 18.

Title: Why isn't 18:9 ratio just called 2:1?


问:
How to retrieve data from dynamically created textboxes and build strings
So I have some code, that creates a row of 4 textboxes.  The data from those 4 textboxes will be combined to make a SQL query and then executed.  The button to add a row can be hit an infinite amount of times.  I have my IDs generated so that on the first click textbox one is txtBox1Row1, then on the second click it is txtBox1Row2 etc, etc.

Now I need a way to retrieve the data from each row and build SQL queries from them.  Just to reiterate, I only need the data from the 4 textboxes in each row per loop (I assume thats how this will need to be done).

So how do I go about doing this?

Thanks a lot, the help is always appreciated.  I was planning on doing it like this:

```<code>        foreach (Control c in pnlArea.Controls)
        {
            if (c.ID.Contains("ddlArea"))
            {
                area.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtArea"))
            {
                areaOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("ddHazard"))
            {
                hazard.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtHazard"))
            {
                hazardOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtHazardDesc"))
            {
                hazardDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtActionDesc"))
            {
                actionDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("calDueDate"))
            {
                dueDate.Add(((Calendar)c).SelectedDate);
            }
        }
</code>```

答:
Per Nkosi, you'd want to encapsulate your textbox 'area' in a form.

What I would recommend is looping through each textbox in the form and storing in a dictionary.

Here's what that might look like:

```<code>Dictionary<string, string> textBoxVals = new Dictionary<string, string>();

Control form = this.FindControl("form1") as Control;

TextBox tb;

foreach (Control c in form.Controls)
{
    if (c.GetType() == typeof(TextBox))
    {
        tb = c as TextBox;
        textBoxVals.Add(tb.ID, tb.Text);
    }
}
</code>```

Then you'd be able to loop through the dictionary to build your SQL string. The dictionary would contain both the dynamic name of the control and the value of the textbox.

Based on the code you posted it looks like maybe there are some other controls that might also be associated with each line. If that's the case, you can create another if statement in the foreach loop to handle different control types, so that you're saving the proper parameters of them.

I hope that helps.

Body:
So I have some code, that creates a row of 4 textboxes.  The data from those 4 textboxes will be combined to make a SQL query and then executed.  The button to add a row can be hit an infinite amount of times.  I have my IDs generated so that on the first click textbox one is txtBox1Row1, then on the second click it is txtBox1Row2 etc, etc.

Now I need a way to retrieve the data from each row and build SQL queries from them.  Just to reiterate, I only need the data from the 4 textboxes in each row per loop (I assume thats how this will need to be done).

So how do I go about doing this?

Thanks a lot, the help is always appreciated.  I was planning on doing it like this:

        foreach (Control c in pnlArea.Controls)
        {
            if (c.ID.Contains("ddlArea"))
            {
                area.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtArea"))
            {
                areaOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("ddHazard"))
            {
                hazard.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtHazard"))
            {
                hazardOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtHazardDesc"))
            {
                hazardDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtActionDesc"))
            {
                actionDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("calDueDate"))
            {
                dueDate.Add(((Calendar)c).SelectedDate);
            }
        }

Body:
Per Nkosi, you'd want to encapsulate your textbox 'area' in a form.

What I would recommend is looping through each textbox in the form and storing in a dictionary.

Here's what that might look like:

Dictionary<string, string> textBoxVals = new Dictionary<string, string>();

Control form = this.FindControl("form1") as Control;

TextBox tb;

foreach (Control c in form.Controls)
{
    if (c.GetType() == typeof(TextBox))
    {
        tb = c as TextBox;
        textBoxVals.Add(tb.ID, tb.Text);
    }
}

Then you'd be able to loop through the dictionary to build your SQL string. The dictionary would contain both the dynamic name of the control and the value of the textbox.

Based on the code you posted it looks like maybe there are some other controls that might also be associated with each line. If that's the case, you can create another if statement in the foreach loop to handle different control types, so that you're saving the proper parameters of them.

I hope that helps.


问:
Wordpress theme doesn't have alt tags in their shortcodes except for one image style. I am trying to override that, but it keeps breaking
I made the mistake of purchasing a theme that for some reason does not have an easy way to use alt tags. When I add the images in to wordpress, it gives me the option to put in the alt tag, which I always have done, but it never actually shows up on the page.

I am trying to figure out how to do it, but it appears that the themes shortcode only allows the alt attribute for one type of image, but there are 3 types of images in the theme. The first block of code that you will see below is from the photo frame, which is just the regular photo addition into a post. It has the spot for an alt tag.

As soon as I try to add that to the code in the other option, which is a banner list, it breaks all the code and gives me an error saying:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING,
  expecting ')' in

I would like to add the alt attribute to the second block of code.

This is the code that works:

```<code>    // Photo Frame
add_shortcode('photo', 'theme_shortcode_photo');
function theme_shortcode_photo($atts, $content = null, $code) {
    extract(shortcode_atts(array(
        'size' => '',
        'width' => null,
        'height' => null,
        'frame' => 'true',
        'title' => false,
        'link' => false,
        'lightbox' => 'image',
        'align' => 'none',
        'icon' => 'zoom',
        'target' => '_self',
        'alt' => ''
    ), $atts));

    if( $width == null )
    switch( $size ) {
        case 'small' : $width = 200;
            break;
        case 'medium' : $width = 400;
            break;
        case 'big' : $width = 675;
            break;
    }

    $original_image_src = $content;
    $resized_image_src = theme_get_image( $original_image_src, $width, $height, true );

    $lightbox = $lightbox ? 'gz-fancy-' . $lightbox : '';
    $align = 'align-' . $align;
    $frame = ( $frame != 'true' ) ? 'photo-glass-frame' : '';
    $title_box = $title ? '<div class="photo-title">'. $title .'</div>' : '';
    $title = $title ? 'title="' . $title . '"' : '';
    $play_mask = ( $icon == 'play' ) ? '<span class="play-mask"></span>' : '';
    $icon = 'icon-' . $icon;

    $img_tag = '<img src="'. $resized_image_src .'" alt="'.$alt.'" />';
    if( $link ) $img_tag = '<a href="'.$link.'" class="'. $lightbox . '" ' . $title .' target="' . $target . '">' . $img_tag . $play_mask . '</a>';

    return <<<RET
[raw]
<div class="photo-frame-wrap $align" style="width:{$width}px;">
<div class="photo-frame $frame $icon">
$img_tag
</div>
$title_box
</div>
[/raw]
RET;
}
</code>```

This is the code that does not work:

```<code>    // Banner List
    add_shortcode('banner_list', 'theme_shortcode_banner_list');
    function theme_shortcode_banner_list($atts, $content = null, $code) {
    extract(shortcode_atts(array(
        'align' => 'left',
        'grid_height' => 100,
        'grid_width' => 200,
        'fx_bw' => false
        'alt' => ''
    ), $atts));
    $id = mt_rand(0, 9999);

    $class = 'banner-list banner-list-' . $align;
    $list = '';
    if (!preg_match_all("/(.?)\[(img)\b(.*?)(?:(\/))?\](?:(.+?)\[\/img\])?(.?)/s", $content, $matches)) {
        return do_shortcode($content);
    } else {
        for($i = 0; $i < count($matches[0]); $i++) {
            $matches[3][$i] = shortcode_parse_atts($matches[3][$i]);

            $original_image_src = $matches[5][$i];
            $resized_image_src = theme_get_image( $original_image_src, $grid_width, $grid_height );
            $img = '<img src="' . $resized_image_src . '" />';

            $greyscale = ( $fx_bw ) ? 'class="greyscale"' : '';

            if( isset( $matches[3][$i]['link'] ) ) {
                $list .= '<li ' . $greyscale . '><a href="'.$matches[3][$i]['link'].'">'.$img.'</a></li>';
            } else {
                $list .= '<li ' . $greyscale . '>'.$img.'</li>';
            }
        }
    }

    return <<<RET
<ul class="$class">
$list
</ul>
RET;
}
</code>```

答:
There's a syntax error. Please add a comma after "'fx_bw' => false" in  the array like below

'fx_bw' => false,
'alt' => ''

Body:
I made the mistake of purchasing a theme that for some reason does not have an easy way to use alt tags. When I add the images in to wordpress, it gives me the option to put in the alt tag, which I always have done, but it never actually shows up on the page.

I am trying to figure out how to do it, but it appears that the themes shortcode only allows the alt attribute for one type of image, but there are 3 types of images in the theme. The first block of code that you will see below is from the photo frame, which is just the regular photo addition into a post. It has the spot for an alt tag.

As soon as I try to add that to the code in the other option, which is a banner list, it breaks all the code and gives me an error saying:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING,
  expecting ')' in

I would like to add the alt attribute to the second block of code.

This is the code that works:

    // Photo Frame
add_shortcode('photo', 'theme_shortcode_photo');
function theme_shortcode_photo($atts, $content = null, $code) {
    extract(shortcode_atts(array(
        'size' => '',
        'width' => null,
        'height' => null,
        'frame' => 'true',
        'title' => false,
        'link' => false,
        'lightbox' => 'image',
        'align' => 'none',
        'icon' => 'zoom',
        'target' => '_self',
        'alt' => ''
    ), $atts));

    if( $width == null )
    switch( $size ) {
        case 'small' : $width = 200;
            break;
        case 'medium' : $width = 400;
            break;
        case 'big' : $width = 675;
            break;
    }

    $original_image_src = $content;
    $resized_image_src = theme_get_image( $original_image_src, $width, $height, true );

    $lightbox = $lightbox ? 'gz-fancy-' . $lightbox : '';
    $align = 'align-' . $align;
    $frame = ( $frame != 'true' ) ? 'photo-glass-frame' : '';
    $title_box = $title ? '
'. $title .'
' : '';
    $title = $title ? 'title="' . $title . '"' : '';
    $play_mask = ( $icon == 'play' ) ? '' : '';
    $icon = 'icon-' . $icon;

    $img_tag = '';
    if( $link ) $img_tag = '' . $img_tag . $play_mask . '';

    return <<<RET
[raw]

$img_tag

$title_box

[/raw]
RET;
}

This is the code that does not work:

    // Banner List
    add_shortcode('banner_list', 'theme_shortcode_banner_list');
    function theme_shortcode_banner_list($atts, $content = null, $code) {
    extract(shortcode_atts(array(
        'align' => 'left',
        'grid_height' => 100,
        'grid_width' => 200,
        'fx_bw' => false
        'alt' => ''
    ), $atts));
    $id = mt_rand(0, 9999);

    $class = 'banner-list banner-list-' . $align;
    $list = '';
    if (!preg_match_all("/(.?)\[(img)\b(.*?)(?:(\/))?\](?:(.+?)\[\/img\])?(.?)/s", $content, $matches)) {
        return do_shortcode($content);
    } else {
        for($i = 0; $i < count($matches[0]); $i++) {
            $matches[3][$i] = shortcode_parse_atts($matches[3][$i]);

            $original_image_src = $matches[5][$i];
            $resized_image_src = theme_get_image( $original_image_src, $grid_width, $grid_height );
            $img = '';

            $greyscale = ( $fx_bw ) ? 'class="greyscale"' : '';

            if( isset( $matches[3][$i]['link'] ) ) {
                $list .= '
'.$img.'
';
            } else {
                $list .= '
'.$img.'
';
            }
        }
    }

    return <<<RET

$list

RET;
}