问:
csv to json with column data that needs to be grouped
I have a CSV file in a format similar to this

```<code>order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2
</code>```

I want to export to json, currently I am doing this.

```<code>df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )
</code>```

And the output is

```<code>[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......
</code>```

However, I would like the output to be

```<code>[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......
</code>```

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

答:
Try the following:

```<code>import pandas as pd
import json

output_lst = []

##specify the first row as header
df = pd.read_csv('simple.csv', header=0)
##iterate through all the rows
for index, row in df.iterrows():
    dict = {}
    items_lst = []
    ## column_list is a list of column headers
    column_list = df.columns.values
    for i, col_name in enumerate(column_list):
        ## for the first 2 columns simply copy the value into the dictionary
        if i<2:
            element = row[col_name]
            if isinstance(element, str):
            ## strip if it is a string type value
                element = element.strip()
            dict[col_name] = element

        elif "_id" in col_name:
            ## i+1 is used assuming that the item_quantity comes right after  the corresponding item_id for each item
            item_dict  = {"id":row[col_name], "quantity":row[column_list[i+1]]}
            items_lst.append(item_dict)

    dict["items"] = items_lst
    output_lst.append(dict)

print json.dumps(output_lst)
</code>```

If you run the above file with the sample.csv described in the question then you get the following output:

```<code>[
    {
        "order_id": 1,
        "items": [
            {
                "id": 4,
                "quantity": 1
            },
            {
                "id": 24,
                "quantity": 4
            },
            {
                "id": 16,
                "quantity": 1
            }
        ],
        " customer_name": "John"
    },
    {
        "order_id": 2,
        "items": [
            {
                "id": 8,
                "quantity": 3
            },
            {
                "id": 41,
                "quantity": 1
            },
            {
                "id": 33,
                "quantity": 1
            }
        ],
        " customer_name": "Paul"
    },
    {
        "order_id": 3,
        "items": [
            {
                "id": 1,
                "quantity": 1
            },
            {
                "id": 34,
                "quantity": 4
            },
            {
                "id": 8,
                "quantity": 2
            }
        ],
        " customer_name": "Andrew"
    }
]
</code>```

Body:
I have a CSV file in a format similar to this

order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2

I want to export to json, currently I am doing this.

df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )

And the output is

[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......

However, I would like the output to be

[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

Body:
Try the following:

import pandas as pd
import json

output_lst = []

##specify the first row as header
df = pd.read_csv('simple.csv', header=0)
##iterate through all the rows
for index, row in df.iterrows():
    dict = {}
    items_lst = []
    ## column_list is a list of column headers
    column_list = df.columns.values
    for i, col_name in enumerate(column_list):
        ## for the first 2 columns simply copy the value into the dictionary
        if i<2:
            element = row[col_name]
            if isinstance(element, str):
            ## strip if it is a string type value
                element = element.strip()
            dict[col_name] = element

        elif "_id" in col_name:
            ## i+1 is used assuming that the item_quantity comes right after  the corresponding item_id for each item
            item_dict  = {"id":row[col_name], "quantity":row[column_list[i+1]]}
            items_lst.append(item_dict)

    dict["items"] = items_lst
    output_lst.append(dict)

print json.dumps(output_lst)

If you run the above file with the sample.csv described in the question then you get the following output:

[
    {
        "order_id": 1,
        "items": [
            {
                "id": 4,
                "quantity": 1
            },
            {
                "id": 24,
                "quantity": 4
            },
            {
                "id": 16,
                "quantity": 1
            }
        ],
        " customer_name": "John"
    },
    {
        "order_id": 2,
        "items": [
            {
                "id": 8,
                "quantity": 3
            },
            {
                "id": 41,
                "quantity": 1
            },
            {
                "id": 33,
                "quantity": 1
            }
        ],
        " customer_name": "Paul"
    },
    {
        "order_id": 3,
        "items": [
            {
                "id": 1,
                "quantity": 1
            },
            {
                "id": 34,
                "quantity": 4
            },
            {
                "id": 8,
                "quantity": 2
            }
        ],
        " customer_name": "Andrew"
    }
]


来源: stackexchange

问:
Can't create migrations with same name even after deleting the file
```
php artisan make:migration create_batles_table
Created Migration: 2017_04_01_123218_create_batles_table

php artisan make:migration create_batles_table
  [InvalidArgumentException]
  A CreateBatlesTable migration already exists.

---------------------File deleted by me-----------------------------

php artisan make:migration create_batles_table
 [ErrorException]
 include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123218_create_batles_table.php): fail
  ed to open stream: No such file or directory
```

Now using another name "newbatles" instead of "batles"

```
php artisan make:migration create_newbatles_table
Created Migration: 2017_04_01_123343_create_newbatles_table

php artisan make:migration create_newbatles_table
[InvalidArgumentException]
A CreateNewbatlesTable migration already exists.

-----------File deleted by me--------------

php artisan make:migration create_newbatles_table
[ErrorException]
include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123343_create_newbatles_table.php): f
  ailed to open stream: No such file or directory
```

Why I can't recreate migrations with same name in Laravel 5.4?

答:
Did you delete it from migration table too ?

If not please run

```<code>php artisan migrate:refresh
</code>```

to refresh the table.
but be aware that in this way you will clean all the database tables!
so if you don't want to do so, just delete the migration from the database directly.

ContentLicense: CC BY-SA 3.0

Body:
php artisan make:migration create_batles_table
Created Migration: 2017_04_01_123218_create_batles_table

php artisan make:migration create_batles_table
  [InvalidArgumentException]
  A CreateBatlesTable migration already exists.

---------------------File deleted by me-----------------------------

php artisan make:migration create_batles_table
 [ErrorException]
 include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123218_create_batles_table.php): fail
  ed to open stream: No such file or directory

Now using another name "newbatles" instead of "batles"

php artisan make:migration create_newbatles_table
Created Migration: 2017_04_01_123343_create_newbatles_table

php artisan make:migration create_newbatles_table
[InvalidArgumentException]
A CreateNewbatlesTable migration already exists.

-----------File deleted by me--------------

php artisan make:migration create_newbatles_table
[ErrorException]
include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123343_create_newbatles_table.php): f
  ailed to open stream: No such file or directory

Why I can't recreate migrations with same name in Laravel 5.4?

Body:
Did you delete it from migration table too ?

If not please run

php artisan migrate:refresh

to refresh the table.
but be aware that in this way you will clean all the database tables!
so if you don't want to do so, just delete the migration from the database directly.


问:
Edit .gitconfig in Cloud9 IDE globally
A basic googling didn't yield many good results. If you are in a typical workspace, and open a terminal tab you can easily navigate back one directory and find the .gitconfig file.

The problem is, anything you do in there doesn't seem to persist to other workspaces; it only works for that local workspace.

Is there a way to set up configurations for Git globally?

答:
Create a new workspace and set up git the way you like it using git config --global . Also set up the rest of the environment the way you like to work.

Thereafter, to spin-up a new C9 workspace clone the one with your preferred environment. The new workspace will have your preferred settings.

If you change the settings after cloning these changes will not propagate across work spaces. But at least it is more convenient than setting up git configurations from scratch with each new workspace.

Title: Edit .gitconfig in Cloud9 IDE globally

ContentLicense: CC BY-SA 4.0


问:
How can I convert a BinaryExpression to Expression<Func<T, bool>>?
I have the following simple extension class

```<code>public static class ExpressionOrExtension
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression)
    {
        if (source == null)
            return expression;
        return Expression.Or(source, expression);
    }
}
</code>```

But Expression.Or returns a BinaryExpression - How can I get it to return an Expression<Func<T, bool>> instead?

This is how I am trying to consume the method, using Entity Framework

```<code>    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        Expression<Func<BookVerse, bool>> conditions = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            conditions = conditions.Or<BookVerse>(x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
        }
        return MyDbContext.BookVerses.Where(conditions);
    }
</code>```

答:
I used the LinqKit nuget package and implemented it like so...</p>

```<code>    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        var predicateBuilder = PredicateBuilder.New<BookVerse>();
        Expression<Func<BookVerse, bool>> predicate = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            Expression<Func<BookVerse, bool>> conditions = (x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
            predicate = predicateBuilder.Or(conditions);
        }
        return ObjectSpace.BookVerses.AsExpandable().Where(predicate);
    }
</code>```

Body:
I have the following simple extension class

public static class ExpressionOrExtension
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression)
    {
        if (source == null)
            return expression;
        return Expression.Or(source, expression);
    }
}

But Expression.Or returns a BinaryExpression - How can I get it to return an Expression<Func<T, bool>> instead?

This is how I am trying to consume the method, using Entity Framework

    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        Expression<Func<BookVerse, bool>> conditions = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            conditions = conditions.Or<BookVerse>(x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
        }
        return MyDbContext.BookVerses.Where(conditions);
    }

Body:
I used the LinqKit nuget package and implemented it like so...

    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        var predicateBuilder = PredicateBuilder.New<BookVerse>();
        Expression<Func<BookVerse, bool>> predicate = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            Expression<Func<BookVerse, bool>> conditions = (x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
            predicate = predicateBuilder.Or(conditions);
        }
        return ObjectSpace.BookVerses.AsExpandable().Where(predicate);
    }


问:
Android: Unable to display JSON Data, unknown reason
There is no error in the app, the logcat also does not show anything useful, the app doesn't crash, but, it also doesn't show anything. Here is the type of JSON response I'm receiving:

```<code>{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
    {
        "id": 1216615,
        "name": "Andrew Kreisberg",
        "profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
    },
    {
        "id": 211962,
        "name": "Geoff Johns",
        "profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
    }
],
"episode_run_time": [
    44
],
"first_air_date": "2014-10-07",
"genres": [
    {
        "id": 18,
        "name": "Drama"
    },
    {
        "id": 10765,
        "name": "Sci-Fi & Fantasy"
    }
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
    "en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
    {
        "id": 71,
        "name": "The CW"
    }
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
    "US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
    {
        "name": "Warner Bros. Television",
        "id": 1957
    },
    {
        "name": "DC Entertainment",
        "id": 9993
    },
    {
        "name": "Berlanti Productions",
        "id": 27711
    }
],
"seasons": [
    {
        "air_date": "2016-04-19",
        "episode_count": 5,
        "id": 79954,
        "poster_path": null,
        "season_number": 0
    },
    {
        "air_date": "2014-10-07",
        "episode_count": 23,
        "id": 60523,
        "poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
        "season_number": 1
    },
    {
        "air_date": "2015-10-06",
        "episode_count": 23,
        "id": 66922,
        "poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
        "season_number": 2
    },
    {
        "air_date": "2016-10-04",
        "episode_count": 19,
        "id": 77888,
        "poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
        "season_number": 3
    }
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}
</code>```

Here is a screenshot of what the app is displaying:
Click here to see the image

Please note that the main poster, backdrop and all the other things including the tabLayout are a part of the MainActivity, the viewPager consists of 5 fragments of which 2 work fine in this activity; one is supposed to work and is working when I use it with another activity but doesn't work here and the other two don't work at all.

The MainActivity is able to load the data fine. Before now, I was trying to send a Bundle from this activity to the rest fragments, but out of five, three turned out to be null, the rest two are still loading the data just fine. Now, I'm using a function in MainActivity which returns the data and then am using the getActivity() method in the fragments, I know that I won't be able to use these fragments anywhere else. Now, I've checked everything and the fragments are receiving the data, but even now, they aren't displaying anything. Here is the code parsing the JSON, I'm using a recyclerView, also I'm using Volley inside AsyncTask so that the default messgaes are displayed only when everything is set:

```<code>private class connectToTheInternet extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("receivedData", response);

                        try {
                            JSONObject parentObject = new JSONObject(response);
                            Log.d("receivedData", response);

                            JSONArray genreArray = parentObject.getJSONArray("genres");
                            for (int i = 0; i < genreArray.length(); i++) {
                                JSONObject tempObject = genreArray.getJSONObject(i);
                                if (i < genreArray.length() - 1) {
                                    genreCollector = genreCollector + tempObject.getString("name") + ", ";
                                } else
                                    genreCollector = genreCollector + tempObject.getString("name");
                            }
                            genre.setText(genreCollector);

                            if (genreArray.length() == 1) {
                                genreTag.setText("Genres: ");
                            } else
                                genreTag.setText("Genre: ");

                            JSONArray creatorArray = parentObject.getJSONArray("created_by");
                            for (int i = 0; i < creatorArray.length(); i++) {
                                JSONObject tempObject = creatorArray.getJSONObject(i);

                                if (i < creatorArray.length() - 1) {
                                    creatorName = creatorName + tempObject.getString("name") + ", ";
                                } else {
                                    creatorName = creatorName + tempObject.getString("name");
                                }
                            }
                            createdBy.setText(creatorName);

                            JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
                            int arrayLength = runTimeArray.length();

                            for (int i = 0; i < runTimeArray.length(); i++) {
                                //No need for a tempObject, as the values in this array don't have a 'key'.....
                                runTimeCollector += runTimeArray.getInt(i);
                            }
                            runTimeCollector = runTimeCollector / arrayLength;
                            runtime.setText(runTimeCollector);

                            numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
                            numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));

                            lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        runTimeTag.setText("RunTime:");
        numberOfSeasonsTag.setText("Number Of Seasons:");
        numberOfEpisodesTag.setText("Number Of Episodes:");
        lastAirDateTag.setText("Last Air Date:");
        createdByTag.setText("Created By:");
        overViewTag.setText("OVERVIEW:");
    }
}
</code>```

Here is the logcat trace:

```<code>    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:609)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at                                         com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Looper.loop(Looper.java:154)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
    04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
    04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms
</code>```

Please help as I'm new and don't know what to do.....

P.S. 'Credits' is the name of another java class that is supposed to display a list of all the celebrities acting in that particular movie. This isn't supposed to hinder the functioning of the other two classes that aren't displaying any data.

答:
The important bit seems to be org.json.JSONException: No value for credits. Are you trying to get a tag called credits (that doesn't exist in your JSON data)? If so, do a check like

```<code>if(jsonObject.has("credits")) {
    ...
}
</code>```

Body:
There is no error in the app, the logcat also does not show anything useful, the app doesn't crash, but, it also doesn't show anything. Here is the type of JSON response I'm receiving:

{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
    {
        "id": 1216615,
        "name": "Andrew Kreisberg",
        "profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
    },
    {
        "id": 211962,
        "name": "Geoff Johns",
        "profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
    }
],
"episode_run_time": [
    44
],
"first_air_date": "2014-10-07",
"genres": [
    {
        "id": 18,
        "name": "Drama"
    },
    {
        "id": 10765,
        "name": "Sci-Fi & Fantasy"
    }
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
    "en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
    {
        "id": 71,
        "name": "The CW"
    }
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
    "US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
    {
        "name": "Warner Bros. Television",
        "id": 1957
    },
    {
        "name": "DC Entertainment",
        "id": 9993
    },
    {
        "name": "Berlanti Productions",
        "id": 27711
    }
],
"seasons": [
    {
        "air_date": "2016-04-19",
        "episode_count": 5,
        "id": 79954,
        "poster_path": null,
        "season_number": 0
    },
    {
        "air_date": "2014-10-07",
        "episode_count": 23,
        "id": 60523,
        "poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
        "season_number": 1
    },
    {
        "air_date": "2015-10-06",
        "episode_count": 23,
        "id": 66922,
        "poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
        "season_number": 2
    },
    {
        "air_date": "2016-10-04",
        "episode_count": 19,
        "id": 77888,
        "poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
        "season_number": 3
    }
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}

Here is a screenshot of what the app is displaying:
Click here to see the image

Please note that the main poster, backdrop and all the other things including the tabLayout are a part of the MainActivity, the viewPager consists of 5 fragments of which 2 work fine in this activity; one is supposed to work and is working when I use it with another activity but doesn't work here and the other two don't work at all.

The MainActivity is able to load the data fine. Before now, I was trying to send a Bundle from this activity to the rest fragments, but out of five, three turned out to be null, the rest two are still loading the data just fine. Now, I'm using a function in MainActivity which returns the data and then am using the getActivity() method in the fragments, I know that I won't be able to use these fragments anywhere else. Now, I've checked everything and the fragments are receiving the data, but even now, they aren't displaying anything. Here is the code parsing the JSON, I'm using a recyclerView, also I'm using Volley inside AsyncTask so that the default messgaes are displayed only when everything is set:

private class connectToTheInternet extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("receivedData", response);

                        try {
                            JSONObject parentObject = new JSONObject(response);
                            Log.d("receivedData", response);

                            JSONArray genreArray = parentObject.getJSONArray("genres");
                            for (int i = 0; i < genreArray.length(); i++) {
                                JSONObject tempObject = genreArray.getJSONObject(i);
                                if (i < genreArray.length() - 1) {
                                    genreCollector = genreCollector + tempObject.getString("name") + ", ";
                                } else
                                    genreCollector = genreCollector + tempObject.getString("name");
                            }
                            genre.setText(genreCollector);

                            if (genreArray.length() == 1) {
                                genreTag.setText("Genres: ");
                            } else
                                genreTag.setText("Genre: ");

                            JSONArray creatorArray = parentObject.getJSONArray("created_by");
                            for (int i = 0; i < creatorArray.length(); i++) {
                                JSONObject tempObject = creatorArray.getJSONObject(i);

                                if (i < creatorArray.length() - 1) {
                                    creatorName = creatorName + tempObject.getString("name") + ", ";
                                } else {
                                    creatorName = creatorName + tempObject.getString("name");
                                }
                            }
                            createdBy.setText(creatorName);

                            JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
                            int arrayLength = runTimeArray.length();

                            for (int i = 0; i < runTimeArray.length(); i++) {
                                //No need for a tempObject, as the values in this array don't have a 'key'.....
                                runTimeCollector += runTimeArray.getInt(i);
                            }
                            runTimeCollector = runTimeCollector / arrayLength;
                            runtime.setText(runTimeCollector);

                            numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
                            numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));

                            lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        runTimeTag.setText("RunTime:");
        numberOfSeasonsTag.setText("Number Of Seasons:");
        numberOfEpisodesTag.setText("Number Of Episodes:");
        lastAirDateTag.setText("Last Air Date:");
        createdByTag.setText("Created By:");
        overViewTag.setText("OVERVIEW:");
    }
}

Here is the logcat trace:

    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:609)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at                                         com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Looper.loop(Looper.java:154)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
    04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
    04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms

Please help as I'm new and don't know what to do.....

P.S. 'Credits' is the name of another java class that is supposed to display a list of all the celebrities acting in that particular movie. This isn't supposed to hinder the functioning of the other two classes that aren't displaying any data.

Body:
The important bit seems to be org.json.JSONException: No value for credits. Are you trying to get a tag called credits (that doesn't exist in your JSON data)? If so, do a check like

if(jsonObject.has("credits")) {
    ...
}


问:
Setting Parameters.FLASH_MODE_TORCH doesn't work on Droid X 2.3
I am writing an app that sets the flash mode to torch.  I have been testing the application on my Droid X, and the LED light does not come on.  I tried it on a Droid Incredible and it worked fine.  I can't figure out what the problem is.  Here is part of my code for turning on torch mode.

```<code>    Camera mCamera = Camera.open();
    Camera.Parameters params = mCamera.getParameters();
    if(params.getFlashMode() != null){
        params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    }
    mCamera.setParameters(params);
</code>```

I have added mCamera.startPreview(); because I read that should make a difference, but it doesn't.  I also made a list of available flash modes and displayed them to the screen to make sure that my Droid X does have torch mode, and it was in the list.  I even created a new application from code I found online that turns the LED flash on and off with a button.  Again it worked fine on the Droid Incredible but not the Droid X.  Is there something I am missing to get this to run on the Droid X, or could it be something with Gingerbread?  The Droid X is running Gingerbread and the Droid Incredible is running FroYo.

答:
Refer to Issue 191453:</p>

```<code>SurfaceTexture mDummy = new SurfaceTexture(1); // any int argument will do
camera.setPreviewTexture(mDummy);
camera.startPreview();
</code>```

Body:
I am writing an app that sets the flash mode to torch.  I have been testing the application on my Droid X, and the LED light does not come on.  I tried it on a Droid Incredible and it worked fine.  I can't figure out what the problem is.  Here is part of my code for turning on torch mode.

    Camera mCamera = Camera.open();
    Camera.Parameters params = mCamera.getParameters();
    if(params.getFlashMode() != null){
        params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    }
    mCamera.setParameters(params);

I have added mCamera.startPreview(); because I read that should make a difference, but it doesn't.  I also made a list of available flash modes and displayed them to the screen to make sure that my Droid X does have torch mode, and it was in the list.  I even created a new application from code I found online that turns the LED flash on and off with a button.  Again it worked fine on the Droid Incredible but not the Droid X.  Is there something I am missing to get this to run on the Droid X, or could it be something with Gingerbread?  The Droid X is running Gingerbread and the Droid Incredible is running FroYo.

Body:
Refer to Issue 191453:

SurfaceTexture mDummy = new SurfaceTexture(1); // any int argument will do
camera.setPreviewTexture(mDummy);
camera.startPreview();


问:
Looping over child selectors
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

```<code><div id="checker">
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
</div>
</code>```

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

```<code>$('#checker').children('checkbox').each( function(){ .... });
</code>```

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

答:
If #checker is the id to your div then</p>

```<code>$("div#checker input:checkbox").each(function () { ... });
</code>```

ContentLicense: CC BY-SA 2.5

Title: Looping over child selectors

Body:
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

$('#checker').children('checkbox').each( function(){ .... });

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

Body:
If #checker is the id to your div then

$("div#checker input:checkbox").each(function () { ... });


问:
Turn off automatic color cycling during successive plot commands
I want to use the same color cycle when plotting two pandas dataframes whose columns are the same but represent a different experiment. For example,

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f1 = lambda x: (x/1)**2
f2 = lambda x: (x/2)**2
f3 = lambda x: (x/3)**2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x),
                     'f2': f2(x),
                     'f3': f3(x)})
exp2 = exp1 * 1.5

fig, ax = plt.subplots()

exp1.plot(ax=ax)
exp2.plot(ax=ax, style='--', legend=False)
</code>```

Gives a figure that looks like:

The second plot command continues where the color cycle left off after the first one. What is the best way to 'reset' the color cycle between successive plotting commands of pandas DataFrames?

答:
As well as the above mentioned answer, it's also worth mentioning that you can always choose your own custom colours, and then use that set for both plots.</p>

```<code>from itertools import cycle, islice

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f1 = lambda x: (x / 1) ** 2
f2 = lambda x: (x / 2) ** 2
f3 = lambda x: (x / 3) ** 2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x),
                     'f2': f2(x),
                     'f3': f3(x)})
exp2 = exp1 * 1.5

custom_colours = list(islice(cycle(["b", "g", "r", "c", "m", 'k']), None, len(exp1)))

fig, ax = plt.subplots()

exp1.plot(ax=ax, color=custom_colours)
exp2.plot(ax=ax, style='--', legend=False, color=custom_colours)
</code>```

Body:
I want to use the same color cycle when plotting two pandas dataframes whose columns are the same but represent a different experiment. For example,

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f1 = lambda x: (x/1)**2
f2 = lambda x: (x/2)**2
f3 = lambda x: (x/3)**2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x),
                     'f2': f2(x),
                     'f3': f3(x)})
exp2 = exp1 * 1.5

fig, ax = plt.subplots()

exp1.plot(ax=ax)
exp2.plot(ax=ax, style='--', legend=False)

Gives a figure that looks like:

The second plot command continues where the color cycle left off after the first one. What is the best way to 'reset' the color cycle between successive plotting commands of pandas DataFrames?

Body:
As well as the above mentioned answer, it's also worth mentioning that you can always choose your own custom colours, and then use that set for both plots.

from itertools import cycle, islice

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f1 = lambda x: (x / 1) ** 2
f2 = lambda x: (x / 2) ** 2
f3 = lambda x: (x / 3) ** 2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x),
                     'f2': f2(x),
                     'f3': f3(x)})
exp2 = exp1 * 1.5

custom_colours = list(islice(cycle(["b", "g", "r", "c", "m", 'k']), None, len(exp1)))

fig, ax = plt.subplots()

exp1.plot(ax=ax, color=custom_colours)
exp2.plot(ax=ax, style='--', legend=False, color=custom_colours)


问:
Is this factorial function from a C tutorial wrong?
I have a little programming experience in Python, and for the sake of curiosity I started to learn C, at least the very basics. In a tutorial, I found an example function for calculating a factorial, which is this:

```<code>int factorial(int x)
{
    int i;
    for(i=1; i < x; i++)
    {
        x *= i;
    }
    return x;
}
</code>```

I also added these lines in order to see the output:

```<code>#include <stdio.h>

int main()
{
    int val;
    val = factorial(5);
    printf("%d\n",val);
    return 0;
}
</code>```

Then I compiled the code with gcc factor.c -o factor.out, run and... ooops, the result is -1899959296, clearly there's something wrong.

After a couple of tries, using printf() to print both i and x, I figured out what went wrong (I think): since the condition of the for loop checks if the counter is less than x, and at each step x gets bigger and bigger, i is always less than x, so the loop keeps going on, presumably stopping when the value of x is too big (which should be related to int, I'm not very familiar yet with the various data types).

So, to "solve" the problem, I rewrote the function like this:

```<code>int factorial(int x)
{
    int counter = x;
    int number = x;
    int i;
    for (i=1; i < counter; i++)
    {
        number *= i;
    }
    return number;
}
</code>```

I compiled the program, run, and the value printed is 120, which is correct.

I searched a little bit for examples of factorial functions in C, and found many solutions much better than mine, taking into account negative numbers and formats like long and whatnot, but all of them, in a way or another, seem to rely on two "main" variables, much like my solution.

So, the final question: is the example proposed wrong, or am I missing something? This really bothers me, because if such a simple example is blatantly wrong, I should question the credibility of the rest.

答:
I think by putting loop condition i<=x and using another variable to store factorial will correct it.

Here is the example:

```<code>int factorial(int x)
{
    int i;
    int fact = 1; //store factorial
    for (i = 1; i <= x; i++)
    {
        fact *= i;
    }
    return fact;
}
</code>```

Or you can use recursive function

```<code>int factorial(int x) {
    if (x == 1)
        return 1;
    else
        return x * factorial(x - 1);
}
</code>```

Body:
I have a little programming experience in Python, and for the sake of curiosity I started to learn C, at least the very basics. In a tutorial, I found an example function for calculating a factorial, which is this:

int factorial(int x)
{
    int i;
    for(i=1; i < x; i++)
    {
        x *= i;
    }
    return x;
}

I also added these lines in order to see the output:

#include <stdio.h>

int main()
{
    int val;
    val = factorial(5);
    printf("%d\n",val);
    return 0;
}

Then I compiled the code with gcc factor.c -o factor.out, run and... ooops, the result is -1899959296, clearly there's something wrong.

After a couple of tries, using printf() to print both i and x, I figured out what went wrong (I think): since the condition of the for loop checks if the counter is less than x, and at each step x gets bigger and bigger, i is always less than x, so the loop keeps going on, presumably stopping when the value of x is too big (which should be related to int, I'm not very familiar yet with the various data types).

So, to "solve" the problem, I rewrote the function like this:

int factorial(int x)
{
    int counter = x;
    int number = x;
    int i;
    for (i=1; i < counter; i++)
    {
        number *= i;
    }
    return number;
}

I compiled the program, run, and the value printed is 120, which is correct.

I searched a little bit for examples of factorial functions in C, and found many solutions much better than mine, taking into account negative numbers and formats like long and whatnot, but all of them, in a way or another, seem to rely on two "main" variables, much like my solution.

So, the final question: is the example proposed wrong, or am I missing something? This really bothers me, because if such a simple example is blatantly wrong, I should question the credibility of the rest.

Body:
I think by putting loop condition i<=x and using another variable to store factorial will correct it.

Here is the example:

int factorial(int x)
{
    int i;
    int fact = 1; //store factorial
    for (i = 1; i <= x; i++)
    {
        fact *= i;
    }
    return fact;
}

Or you can use recursive function

int factorial(int x) {
    if (x == 1)
        return 1;
    else
        return x * factorial(x - 1);
}


问:
not sure why all text is being printed when specific template exists
I have a template element that is specific to listitems nodes.

xsl

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

  <xsl:output method="text"/>

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

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

xml

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="callvsapply.xslt"?>
<!-- sample XML snippet -->
<xml>
  <foo status="No">You are here.</foo>
  <bar status="Yes">Hello Bar!</bar>
  <baz status="No">Hello Baz!</baz>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>
</code>```

results

```<code>  You are here.
  Hello Bar!
  Hello Baz!
  Yes
  No
</code>```

Why does all text print? I expected just Yes and No.

答:
You have to first delete all elements that you don't need to print.

For this you can use this:

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

        <xsl:output method="text"/>

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

        <xsl:template match="node()|@*">
                <xsl:apply-templates/>
        </xsl:template>

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

Body:
I have a template element that is specific to listitems nodes.

xsl

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

  <xsl:output method="text"/>

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

</xsl:stylesheet>

xml

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="callvsapply.xslt"?>

<xml>
  <foo status="No">You are here.</foo>
  <bar status="Yes">Hello Bar!</bar>
  <baz status="No">Hello Baz!</baz>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>

results

  You are here.
  Hello Bar!
  Hello Baz!
  Yes
  No

Why does all text print? I expected just Yes and No.

Body:
You have to first delete all elements that you don't need to print.

For this you can use this:

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

        <xsl:output method="text"/>

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

        <xsl:template match="node()|@*">
                <xsl:apply-templates/>
        </xsl:template>

</xsl:stylesheet>


问:
Programmatically clear Python Interpreter window in Pyscripter?
Is there an API for controlling the PyScripter Python Interpreter window? I'd like basic control such as clearing the screen.

I'm aware of (and using) the option to Clear output before run, but I'm specifically looking for an option to achieve this programmatically.

I've tried using system calls to CLS but this doesn't work in the Python Interpreter window. I've also tried using ANSI escape codes but it looks like this too is not supported in the Python Interpreter window.

Another solution I've considered is printing a lot of newlines but this solution doesn't truly clear the screen.

Edit: Using another IDE/console/environment is not an option for me at this point.

答:
in shortcuts/interpreter/actClearContents = [shortcut-of-your-choice]
=> clear the console</p>


问:
Connection timeout on query on large table
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

```<code>SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);
</code>```

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

```<code>16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

Here is the code

```<code>public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}
</code>```

答: Add an index on the customerId column.

Body:
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Here is the code

public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}

Body: Add an index on the customerId column.


问:
Swift JSON Parsing Wunderground
i am a beginner with swift an Progrmamming i need values from the JSON it looks Like this:

```<code>{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "astronomy": 1
  }
    }
        ,   "moon_phase": {
        "percentIlluminated":"23",
        "ageOfMoon":"5",
        "phaseofMoon":"Erstes Viertel",
        "hemisphere":"North",
        "current_time": {
        "hour":"8",
        "minute":"28"
        },
        "sunrise": {
        "hour":"6",
        "minute":"55"
        },
        "sunset": {
        "hour":"19",
        "minute":"50"
        },
        "moonrise": {
        "hour":"9",
        "minute":"50"
        },
        "moonset": {
        "hour":"0",
        "minute":"06"
        }
    },
    "sun_phase": {
        "sunrise": {
        "hour":"6",
        "minute":"55"
        },
        "sunset": {
        "hour":"19",
        "minute":"50"
        }
    }
}
</code>```

i will get the hour & minute from sunset and sunrise to a variable!

my code :

```<code> var sunriseHour: [String] = []
    var sunriseMinute: [String] = []
    var sunsetHour: [String] = []
    var sunsetMinute: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let url=URL(string:"http://api.wunderground.com/api/dbd539bd631e/astronomy/lang:DL/q/DL/iphofen.json")
        do {
            let allData = try Data(contentsOf: url!)
            let data = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
            if let arrJSON = data["moon_phase"] {

                        if let sunriseData = arrJSON["sunrise"]{

                print(sunriseData)
                                        }
                if let sunsetData = arrJSON["sunset"]{

             print(sunsetData)
                }
           }
            print("hour: ",sunriseHour)
            print("minute: ",sunriseMinute)
            print("hour: ",sunsetHour)
            print("minute: ",sunsetMinute)

        }
        catch {

        }

            }
</code>```

i get with print(sunriseData) and print(sunsetData) the right data from this :

Optional({
      hour = 6;
      minute = 55; }) Optional({
      hour = 19;
      minute = 50; }) hour:  [] minute:  [] hour:  [] minute:  []

How do i get it in the variable sunriseHour, sunriseMinute, sunsetHour, sunsetMinute..

thanks from your help..!

答:
All hour and minute values are (single) String not [String] (array).

Declare all variables as empty strings

```<code>var sunriseHour = ""
var sunriseMinute = ""
var sunsetHour = ""
var sunsetMinute = ""
</code>```

Then do not load data synchronously from a remote URL, use always an asynchronous way:

```<code>       let url = URL(string:"http://api.wunderground.com/api/dbd539bd631e/astronomy/lang:DL/q/DL/iphofen.json")!

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
            } else {
                do {
                    guard let jsonData = try JSONSerialization.jsonObject(with:data!) as? [String:Any],
                          let moonPhase = jsonData["moon_phase"] as? [String:Any] else { return }

                    let sunrise = moonPhase["sunrise"] as! [String:String]
                    let sunset = moonPhase["sunset"] as! [String:String]

                    sunriseHour = sunrise["hour"]!
                    sunriseMinute = sunrise["minute"]!

                    sunsetHour = sunset["hour"]!
                    sunsetMinute = sunset["minute"]!

                    print("Sunrise - \(sunriseHour):\(sunriseMinute)"
                    print("Sunset - \(sunsetHour):\(sunsetMinute)"

                } catch {
                    print(error)
                }
            }
        }
        task.resume()
</code>```

The data for sunrise and sunset are in dictionaries derived from moon_phase. All values are forced unwrapped because sunrise and sunset are supposed to exist every day ;-)

PS : Consider to define more descriptive variable names, arrJSON is not very meaningful.

Title: Swift JSON Parsing Wunderground

Body:
i am a beginner with swift an Progrmamming i need values from the JSON it looks Like this:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "astronomy": 1
  }
    }
        ,   "moon_phase": {
        "percentIlluminated":"23",
        "ageOfMoon":"5",
        "phaseofMoon":"Erstes Viertel",
        "hemisphere":"North",
        "current_time": {
        "hour":"8",
        "minute":"28"
        },
        "sunrise": {
        "hour":"6",
        "minute":"55"
        },
        "sunset": {
        "hour":"19",
        "minute":"50"
        },
        "moonrise": {
        "hour":"9",
        "minute":"50"
        },
        "moonset": {
        "hour":"0",
        "minute":"06"
        }
    },
    "sun_phase": {
        "sunrise": {
        "hour":"6",
        "minute":"55"
        },
        "sunset": {
        "hour":"19",
        "minute":"50"
        }
    }
}

i will get the hour & minute from sunset and sunrise to a variable!

my code :

 var sunriseHour: [String] = []
    var sunriseMinute: [String] = []
    var sunsetHour: [String] = []
    var sunsetMinute: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let url=URL(string:"http://api.wunderground.com/api/dbd539bd631e/astronomy/lang:DL/q/DL/iphofen.json")
        do {
            let allData = try Data(contentsOf: url!)
            let data = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
            if let arrJSON = data["moon_phase"] {

                        if let sunriseData = arrJSON["sunrise"]{

                print(sunriseData)
                                        }
                if let sunsetData = arrJSON["sunset"]{

             print(sunsetData)
                }
           }
            print("hour: ",sunriseHour)
            print("minute: ",sunriseMinute)
            print("hour: ",sunsetHour)
            print("minute: ",sunsetMinute)

        }
        catch {

        }

            }

i get with print(sunriseData) and print(sunsetData) the right data from this :

Optional({
      hour = 6;
      minute = 55; }) Optional({
      hour = 19;
      minute = 50; }) hour:  [] minute:  [] hour:  [] minute:  []

How do i get it in the variable sunriseHour, sunriseMinute, sunsetHour, sunsetMinute..

thanks from your help..!

Body:
All hour and minute values are (single) String not [String] (array).

Declare all variables as empty strings

var sunriseHour = ""
var sunriseMinute = ""
var sunsetHour = ""
var sunsetMinute = ""

Then do not load data synchronously from a remote URL, use always an asynchronous way:

       let url = URL(string:"http://api.wunderground.com/api/dbd539bd631e/astronomy/lang:DL/q/DL/iphofen.json")!

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
            } else {
                do {
                    guard let jsonData = try JSONSerialization.jsonObject(with:data!) as? [String:Any],
                          let moonPhase = jsonData["moon_phase"] as? [String:Any] else { return }

                    let sunrise = moonPhase["sunrise"] as! [String:String]
                    let sunset = moonPhase["sunset"] as! [String:String]

                    sunriseHour = sunrise["hour"]!
                    sunriseMinute = sunrise["minute"]!

                    sunsetHour = sunset["hour"]!
                    sunsetMinute = sunset["minute"]!

                    print("Sunrise - \(sunriseHour):\(sunriseMinute)"
                    print("Sunset - \(sunsetHour):\(sunsetMinute)"

                } catch {
                    print(error)
                }
            }
        }
        task.resume()

The data for sunrise and sunset are in dictionaries derived from moon_phase. All values are forced unwrapped because sunrise and sunset are supposed to exist every day ;-)

PS : Consider to define more descriptive variable names, arrJSON is not very meaningful.


问:
How to initialize a 2d array and how to access it from a main method in java?
The 2d array created overwrites the previously created 2d array each time the loop continues, how can I create a seperate 2d array and access/change it in the way listed below.

I'm currently a highschool student taking an online computer sciences course and would like to improve my efficiency with coding and get some tips on bad habbits I have. Here is my program:

```<code>import java.util.Arrays;
import java.util.Scanner;

public class FundRaising
{

    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Would you like to input donation information regarding the selected schools?\n0 - Yes\n1 - No"); //runs the program or ends the program
        Integer loop = scanner.nextInt();

        while (loop == 0) //while the user would like to run the program, the code will look
            {
            if (loop == 0) //continues if the user would like to continue
                {
                System.out.println("Which school is fundraising?\n0 - Central\n1 - Holy Cross\n2 - John Paul II\n3 - Teresa\n4 - Regina\n5 - Joeseph\n6 - Mary\n7 - Thomas Aquinas");
                Integer school = scanner.nextInt(); //asks which school information will be input for

                System.out.println("Amount donated?\n0 - 25 cents\n1 - 50 cents\n2 - 1 dollar\n3 - 2 dollars");
                Integer donation = scanner.nextInt(); //asks the amount donated

                System.out.println("School population?");
                Integer population = scanner.nextInt(); //asks the population of the school

                if (donation == 0) //if the first donation amount is selected then this selection will be used
                    {
                    double schoolTotal = 0.25*population; //the donation amount times the population gives the total for the school selected
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total"); //prints out headers for the 2d array

                    int rows = 4; //set the initial size of the 2d array according to schools and donations
                    int columns = 10;
                    double totals [][] = new double [rows][columns]; //initialize the 2d array
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5; //set various positions on the 2d array to equal the donation amounts
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal; //set the positions corredsponding to the input school and donation in order to create a "total" column on the 2d array
                    totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7]; //the sums of everything in the row is used to find a value for the total column

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9]; //adds the total for each school in the total column to create a final total for donations

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n ")); //prints out the 2d array with slight modifications for easier viewing
                    System.out.println("\nTotals donations:" + finalDonations +""); //prints the total amount of donations to the user

                    }

                if (donation == 1) //each subsequence if statement is used if the donation amount differs (4 different donations amounts, 25 cents, 50 cents, 1 dollar and 2 dollars
                    { //remainder of code is drycut paste with small modifications to adjust for differing donation amount
                    double schoolTotal = 0.50*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[1][0]+totals[1][1]+totals[1][2]+totals[1][3]+totals[1][4]+totals[1][5]+totals[1][6]+totals[1][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 2)
                    {
                    double schoolTotal = 1.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[2][0]+totals[2][1]+totals[2][2]+totals[2][3]+totals[2][4]+totals[2][5]+totals[2][6]+totals[2][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 3)
                    {
                    double schoolTotal = 2.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[3][0]+totals[3][1]+totals[3][2]+totals[3][3]+totals[3][4]+totals[3][5]+totals[3][6]+totals[3][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                }

            else //if the user did not chose to run the program this message is displayed
                {
                        System.out.println("You did not not choose to input information");
                }

            }

    }
}
</code>```

答:
I don't really understand what your question is, but i recommend you to start using for loops instead of code repetition.

lines like this:

totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7];

should be replaced by:

```<code>for(int i=0; i<8; i++) (or i<totals[0].length if you want to run on all the cells)
    totals[donation][9]+=totals[0][i];
</code>```

Body:
The 2d array created overwrites the previously created 2d array each time the loop continues, how can I create a seperate 2d array and access/change it in the way listed below.

I'm currently a highschool student taking an online computer sciences course and would like to improve my efficiency with coding and get some tips on bad habbits I have. Here is my program:

import java.util.Arrays;
import java.util.Scanner;

public class FundRaising
{

    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Would you like to input donation information regarding the selected schools?\n0 - Yes\n1 - No"); //runs the program or ends the program
        Integer loop = scanner.nextInt();

        while (loop == 0) //while the user would like to run the program, the code will look
            {
            if (loop == 0) //continues if the user would like to continue
                {
                System.out.println("Which school is fundraising?\n0 - Central\n1 - Holy Cross\n2 - John Paul II\n3 - Teresa\n4 - Regina\n5 - Joeseph\n6 - Mary\n7 - Thomas Aquinas");
                Integer school = scanner.nextInt(); //asks which school information will be input for

                System.out.println("Amount donated?\n0 - 25 cents\n1 - 50 cents\n2 - 1 dollar\n3 - 2 dollars");
                Integer donation = scanner.nextInt(); //asks the amount donated

                System.out.println("School population?");
                Integer population = scanner.nextInt(); //asks the population of the school

                if (donation == 0) //if the first donation amount is selected then this selection will be used
                    {
                    double schoolTotal = 0.25*population; //the donation amount times the population gives the total for the school selected
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total"); //prints out headers for the 2d array

                    int rows = 4; //set the initial size of the 2d array according to schools and donations
                    int columns = 10;
                    double totals [][] = new double [rows][columns]; //initialize the 2d array
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5; //set various positions on the 2d array to equal the donation amounts
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal; //set the positions corredsponding to the input school and donation in order to create a "total" column on the 2d array
                    totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7]; //the sums of everything in the row is used to find a value for the total column

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9]; //adds the total for each school in the total column to create a final total for donations

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n ")); //prints out the 2d array with slight modifications for easier viewing
                    System.out.println("\nTotals donations:" + finalDonations +""); //prints the total amount of donations to the user

                    }

                if (donation == 1) //each subsequence if statement is used if the donation amount differs (4 different donations amounts, 25 cents, 50 cents, 1 dollar and 2 dollars
                    { //remainder of code is drycut paste with small modifications to adjust for differing donation amount
                    double schoolTotal = 0.50*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[1][0]+totals[1][1]+totals[1][2]+totals[1][3]+totals[1][4]+totals[1][5]+totals[1][6]+totals[1][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 2)
                    {
                    double schoolTotal = 1.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[2][0]+totals[2][1]+totals[2][2]+totals[2][3]+totals[2][4]+totals[2][5]+totals[2][6]+totals[2][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                if (donation == 3)
                    {
                    double schoolTotal = 2.00*population;
                    System.out.println("  Cen Cross Paul Trsa Rgna Joes Mary Tom  Amnt Total");

                    int rows = 4;
                    int columns = 10;
                    double totals [][] = new double [rows][columns];
                    totals[0][8] = 0.25;
                    totals[1][8] = 0.5;
                    totals[2][8] = 1.00;
                    totals[3][8] = 2.00;
                    totals[donation][school] = schoolTotal;
                    totals[donation][9] = totals[3][0]+totals[3][1]+totals[3][2]+totals[3][3]+totals[3][4]+totals[3][5]+totals[3][6]+totals[3][7];

                    double finalDonations = totals[0][9]+totals[1][9]+totals[2][9]+totals[3][9];

                    System.out.print(Arrays.deepToString(totals).replace("], ", "]\n "));
                    System.out.println("\nTotals donations:" + finalDonations +"");

                    }

                }

            else //if the user did not chose to run the program this message is displayed
                {
                        System.out.println("You did not not choose to input information");
                }

            }

    }
}

Body:
I don't really understand what your question is, but i recommend you to start using for loops instead of code repetition.

lines like this:

totals[donation][9] = totals[0][0]+totals[0][1]+totals[0][2]+totals[0][3]+totals[0][4]+totals[0][5]+totals[0][6]+totals[0][7];

should be replaced by:

for(int i=0; i<8; i++) (or i<totals[0].length if you want to run on all the cells)
    totals[donation][9]+=totals[0][i];


问:
X is not a function
I know the answer must be silly for you but I have just started javascript to do functions with firebase and I block on my script even after reading several questions with the same problem here (stackoverflow).

When running my script tells me:

```<code>TypeError: d.getFullYear is not a function
at Date.sameDay (/user_code/index.js:36:41)
at /user_code/index.js:61:33
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
</code>```

"

```<code>exports.sendNotificationToNewUser = functions.https.onRequest((request, response) => {

    // Enable logging
    // admin.database.enableLogging(true);

    Date.prototype.sameDay = function(d) {
        return this.getFullYear() === d.getFullYear()
        && this.getDate() === d.getDate()
        && this.getMonth() === d.getMonth();
    }

    // Loop through users in order with the forEach() method. The callback
    // provided to forEach() will be called synchronously with a DataSnapshot
    // for each child:
    var query = admin.database().ref("users").orderByKey();
    var defaultAuth = admin.auth();
    query.once("value")
    .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
            // user will be "ada" the first time and "alan" the second time
            var user_id = childSnapshot.key;
            // childData will be the actual contents of the child
            var user_data = childSnapshot.val();

            console.log(user_id);

            admin.auth().getUser(user_id)
            .then(function(userRecord) {
                var create_date = userRecord.metadata.createdAt
                console.log("Creation date:", create_date);
                create_date.setDate(create_date.getDate()+4);
                if (create_date.sameDay(Date.now())) {
                    //things
                }
            });
        });
    });
    response.send("OK");
})
</code>```

答:
The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Here you're calling .sameDay() with a number

```<code>if (create_date.sameDay(Date.now())) {
    //things
}
</code>```

But your function expects a date object.
Change Date.now() to new Date()

```<code>if (create_date.sameDay(new Date())) {
    //things
}
</code>```

Title: X is not a function

Body:
I know the answer must be silly for you but I have just started javascript to do functions with firebase and I block on my script even after reading several questions with the same problem here (stackoverflow).

When running my script tells me:

TypeError: d.getFullYear is not a function
at Date.sameDay (/user_code/index.js:36:41)
at /user_code/index.js:61:33
at process._tickDomainCallback (internal/process/next_tick.js:129:7)

"

exports.sendNotificationToNewUser = functions.https.onRequest((request, response) => {

    // Enable logging
    // admin.database.enableLogging(true);

    Date.prototype.sameDay = function(d) {
        return this.getFullYear() === d.getFullYear()
        && this.getDate() === d.getDate()
        && this.getMonth() === d.getMonth();
    }

    // Loop through users in order with the forEach() method. The callback
    // provided to forEach() will be called synchronously with a DataSnapshot
    // for each child:
    var query = admin.database().ref("users").orderByKey();
    var defaultAuth = admin.auth();
    query.once("value")
    .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
            // user will be "ada" the first time and "alan" the second time
            var user_id = childSnapshot.key;
            // childData will be the actual contents of the child
            var user_data = childSnapshot.val();

            console.log(user_id);

            admin.auth().getUser(user_id)
            .then(function(userRecord) {
                var create_date = userRecord.metadata.createdAt
                console.log("Creation date:", create_date);
                create_date.setDate(create_date.getDate()+4);
                if (create_date.sameDay(Date.now())) {
                    //things
                }
            });
        });
    });
    response.send("OK");
})

Body:
The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Here you're calling .sameDay() with a number

if (create_date.sameDay(Date.now())) {
    //things
}

But your function expects a date object.
Change Date.now() to new Date()

if (create_date.sameDay(new Date())) {
    //things
}


问:
C Pipe between a parent and 2 children
I can not figure out why only 1 child sends data to parent (only the 1st child)..
When I do sleep(5) after the child1 sends data through pipe to parent then the 2nd child sends the same prime number to the parent.

Can someone help me?

//--------------------------Consts---------------------------------
#define NUM_OF_CHILDS 2
#define N 20
#define WIN 5

struct msg{
 pid_t _pid;
 int _prime;
};

//--------------------------Prototypes-----------------------------
bool is_prime(int num);
void terminate(pid_t child_pid[],int fd[2]);
void do_child(int fd[2]);
void print_pair(const int f_arr[],const int s_arr[]);

//--------------------------Main-------------------------------------
int main()
{
 int f_arr[N] = {0},
  s_arr[N] = {0},
  ind, //running on children fork
  count1 = 0,
  count2 = 0,
  victory1 = 0,
  victory2 = 0,
  min = 0;

 int fd[2];

 bool read1 = false,
  read2 = false;

 srand((unsigned)time(NULL));
 pid_t child_pid [NUM_OF_CHILDS];//children pid status array

 struct msg msg1;

 if (pipe(fd) == -1)//pipe fd
 {
  perror("cannot open pipe");
  exit(EXIT_FAILURE);
 }

 for(ind = 0; ind < NUM_OF_CHILDS; ind++)
 {
  child_pid[ind] = fork();// duplicate the current process

  if (child_pid[ind] < 0)//fork failed
  {
   perror("Cannot fork()");
   exit(EXIT_FAILURE);
  }

  if(child_pid[ind] == 0)/* child : sends message to parent*/
   do_child(fd);
 }

 /* parent : receives message from child */
 close(fd[1]); // close the write-end of the pipe

 //read data from pipe
 while(read(fd[0],&msg1,sizeof(struct msg)) > 0)
 {
  if(child_pid[0] == msg1._pid)
  {
   f_arr[count1++] = msg1._prime;
   read1 = true;
  }

  else
  {
   s_arr[count2++] = msg1._prime;
   read2 = true;
  }

  if(read1 && read2)
  {
   if(f_arr[min] > s_arr[min])
    victory1++;
   else if(f_arr[min] < s_arr[min])
    victory2++;

   read1 = false;
   read2 = false;
   min++;
  }

  if(victory1 == WIN || victory2 == WIN)
   terminate(child_pid,fd);
 }

 close(fd[0]);// close the read-end of the pipe
 print_pair(f_arr,s_arr);

 return EXIT_SUCCESS ;
}
//---------------------------------------------------------------------
//checking if number is a prime number or not
//and return true or false
bool is_prime(int num)
{
 int i;
 if(num==0 || num==1 || num==2)
  return false;
 for(i=2;i<=num/2;i++)
 {
  //the number is not prime
  if(num%i == 0)
   return false;
 }
 //the number is prime
 return true;
}
//----------------------------------------------------------------
void do_child(int fd[2])
{
 struct msg message;
 int num;

 close(fd[0]);

 while (1)
 {
  num = rand() % 1000;
  if(is_prime(num))
  {
   message._prime = num;
   message._pid = getpid();
   write(fd[1], &message, sizeof(struct msg));
  }
 }
}
//----------------------------------------------------------------
void terminate(pid_t child_pid[],int fd[2])
{
 int ind,
 loop;

 for(ind = 0; ind < NUM_OF_CHILDS; ind++)
 {
  close(fd[1]);
  //first to give the process an opportunity to die gratefully before
  //using SIGKILL
  kill(child_pid[ind], SIGTERM);
  bool died = false;
  //It will give the process 5 seconds to die gracefully
  for (loop = 0; loop < 5 && !died; ++loop)
  {
   int pid;
   //the time the child process takes to close down gracefully.
   sleep(1);
   //to get the return status of that process and prevent zombie processes.
   if (waitpid(child_pid[ind], &pid, WNOHANG) == child_pid[ind])
    died = true;
  }
  //if SIGTERM did not killed the child do SIGKILL
  if (!died)
  {
   int pid;
   kill(child_pid[ind], SIGKILL);
   waitpid(child_pid[ind], &pid, 0);// harvest the zombie
  }

 }
}
//------------------------------------------------------------------
void print_pair(const int f_arr[],const int s_arr[])
{
 int ind;
 for(ind = 0; ind < N; ind++)
 {
  if(f_arr[ind] == 0 && s_arr[ind] == 0)
   break;
  printf("(%d,%d)\n",f_arr[ind],s_arr[ind]);
 }
}```

答:
First, the two child processes are generating the same pseudorandom sequence because they're starting with the same seed. To have any chance of different numbers, you need to seed them after the fork, and probably use something that changes more than once per second (the chance of the two of them having different values of time() is very small even if you moved the srand(time(NULL)) after the fork).

Second, you are receiving all the numbers from the first process because it has a head start. There's plenty of time to write to the pipe while the second process is being created. The parent doesn't start reading until after both children are created, so the first child fills the pipe buffer and then blocks. Pipe buffers are at least a few kilobytes.

Even when I slowed down the child process by making it print the numbers to stderr, the first one still generated hundreds of numbers before the second one got going.

So what happens in your main loop when there are hundreds of messages arriving from child 1 and none from child 2? Your f_arr array overflows because it only has room for 20. After that, anything can happen.

The simplest way to prevent that would be to check whether count1 == N before attempting to store a number into f_arr[count1++], and if so, just continue; to the next message. You should do the same for messages from the second child, even though it's not likely to happen.

This way you'll be accepting at most N messages from each child, and ignoring the rest. You'll need to add another end condition to the main loop: if both children have sent N messages, you need to stop.

Another way to go would be to use a separate pipe for each child and alternate reading from both pipes to keep them synchronized, but I have a feeling you were deliberately avoiding that.

Title: C Pipe between a parent and 2 children


问:
How to get coordinates of a button in a browser?
I am looking for a way to get the coordinates of e.g. a button in a browser.
Thanks in advance. </p>

答:
you need to use as following code to get Co-ordinates of the button.

```<code><input type="button" id="button" value="display" onclick="getCoords()">
<script>
    function getCoords() {
        var mainEvent = event ? event : window.event;

        alert("This button click occurred at: X(" + mainEvent.screenX + ")
            and Y(" + mainEvent.screenY +       ")");
    }
</script>
</code>```

Here is the working example:http://jsfiddle.net/Bnuy7/1692/

Body:
you need to use as following code to get Co-ordinates of the button.

<input type="button" id="button" value="display" onclick="getCoords()">
<script>
    function getCoords() {
        var mainEvent = event ? event : window.event;

        alert("This button click occurred at: X(" + mainEvent.screenX + ")
            and Y(" + mainEvent.screenY +       ")");
    }
</script>

Here is the working example:http://jsfiddle.net/Bnuy7/1692/


问:
how to remove fragment over an activity layout
I am really new to android development. I have created a simple main activity and add an icon on top left. Clicking it I can show a  blank fragment.on my screen replacing a layout which is loaded in onCreate method.  Now clicking  another icon I want to hide that fragment and load that layout again. How to do that?? any helps??
Below is  my code</p>

```<code> //part of oncreate where my layout is loaded
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            }

     // part of code when icon clicked and fragment is loaded
             FragmentManager fragmentManager = getFragmentManager();
             FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               BlankFragment  frag = new BlankFragment();
             fragmentTransaction.replace(R.id.content_main, frag);
                        fragmentTransaction.commit();

                        //another nearby icon clicked
    //now i want to replace this fragment from content_main layout

    //what code to add??
</code>```

答:
You can toggle visibilty by below code.</p>

```<code>public void toggleVisibility(Fragment fragment){

    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    if (fragment.isHidden()) {
        transaction.show(fragment);
    } else {
        transaction.hide(fragment);
    }

    transaction.commit();
}
</code>```

Body:
I am really new to android development. I have created a simple main activity and add an icon on top left. Clicking it I can show a  blank fragment.on my screen replacing a layout which is loaded in onCreate method.  Now clicking  another icon I want to hide that fragment and load that layout again. How to do that?? any helps??
Below is  my code

 //part of oncreate where my layout is loaded
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            }

     // part of code when icon clicked and fragment is loaded
             FragmentManager fragmentManager = getFragmentManager();
             FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               BlankFragment  frag = new BlankFragment();
             fragmentTransaction.replace(R.id.content_main, frag);
                        fragmentTransaction.commit();

                        //another nearby icon clicked
    //now i want to replace this fragment from content_main layout

    //what code to add??

Body:
You can toggle visibilty by below code.

public void toggleVisibility(Fragment fragment){

    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    if (fragment.isHidden()) {
        transaction.show(fragment);
    } else {
        transaction.hide(fragment);
    }

    transaction.commit();
}


问:
Maven Web Project + Tomcat + jRebel
I just bought a license and I am having problems to setup the jRebel.

My project is a Java Web Maven Project
Product Version:
NetBeans IDE 8.1 (Build 201510222201)
Updates: NetBeans IDE is updated to version NetBeans 8.1 Patch 1
Java: 1.8.0_74; Java HotSpot(TM) 64-Bit Server VM 25.74-b02
Runtime: Java(TM) SE Runtime Environment 1.8.0_74-b02
System: Mac OS X version 10.11.4 running on x86_64; UTF-8; en_US (nb)

Frameworks: Spring 4.2.5 + Hibernate + Tomcat 7 via Maven

The problem
I already followed these links below:
http://zeroturnaround.com/software/jrebel/quickstart/netbeans/
http://manuals.zeroturnaround.com/jrebel/standalone/maven.html

The situation:

My project uses tomcat maven plugin, so, I don’t need to have installed the tomcat server locally on my NetBeans IDE.

There is only one case the jRebel works fine, disabling tomcat maven plugin and install locally apache tomcat.

What else should I do ?

I need to use the jRebel with maven tomcat plugin.

答:
You can easily run your embedded tomcat plugin by making two small changes:

1) Add Jrebel maven Plugin to your project so it takes care of generating the required "rebel.xml" file.

2) Add Jrebel to you JVM options using this line:

```<code>export JAVA_OPTIONS="-agentpath:{JRebel root folder}/lib/libjrebel64.so $JAVA_OPTIONS"
</code>```

in Windows

```<code>export JAVA_OPTIONS="-agentpath:{JRebel root folder}/lib/libjrebel64.dylib $JAVA_OPTIONS"
</code>```

(or you may want 32 bit of course)

and then run your tomcat as usual like mvn tomcat7:run

While tomcat is running. if you compile your code, new changes will be hot deployed and for static resources you don't need to do something.

Title: Maven Web Project + Tomcat + jRebel

Body:
You can easily run your embedded tomcat plugin by making two small changes:

1) Add Jrebel maven Plugin to your project so it takes care of generating the required "rebel.xml" file.

2) Add Jrebel to you JVM options using this line:

export JAVA_OPTIONS="-agentpath:{JRebel root folder}/lib/libjrebel64.so $JAVA_OPTIONS"

in Windows

export JAVA_OPTIONS="-agentpath:{JRebel root folder}/lib/libjrebel64.dylib $JAVA_OPTIONS"

(or you may want 32 bit of course)

and then run your tomcat as usual like mvn tomcat7:run

While tomcat is running. if you compile your code, new changes will be hot deployed and for static resources you don't need to do something.