问:
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>```

答:
You actually create new array each loop iteration.

Just move this part

```<code>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
</code>```

to the main method, just after the Scanner scanner = new Scanner(System.in); , and erase it from inside the loop, so the donation values for previous schools don't get overwritten the next time.

Then, if you want the sum of the donation increase you should change the

totals[donation][school] = schoolTotal; to

```<code>totals[donation][school] = totals[donation][school] + schoolTotal;
</code>```

or else leave it as is.

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:
You actually create new array each loop iteration.

Just move this part

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

to the main method, just after the Scanner scanner = new Scanner(System.in); , and erase it from inside the loop, so the donation values for previous schools don't get overwritten the next time.

Then, if you want the sum of the donation increase you should change the

totals[donation][school] = schoolTotal; to

totals[donation][school] = totals[donation][school] + schoolTotal;

or else leave it as is.


来源: stackexchange

问:
What exactly does this WSO2 ESB echo endpoint?
I am very new in WSO2 and I have the following doubt related to an ESB project on which I am working.

In this ESB application I am sending a message to a named endopoint mediator, something like this:

```<code><send>
    <endpoint key="echoEndpoint"/>
</send>
</code>```

This is the contend of the related echoEndpoint.xml file in my project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<endpoint name="echoEndpoint" xmlns="http://ws.apache.org/ns/synapse">
    <address format="soap11" statistics="enable" trace="enable" uri="http://localhost:8280/services/echo"/>
</endpoint>
</code>```

So what exactly does this endpoint? The http://localhost:8280/services/echo is something like a predefined endopoined provided natively by WSO2? or what?

答:
echo service included into esb/ei by default. You can see it in Carbon Panel -> Main -> Manage -> Services. There you can test it via "Try It" feature. It has few methods:

echoInt extected to get integer as argument and returned same integer value

echoString - expected to get string value as argument and returned same value

echoOMElement - received XML as argument and returned same XML

and some other methods. General idea - this service returned same value as it is received.

This service is helpful for testing purposes.

ContentLicense: CC BY-SA 3.0

Body:
I am very new in WSO2 and I have the following doubt related to an ESB project on which I am working.

In this ESB application I am sending a message to a named endopoint mediator, something like this:

<send>
    <endpoint key="echoEndpoint"/>
</send>

This is the contend of the related echoEndpoint.xml file in my project:

<?xml version="1.0" encoding="UTF-8"?>
<endpoint name="echoEndpoint" xmlns="http://ws.apache.org/ns/synapse">
    <address format="soap11" statistics="enable" trace="enable" uri="http://localhost:8280/services/echo"/>
</endpoint>

So what exactly does this endpoint? The http://localhost:8280/services/echo is something like a predefined endopoined provided natively by WSO2? or what?


问:
Element-wise addition of 2 lists?
I have now:

```<code>list1 = [1, 2, 3]
list2 = [4, 5, 6]
</code>```

I wish to have:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]
```

Simply an element-wise addition of two lists.

I can surely iterate the two lists, but I don't want do that.

What is the most Pythonic way of doing so?

答:
Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

```<code># Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]
</code>```

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).

ContentLicense: CC BY-SA 4.0

Title: Element-wise addition of 2 lists?

Body:
I have now:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

I wish to have:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

Simply an element-wise addition of two lists.

I can surely iterate the two lists, but I don't want do that.

What is the most Pythonic way of doing so?

Body:
Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).


问:
Can sprintf / formatted strings be passed directly to a function?
Is something like this allowed in C++? If so, how do I do it?

```<code>myFunction("User input: %s", a);
</code>```

Or is the only way to format it first and then pass it?

答:
I guess what you want is to call a function like vsprintf from your myFunction - this way you can do the formatting inside of your function. Example:</p>

```<code>void myFunction(const char *format, ...)
{
  char buf[1024];

  va_list arglist;
  va_start( arglist, format );
  vsprintf(buf,format,arglist);
  va_end( arglist );
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is something like this allowed in C++? If so, how do I do it?

myFunction("User input: %s", a);

Or is the only way to format it first and then pass it?

Body:
I guess what you want is to call a function like vsprintf from your myFunction - this way you can do the formatting inside of your function. Example:

void myFunction(const char *format, ...)
{
  char buf[1024];

  va_list arglist;
  va_start( arglist, format );
  vsprintf(buf,format,arglist);
  va_end( arglist );
}


问:
What is UWP analog for Application.StartupPath?
This is my first experience with UWP and currently I porting my WinForms C# app to UWP, so I can use it on my phone.
My app using two files that I store near with it's exe: the PNG and text file. I accessed these with use of Application.StartupPath + "\\my.png" and etc. How I can do the same in UWP?

答: you cant write files in the application package folder (path where the appx is deployed). You can use ApplicationData class to storage files.</p>


问:
Is it possible write a gulpfile in es6?
Question: How can I write my gulp file in ES6 so I can use import instead of require and use => syntax over function()?

I can use io.js or node any version.

gulpfile.js:

```<code>import gulp from "./node_modules/gulp/index.js";
gulp.task('hello-world', =>{
    console.log('hello world');
});
</code>```

Errors:

```<code>import gulp from "./node_modules/gulp/index.js";
^^^^^^
SyntaxError: Unexpected reserved word
</code>```

```<code>gulp.task('hello-world', =>{
                         ^^
SyntaxError: Unexpected token =>
</code>```

Inside the node_modules/gulp/bin/gulp.js i've changed the first line to #!/usr/bin/env node --harmony as asked in this stack

答:
Basically, what you need to install using npm is gulp, gulp-babel and babel-resent-env, add "env" to your .babelrc presets array, and use a gulpfile.babel.js file.

```<code>npm install gulp-babel --save-dev
</code>```

Some of the answers mentioned babel-core, babel-preset-es2015, etc. The Babel official setup guide with Gulp is to use gulp-babel only, while gulp-babel has dependencies modules including babel-core so you don't need to install it separately.

About preset, you need to use a preset to make Babel actually do something, which is called Preset Env that automatically determines the Babel plugins you need based on your supported environments.

```<code>npm install babel-preset-env --save-dev
</code>```

and in .babelrc file

```<code>{
  "presets": ["env"]
}
</code>```

Title: Is it possible write a gulpfile in es6?

Body:
Question: How can I write my gulp file in ES6 so I can use import instead of require and use => syntax over function()?

I can use io.js or node any version.

gulpfile.js:

import gulp from "./node_modules/gulp/index.js";
gulp.task('hello-world', =>{
    console.log('hello world');
});

Errors:

import gulp from "./node_modules/gulp/index.js";
^^^^^^
SyntaxError: Unexpected reserved word

gulp.task('hello-world', =>{
                         ^^
SyntaxError: Unexpected token =>

Inside the node_modules/gulp/bin/gulp.js i've changed the first line to #!/usr/bin/env node --harmony as asked in this stack

Body:
Basically, what you need to install using npm is gulp, gulp-babel and babel-resent-env, add "env" to your .babelrc presets array, and use a gulpfile.babel.js file.

npm install gulp-babel --save-dev

Some of the answers mentioned babel-core, babel-preset-es2015, etc. The Babel official setup guide with Gulp is to use gulp-babel only, while gulp-babel has dependencies modules including babel-core so you don't need to install it separately.

About preset, you need to use a preset to make Babel actually do something, which is called Preset Env that automatically determines the Babel plugins you need based on your supported environments.

npm install babel-preset-env --save-dev

and in .babelrc file

{
  "presets": ["env"]
}


问:
how to redirect all users coming from all other sites when referral
hello im looking to show a message to users when they come on my page from different sites https sites or http can someone help me to redirect users coming from all sites example if they have referral different sites with https or http referrals, this is working only from http referrals</p>

```<code><?php
$pos = (strpos($_SERVER['HTTP_REFERER'], 'http'));
if($pos===false)
  die('<h1>Restricted access</h1>');
else
{echo '<h1>It Works</h1>';}

?>
</code>```

答:
generally regex should be used for such kind of problem ... the below should work for your problem ... </p>

```<code>if (preg_match('/http(s)?/',$_SERVER['HTTP_REFERER'])) {
    echo 'redirect now';
} else {
    echo 'stay here';
}
</code>```

Body:
hello im looking to show a message to users when they come on my page from different sites https sites or http can someone help me to redirect users coming from all sites example if they have referral different sites with https or http referrals, this is working only from http referrals

<?php
$pos = (strpos($_SERVER['HTTP_REFERER'], 'http'));
if($pos===false)
  die('
Restricted access
');
else
{echo '
It Works
';}

?>

Body:
generally regex should be used for such kind of problem ... the below should work for your problem ...

if (preg_match('/http(s)?/',$_SERVER['HTTP_REFERER'])) {
    echo 'redirect now';
} else {
    echo 'stay here';
}


问:
How to access static methode when its in class
Here I write some code in static methode which is in class file please Help me how can i create instance of static class</p>

```<code>public class ConnectionString
    {

       public static void CreateCommand(string querystring, string connectionString)
        {
           using(SqlConnection cn = new SqlConnection(connectionString))
           {
               SqlCommand cmd = new SqlCommand(querystring, cn);
               cmd.Connection.Open();
               cmd.ExecuteNonQuery();
           }
        }

    }
</code>```

答:
Just call it like this:

```<code>string querystring = "Your values here";
string connectionString = "Your values here";
ConnectionString.CreateCommand(querystring, connectionString);
</code>```

That's it.

Body:
Here I write some code in static methode which is in class file please Help me how can i create instance of static class

public class ConnectionString
    {

       public static void CreateCommand(string querystring, string connectionString)
        {
           using(SqlConnection cn = new SqlConnection(connectionString))
           {
               SqlCommand cmd = new SqlCommand(querystring, cn);
               cmd.Connection.Open();
               cmd.ExecuteNonQuery();
           }
        }

    }

Body:
Just call it like this:

string querystring = "Your values here";
string connectionString = "Your values here";
ConnectionString.CreateCommand(querystring, connectionString);

That's it.


问:
Create drawable programmatically
How can I create this exact drawable in java code only?

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size android:width="1dp" />
    <solid android:color="#ff0000" />

    <padding
        android:bottom="-15px"
        android:top="-5px" />
</shape>
</code>```

I need the padding values to be variable so I can't do it as an xml.

答:
If you wanna draw something custom, you should open a Canvas and make your drawing there.

Read this:
https://developer.android.com/training/custom-views/custom-drawing.html

And it seems a simple shape. So you can add a layout view (View,TextView, ImageView, etc.) set background with this drawable and adjust padding through this view.

Title: Create drawable programmatically

Body:
How can I create this exact drawable in java code only?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size android:width="1dp" />
    <solid android:color="#ff0000" />

    <padding
        android:bottom="-15px"
        android:top="-5px" />
</shape>

I need the padding values to be variable so I can't do it as an xml.


问:
Unable to install Scipy using pip
I use the 'pip install scipy' command in the cmd, but get this error at the end. How do I fix it?

```<code>Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Spencer>pip install scipy
Collecting scipy
  Using cached scipy-0.17.0.tar.gz
Complete output from command python setup.py egg_info:
non-existing path in 'numpy\\distutils': 'site.cfg'
Running from numpy source directory.
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\setup.py:327: UserWarning:
Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
  warnings.warn("Unrecognized setuptools command, proceeding with "
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1640: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1649: UserWarning:
    Blas (http://www.netlib.org/blas/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [blas]) or by setting
    the BLAS environment variable.
  warnings.warn(BlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1652: UserWarning:
    Blas (http://www.netlib.org/blas/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [blas_src]) or by setting
    the BLAS_SRC environment variable.
  warnings.warn(BlasSrcNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1542: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1553: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  warnings.warn(LapackNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1556: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  warnings.warn(LapackSrcNotFoundError.__doc__)
c:\python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'define_macros'

  warnings.warn(msg)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\setup.py", line 265, in <modu
le>
    setup_package()
  File "c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\setup.py", line 262, in setup
_package
    setup(**metadata)
  File "c:\python27\lib\distutils\core.py", line 111, in setup
    _setup_distribution = dist = klass(attrs)
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 268, in __init__
    self.fetch_build_eggs(attrs['setup_requires'])
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 313, in fetch_build_eggs
    replace_conflicting=True,
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 836, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1081, in best_match
    return self.obtain(req, installer)
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1093, in obtain
    return installer(requirement)
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 380, in fetch_build_egg
    return cmd.easy_install(req)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 629, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 659, in install_
item
    dists = self.install_eggs(spec, download, tmpdir)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 842, in install_
eggs
    return self.build_and_install(setup_script, setup_base)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1070, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1058, in run_set
up
    raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in       c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\
</code>```

EDIT: added the entire error
The post has too much code and won't let me post, please ignore these next could of sentences as it is just to fill the required amount before I can post this.

答: In the errors it says: "Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27"</p>

Title: Unable to install Scipy using pip

Body:
I use the 'pip install scipy' command in the cmd, but get this error at the end. How do I fix it?

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Spencer>pip install scipy
Collecting scipy
  Using cached scipy-0.17.0.tar.gz
Complete output from command python setup.py egg_info:
non-existing path in 'numpy\\distutils': 'site.cfg'
Running from numpy source directory.
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\setup.py:327: UserWarning:
Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
  warnings.warn("Unrecognized setuptools command, proceeding with "
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1640: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1649: UserWarning:
    Blas (http://www.netlib.org/blas/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [blas]) or by setting
    the BLAS environment variable.
  warnings.warn(BlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1652: UserWarning:
    Blas (http://www.netlib.org/blas/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [blas_src]) or by setting
    the BLAS_SRC environment variable.
  warnings.warn(BlasSrcNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1542: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1553: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  warnings.warn(LapackNotFoundError.__doc__)
c:\users\spencer\appdata\local\temp\easy_install-3pkkpt\numpy-1.11.0\numpy\distutils\system_info
.py:1556: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  warnings.warn(LapackSrcNotFoundError.__doc__)
c:\python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'define_macros'

  warnings.warn(msg)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\setup.py", line 265, in <modu
le>
    setup_package()
  File "c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\setup.py", line 262, in setup
_package
    setup(**metadata)
  File "c:\python27\lib\distutils\core.py", line 111, in setup
    _setup_distribution = dist = klass(attrs)
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 268, in __init__
    self.fetch_build_eggs(attrs['setup_requires'])
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 313, in fetch_build_eggs
    replace_conflicting=True,
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 836, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1081, in best_match
    return self.obtain(req, installer)
  File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1093, in obtain
    return installer(requirement)
  File "c:\python27\lib\site-packages\setuptools\dist.py", line 380, in fetch_build_egg
    return cmd.easy_install(req)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 629, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 659, in install_
item
    dists = self.install_eggs(spec, download, tmpdir)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 842, in install_
eggs
    return self.build_and_install(setup_script, setup_base)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1070, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1058, in run_set
up
    raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in       c:\users\spencer\appdata\local\temp\pip-build-i4x0vy\scipy\

EDIT: added the entire error
The post has too much code and won't let me post, please ignore these next could of sentences as it is just to fill the required amount before I can post this.


问:
How can I package my ng-cli app for redistribution via NPM?
As the title states, I'm looking for 'best practices' or guides on how to go about packaging your application created via angular-cli for redistribution via NPM.

The way I was thinking would be to have my main app as its own repository, but include the modules I wanted to reuse as git submodules, this however doesn't seem like the best way to handle it, as users who install the submodule for extension don't have access to the core boostrapping of the application. I also don't want third party developers to necessarily have to learn git submodules, as they can be a bit tricky.

Edit:
The folder structure is currently

```<code>/
src/
   app/
       core/ # main module
       shared/ # shared modules used by core
       ui/ # UI module specifically for general UI components
</code>```

The modules, core, shared and UI are what I want bundled into one application that developers can simply npm install & import into their existing project.

Any ideas?

答:
The functionality I desire has yet to been implemented:

https://github.com/angular/angular-cli/issues/1692

All the workarounds only seem to cover only some of what I want and don't let you develop your base application with the CLI.

Workaround projects:

http://dbarnes.me/writing-an-aot-compliant-angular-library/

https://github.com/filipesilva/angular-quickstart-lib

https://medium.com/@cyrilletuzi/how-to-build-and-publish-an-angular-module-7ad19c0b4464

Body:
As the title states, I'm looking for 'best practices' or guides on how to go about packaging your application created via angular-cli for redistribution via NPM.

The way I was thinking would be to have my main app as its own repository, but include the modules I wanted to reuse as git submodules, this however doesn't seem like the best way to handle it, as users who install the submodule for extension don't have access to the core boostrapping of the application. I also don't want third party developers to necessarily have to learn git submodules, as they can be a bit tricky.

Edit:
The folder structure is currently

/
src/
   app/
       core/ # main module
       shared/ # shared modules used by core
       ui/ # UI module specifically for general UI components

The modules, core, shared and UI are what I want bundled into one application that developers can simply npm install & import into their existing project.

Any ideas?


问:
rsync files from inside a docker container?
We are using Docker for the build/deploy of a NodeJS app. We have a test container that is built by Jenkins, and executes our unit tests. The Dockerfile looks like this:

```<code>FROM node:boron

# <snip> some misc unimportant config here

# Run the tests
ENTRYPOINT npm test
</code>```

I would like to modify this step so that we run npm run test:cov, which runs the unit tests + generates a coverage report HTML file. I've modified the Dockerfile to say:

```<code># Run the tests + generate coverage
ENTRYPOINT npm run test:cov
</code>```

... which works. Yay!

...But now I'm unsure how to rsync the coverage report ( generated by the above command inside the Dockerfile ) to a remote server.

In Jenkins, the above config is invoked this way:

```<code>docker run -t test --rm
</code>```

which, again, runs the above test and exists the container.

how can I add some additional steps after the entrypoint command executes, to (for example) rsync some results out to a remote server?

答:
I am not a "node" expert, so bear with me on the details.

First of all, you may consider if you need a separate Dockerfile for running the tests. Ideally, you'd want your image to be built, then tested, without modifying the actual image.

Building a test-image that uses your NodeJS app as a base image (FROM my-nodejs-image) could do the trick, but may not be needed if all you have to do is run a different command / entrypoint on the image.

Secondly; stateful data (the coverage report falls into that category) should not be stored inside the container (i.e., not stored on the container's filesystem). You want your containers to be ephemeral, and anything that should live beyond the container's lifecycle (anything that should be preserved after the container itself is gone), should be stored outside of the container; either in a "volume", or in a bind-mounted directory.

Let me start with the "separate Dockerfile" point. Let's say, your NodeJS application Dockerfile looks like this;

```<code>FROM node:boron

COPY package.json /usr/src/app/
RUN npm install && npm cache clean
COPY . /usr/src/app

CMD [ "npm", "start" ]
</code>```

You build your image, and tag it, for example, with the commit it was built from;

```<code>docker build -t myapp:$GIT_COMMIT .
</code>```

Once the image was built succesfully, you want to test it. Probably a quick test to verify it actually "runs". Many ways to do that, perhaps something like;

```<code>docker run \
  -d \
  --rm \
  --network=test-network \
  --name test-{$GIT_COMMIT} \
  myapp:$GIT_COMMIT
</code>```

And a container to test it actually does something;

```<code>docker run --rm --network=test-network my-test-image curl test-{$GIT_COMMIT}
</code>```

Once tested (and the temporary container removed), you can run your coverage tests, however, instead of writing the coverage report inside the container, write it to a volume or bind-mount. You can override the command to run in the container with docker run;

```<code>mkdir -p /coverage-reports/{$GIT_COMMIT}
docker run \
  --rm \
  --name test-{$GIT_COMMIT}\
  -v /coverage-reports/{$GIT_COMMIT}:/usr/src/app/coverage \
  myapp:$GIT_COMMIT npm run test:cov
</code>```

The commands above;

Create a unique local directory to store the test-artifacts (coverage report)

Runs the image you built (and tagged myapp:$GIT_COMMIT)

Bind-mount the /coverage-reports/{$GIT_COMMIT} into the container at usr/src/app/coverage

Runs the coverage tests (which will write to /usr/src/app/coverage if I'm not mistaken - again, not a Node expert)

Removes the container once it exits

After the container exits, the coverage report is stored in /coverage-reports/{$GIT_COMMIT} on the host. You can use your regular tools to rsync those where you want.

As an alternative, you can use a volume plugin to write the results to (e.g.) an s3 bucket, which saves you from having to rsync the results.

Once tests are successful, you can docker tag the image to bump your application's version (e.g. docker tag myapp:1.0.12345), docker push to your registry, and deploy the new version.

Body:
We are using Docker for the build/deploy of a NodeJS app. We have a test container that is built by Jenkins, and executes our unit tests. The Dockerfile looks like this:

FROM node:boron

# <snip> some misc unimportant config here

# Run the tests
ENTRYPOINT npm test

I would like to modify this step so that we run npm run test:cov, which runs the unit tests + generates a coverage report HTML file. I've modified the Dockerfile to say:

# Run the tests + generate coverage
ENTRYPOINT npm run test:cov

... which works. Yay!

...But now I'm unsure how to rsync the coverage report ( generated by the above command inside the Dockerfile ) to a remote server.

In Jenkins, the above config is invoked this way:

docker run -t test --rm

which, again, runs the above test and exists the container.

how can I add some additional steps after the entrypoint command executes, to (for example) rsync some results out to a remote server?

Body:
I am not a "node" expert, so bear with me on the details.

First of all, you may consider if you need a separate Dockerfile for running the tests. Ideally, you'd want your image to be built, then tested, without modifying the actual image.

Building a test-image that uses your NodeJS app as a base image (FROM my-nodejs-image) could do the trick, but may not be needed if all you have to do is run a different command / entrypoint on the image.

Secondly; stateful data (the coverage report falls into that category) should not be stored inside the container (i.e., not stored on the container's filesystem). You want your containers to be ephemeral, and anything that should live beyond the container's lifecycle (anything that should be preserved after the container itself is gone), should be stored outside of the container; either in a "volume", or in a bind-mounted directory.

Let me start with the "separate Dockerfile" point. Let's say, your NodeJS application Dockerfile looks like this;

FROM node:boron

COPY package.json /usr/src/app/
RUN npm install && npm cache clean
COPY . /usr/src/app

CMD [ "npm", "start" ]

You build your image, and tag it, for example, with the commit it was built from;

docker build -t myapp:$GIT_COMMIT .

Once the image was built succesfully, you want to test it. Probably a quick test to verify it actually "runs". Many ways to do that, perhaps something like;

docker run \
  -d \
  --rm \
  --network=test-network \
  --name test-{$GIT_COMMIT} \
  myapp:$GIT_COMMIT

And a container to test it actually does something;

docker run --rm --network=test-network my-test-image curl test-{$GIT_COMMIT}

Once tested (and the temporary container removed), you can run your coverage tests, however, instead of writing the coverage report inside the container, write it to a volume or bind-mount. You can override the command to run in the container with docker run;

mkdir -p /coverage-reports/{$GIT_COMMIT}
docker run \
  --rm \
  --name test-{$GIT_COMMIT}\
  -v /coverage-reports/{$GIT_COMMIT}:/usr/src/app/coverage \
  myapp:$GIT_COMMIT npm run test:cov

The commands above;

Create a unique local directory to store the test-artifacts (coverage report)

Runs the image you built (and tagged myapp:$GIT_COMMIT)

Bind-mount the /coverage-reports/{$GIT_COMMIT} into the container at usr/src/app/coverage

Runs the coverage tests (which will write to /usr/src/app/coverage if I'm not mistaken - again, not a Node expert)

Removes the container once it exits

After the container exits, the coverage report is stored in /coverage-reports/{$GIT_COMMIT} on the host. You can use your regular tools to rsync those where you want.

As an alternative, you can use a volume plugin to write the results to (e.g.) an s3 bucket, which saves you from having to rsync the results.

Once tests are successful, you can docker tag the image to bump your application's version (e.g. docker tag myapp:1.0.12345), docker push to your registry, and deploy the new version.


问:
python: A module for wrapping text quoted via email conventions?
I'm looking for a python module or some existing python code which can be used to wrap text that makes use of the ">" line prefix to indicate quoted text (see below for an example).

I know that I can use the python textwrap module to do wrapping on paragraphs of text. However, that module doesn't know about this kind of quoting prefix.

I know how to code up a routine which will perform this text wrapping, and I'm not looking for advice on how to write it. Rather, I'm wondering if anyone knows of any python code or python modules that already exist and which are already able to perform this kind of wrapping on email-type quoted text.

I have been searching, but I haven't found anything in python.

I just don't want to "re-invent the wheel", if something like this has already been written.

Here's an example of the text wrapping that I'd like to perform. Suppose I have the following text that comes from a hypothetical email message:

```<code>Abc defg hijk lmnop.

Mary had a little lamb.
Her fleas were white as snow,

> Now is the time for all good men to come to the aid of their party.
>
> The quick
> brown fox jumped over the lazy sleeping dog.

>> When in the Course of human
>> events it
>> becomes necessary for one people to dissolve the political
>> bands
>> which have
>> connected them ...
      and everywhere that Mary went,
      her fleas were sure to go
      ... and to reproduce.
> What do you mean by this?
>> with another
>> and to assume among
>> the powers of the earth ...
> Doo wah diddy, diddy dum, diddy doo.
>> Text text text text text text text text text text text text text text text text text text text text text text text text text text text.
</code>```

Assuming that I want to wrap at column 52, the resulting text should look like this:

```<code>Abc defg hijk lmnop.

Mary had a little lamb. Her fleas were white as
snow,

> Now is the time for all good men to come to the
> aid of their party.
>
> The quick brown fox jumped over the lazy sleeping
> dog.

>> When in the Course of human events it becomes
>> necessary for one people to dissolve the
>> political bands which have connected them ...
      and everywhere that Mary went, her fleas were
      sure to go ... and to reproduce.
> What do you mean by this?
>> with another and to assume among the powers of
>> the earth ...
> Doo wah diddy, diddy dum, diddy doo.
>> Text text text text text text text text text text
>> text text text text text text text text text text
>> text text text text text text text.
</code>```

Thanks for any references to existing python code.

If no such thing exists "out in the wild", I'll then write this and post my code here.

Thank you very much.

答:
I couldn't find any existing code which wraps this kind of quoted text, so here's the code that I wrote. It makes use of the re and textwrap modules.

I break the code into "paragraphs" based on the number of initial quote or indentation characters. I then use textwrap to wrap each "paragraph" with the quote-or-indentation prefix removed from each line. After wrapping, I re-prepend the prefix to each line of the "paragraph".

Some day I will clean up the code and make it a bit more elegant, but at least it seems to work fine, as is.

```<code>import re
import textwrap
def wrapemail(text, wrap=72):
    if not text:
        return ''
    prefix      = None
    prev_prefix = None
    paragraph   = []
    paragraphs  = []
    for line in text.rstrip().split('\n'):
        line = line.rstrip()
        m = wrapemail.qprefixpat.search(line)
        if m:
            prefix = wrapemail.whitepat.sub('', m.group(1))
            text   = m.group(2)
            if text and wrapemail.whitepat.search(text[0]):
                prefix += text[0]
                text    = text[1:]
        else:
            m = wrapemail.wprefixpat.search(line)
            if m:
                prefix = m.group(1)
                text   = m.group(2)
            else:
                prefix = ''
                text   = line
        if not text:
            if paragraph and prev_prefix is not None:
                paragraphs.append((prev_prefix, paragraph))
            paragraphs.append((prefix, ['']))
            prev_prefix = None
            paragraph   = []
        elif prefix != prev_prefix:
            if paragraph and prev_prefix is not None:
                paragraphs.append((prev_prefix, paragraph))
            prev_prefix = prefix
            paragraph   = []
        paragraph.append(text)
    if paragraph and prefix is not None:
        paragraphs.append((prefix, paragraph))
    result = ''
    for paragraph in paragraphs:
        prefix = paragraph[0]
        text   = '\n'.join(paragraph[1]).rstrip()
        wraplen = wrap - len(prefix)
        if wraplen < 1:
            result += '{}{}\n'.format(prefix, text)
        elif text:
            for line in textwrap.wrap(text, wraplen):
                result += '{}{}\n'.format(prefix, line.rstrip())
        else:
            result += '{}\n'.format(prefix)
    return result
wrapemail.qprefixpat = re.compile(r'^([\s>]*>)([^>]*)$')
wrapemail.wprefixpat = re.compile(r'^(\s+)(\S.*)?$')
wrapemail.whitepat   = re.compile(r'\s')
</code>```

Feeding the text in my original message to it with 'wrap' specified as 52 will indeed produce the output that I specified above.

Feel free to improve upon this or steal it. :)

Body:
I'm looking for a python module or some existing python code which can be used to wrap text that makes use of the ">" line prefix to indicate quoted text (see below for an example).

I know that I can use the python textwrap module to do wrapping on paragraphs of text. However, that module doesn't know about this kind of quoting prefix.

I know how to code up a routine which will perform this text wrapping, and I'm not looking for advice on how to write it. Rather, I'm wondering if anyone knows of any python code or python modules that already exist and which are already able to perform this kind of wrapping on email-type quoted text.

I have been searching, but I haven't found anything in python.

I just don't want to "re-invent the wheel", if something like this has already been written.

Here's an example of the text wrapping that I'd like to perform. Suppose I have the following text that comes from a hypothetical email message:

Abc defg hijk lmnop.

Mary had a little lamb.
Her fleas were white as snow,

> Now is the time for all good men to come to the aid of their party.
>
> The quick
> brown fox jumped over the lazy sleeping dog.

>> When in the Course of human
>> events it
>> becomes necessary for one people to dissolve the political
>> bands
>> which have
>> connected them ...
      and everywhere that Mary went,
      her fleas were sure to go
      ... and to reproduce.
> What do you mean by this?
>> with another
>> and to assume among
>> the powers of the earth ...
> Doo wah diddy, diddy dum, diddy doo.
>> Text text text text text text text text text text text text text text text text text text text text text text text text text text text.

Assuming that I want to wrap at column 52, the resulting text should look like this:

Abc defg hijk lmnop.

Mary had a little lamb. Her fleas were white as
snow,

> Now is the time for all good men to come to the
> aid of their party.
>
> The quick brown fox jumped over the lazy sleeping
> dog.

>> When in the Course of human events it becomes
>> necessary for one people to dissolve the
>> political bands which have connected them ...
      and everywhere that Mary went, her fleas were
      sure to go ... and to reproduce.
> What do you mean by this?
>> with another and to assume among the powers of
>> the earth ...
> Doo wah diddy, diddy dum, diddy doo.
>> Text text text text text text text text text text
>> text text text text text text text text text text
>> text text text text text text text.

Thanks for any references to existing python code.

If no such thing exists "out in the wild", I'll then write this and post my code here.

Thank you very much.

Body:
I couldn't find any existing code which wraps this kind of quoted text, so here's the code that I wrote. It makes use of the re and textwrap modules.

I break the code into "paragraphs" based on the number of initial quote or indentation characters. I then use textwrap to wrap each "paragraph" with the quote-or-indentation prefix removed from each line. After wrapping, I re-prepend the prefix to each line of the "paragraph".

Some day I will clean up the code and make it a bit more elegant, but at least it seems to work fine, as is.

import re
import textwrap
def wrapemail(text, wrap=72):
    if not text:
        return ''
    prefix      = None
    prev_prefix = None
    paragraph   = []
    paragraphs  = []
    for line in text.rstrip().split('\n'):
        line = line.rstrip()
        m = wrapemail.qprefixpat.search(line)
        if m:
            prefix = wrapemail.whitepat.sub('', m.group(1))
            text   = m.group(2)
            if text and wrapemail.whitepat.search(text[0]):
                prefix += text[0]
                text    = text[1:]
        else:
            m = wrapemail.wprefixpat.search(line)
            if m:
                prefix = m.group(1)
                text   = m.group(2)
            else:
                prefix = ''
                text   = line
        if not text:
            if paragraph and prev_prefix is not None:
                paragraphs.append((prev_prefix, paragraph))
            paragraphs.append((prefix, ['']))
            prev_prefix = None
            paragraph   = []
        elif prefix != prev_prefix:
            if paragraph and prev_prefix is not None:
                paragraphs.append((prev_prefix, paragraph))
            prev_prefix = prefix
            paragraph   = []
        paragraph.append(text)
    if paragraph and prefix is not None:
        paragraphs.append((prefix, paragraph))
    result = ''
    for paragraph in paragraphs:
        prefix = paragraph[0]
        text   = '\n'.join(paragraph[1]).rstrip()
        wraplen = wrap - len(prefix)
        if wraplen < 1:
            result += '{}{}\n'.format(prefix, text)
        elif text:
            for line in textwrap.wrap(text, wraplen):
                result += '{}{}\n'.format(prefix, line.rstrip())
        else:
            result += '{}\n'.format(prefix)
    return result
wrapemail.qprefixpat = re.compile(r'^([\s>]*>)([^>]*)$')
wrapemail.wprefixpat = re.compile(r'^(\s+)(\S.*)?$')
wrapemail.whitepat   = re.compile(r'\s')

Feeding the text in my original message to it with 'wrap' specified as 52 will indeed produce the output that I specified above.

Feel free to improve upon this or steal it. :)


问:
This context-free grammar is ambiguous and I'm not sure why. The SLR(1) compiler I'm building doesn't work the way I expect it to
I'm building a syntax parser. It's going good to be SLR(1) but I believe there are some reduce/shift conflicts or some kind of conflict that is making the parser reject strings too early . Here is the grammar:
Note: I did left factor the grammar to see if that was the problem, but that doesn't get rid of ambiguity. However this is the original grammar without left factoring

```<code>P'' -> P'$

P' -> P

P -> C | C;D

D -> R | RD

R -> pu{P}

C -> I | I;C

I -> h | O | A | R | Z

O -> i(V) | z(V)

Y -> u

V -> S | N

S -> u

N -> u

A -> S=s | S=S | N=X

X -> N | b | L

L -> d(X,X) | s(X,X) | m(X,X)

R -> f(B)t{C} |  f(B)t{C}1{C}

B -> e(V,V) | (N<N) | (N>N) | nB | a(B,B) | o(B,B)

Z -> w(B){C} | r(N=0;N<N;N=a(N,1)){C}
</code>```

I understand this grammar is quite big, but if you could help me here you would be a life saver. Thank you in advance!

答:
Having recognized an I, and with ; as the next symbol, there's a shift-reduce conflict:

The production C -> I;C says to shift the ;.

The production P -> C;D says to reduce via C -> I.

So the grammar is not SLR(1).

Body:
I'm building a syntax parser. It's going good to be SLR(1) but I believe there are some reduce/shift conflicts or some kind of conflict that is making the parser reject strings too early . Here is the grammar:
Note: I did left factor the grammar to see if that was the problem, but that doesn't get rid of ambiguity. However this is the original grammar without left factoring

P'' -> P'$

P' -> P

P -> C | C;D

D -> R | RD

R -> pu{P}

C -> I | I;C

I -> h | O | A | R | Z

O -> i(V) | z(V)

Y -> u

V -> S | N

S -> u

N -> u

A -> S=s | S=S | N=X

X -> N | b | L

L -> d(X,X) | s(X,X) | m(X,X)

R -> f(B)t{C} |  f(B)t{C}1{C}

B -> e(V,V) | (N<N) | (N>N) | nB | a(B,B) | o(B,B)

Z -> w(B){C} | r(N=0;N<N;N=a(N,1)){C}

I understand this grammar is quite big, but if you could help me here you would be a life saver. Thank you in advance!


问:
Group pandas DataFrame by columns and produce lists out of groups of columns
Assuming we have the following input DataFrame:

```<code>In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2
</code>```

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

```<code>In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

My attempts:

```<code>In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)
</code>```

if i just print it - it works properly:

```<code>In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None
</code>```

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

```<code>df.groupby(..., axis=1).agg(...)
</code>```

or

```<code>df.groupby(..., axis=1).apply(...)
</code>```

答:
Here is a very nice solution from @DSM:</p>

```<code>In [123]: df.set_index(['order_id','customer_name']) \
     ...:   .groupby(lambda x: x.split('_')[-1], axis=1) \
     ...:   .agg(lambda x: x.values.tolist())
     ...:
Out[123]:
                                 id   quantity
order_id customer_name
1        John           [4, 24, 16]  [1, 4, 1]
2        Paul           [8, 41, 33]  [3, 1, 1]
3        Andrew          [1, 34, 8]  [1, 4, 2]
</code>```

Body:
Assuming we have the following input DataFrame:

In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]

My attempts:

In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)

if i just print it - it works properly:

In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

df.groupby(..., axis=1).agg(...)

or

df.groupby(..., axis=1).apply(...)

Body:
Here is a very nice solution from @DSM:

In [123]: df.set_index(['order_id','customer_name']) \
     ...:   .groupby(lambda x: x.split('_')[-1], axis=1) \
     ...:   .agg(lambda x: x.values.tolist())
     ...:
Out[123]:
                                 id   quantity
order_id customer_name
1        John           [4, 24, 16]  [1, 4, 1]
2        Paul           [8, 41, 33]  [3, 1, 1]
3        Andrew          [1, 34, 8]  [1, 4, 2]


问:
php weird file_exists bug
Has anyone got any idea to why doesn't the following work ?

```<code>$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';
</code>```

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help

答:
```<code>$file = rawurldecode('images/thumbs/1%20-%20Copy.jpg');
</code>```

Title: php weird file_exists bug

Body:
Has anyone got any idea to why doesn't the following work ?

$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help


问:
Undefined variable during mysql to mysqli conversion
I am in the process of converting my old PHP from mysql to mysqli and am running into this error during my conversion. The code worked without throwing errors under mysql but for some reason I get the 'Undefined variable: prevcat in /xx/xx/xx/xx/xx/xx/vluchtbijtoestel.php on line 102' error now. I've tried adding $prevcat = $cat to the variables list but that then breaks the code.

My code:

```<code><?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

// Define your colors for the alternating rows
$color1 = "#F0F8FF";
$color2 = "#FFFFFF";
$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT vg.gegevenID, lvm.luchtvaartmaatschappij, lvm.sm_logo, vg.vertrekdatum2, vg.vertrekluchthaven, vg.aankomstluchthaven, vg.toestel, vg.inschrijvingnmr, vlg.vliegtuignaam, vg.vluchtnmr, t.toestel AS toestelnaam, lh.luchthavencode, lh.luchthavennaam, lh.countryflag, lh2.luchthavencode AS aankomstluchthavencode, lh2.countryflag AS countryflagaankomst, vlg.erlr, vlg.firstflight, DATEDIFF(vlg.firstflight,vg.vertrekdatum2) Age1, lh2.luchthavennaam AS aankomstnaam, CONCAT(t.toestel,' ', vlg.erlr) as toestelmeterlr

    FROM (tbl_vliegtuiggegevens vlg

    INNER JOIN (tbl_luchtvaartmaatschappij lvm INNER JOIN tbl_vluchtgegevens vg ON lvm.luchtvaartmaatschappijID = vg.luchtvaartmaatschappij) ON (vlg.inschrijvingnmr = vg.inschrijvingnmr) AND (vlg.lvmID = lvm.luchtvaartmaatschappijID)) INNER JOIN tbl_toestel t ON vg.toestel = t.toestelID

    LEFT JOIN tbl_luchthaven lh
    ON vg.vertrekluchthaven = lh.luchthavenID

    LEFT JOIN tbl_luchthaven lh2
    ON vg.aankomstluchthaven = lh2.luchthavenID

    GROUP BY  lvm.luchtvaartmaatschappij, toestelmeterlr, vg.inschrijvingnmr, vg.vertrekdatum2

    ORDER BY lvm.luchtvaartmaatschappij, toestelmeterlr, vg.vertrekdatum2 DESC, vg.inschrijvingnmr; ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "
<table width='100%' border='0'>
  <tr>
    <td colspan='3'><strong>Luchtvaartmaatschappij</strong></td>
    <td width='17%'> </td>
    <td width='12%'> </td>
    <td width='19%'> </td>
    <td width='28%'> </td>
  </tr>
  <tr>
    <td width='2%'> </td>
    <td colspan='3'><strong>Toestel</strong></td>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td width='3%'> </td>
    <td width='19%'><strong>vertrekdatum</strong></td>
    <td><strong>vliegroute</strong></td>
    <td><strong>registratie</strong></td>
    <td><strong>vliegtuignaam</strong></td>
    <td><strong>vliegtuig leeftijd op reisdatum</strong></td>
  </tr>
</table>
";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {

    $row_color = ($row_count % 2) ? $color1 : $color2;
    $date1 = date_create($row['firstflight']);
    $date2 = date_create($row['vertrekdatum2']);
    $interval = date_diff($date1, $date2);
    $cat = $row['luchtvaartmaatschappij'];
    $subcat = $row['toestelmeterlr'];
    $item = $row['inschrijvingnmr'];

    if($cat != $prevcat){

echo "  <table width='100%' border='0'>";
echo "  <tr>";
echo "    <td><br /><hr></td>";
echo "  </tr>";
echo "  <tr>";
echo "    <td><strong><span class='style4'><img src='http://globe-trekking.com/vg/img/logos/sm/".$row['sm_logo']."'>     " .$cat. "</strong></span>         <br /></td>";
echo "  </tr>";
echo "</table>";
        echo '<span style="color: #0A0094; font-size: 16px;">      '. $subcat.'</span><br />';//if the category has changed, we also want to show the new subcat
    }elseif($subcat != $prevsubcat){
        echo '<br /><span style="color: #0A0094; font-size: 16px;">      ' .$subcat.'</span><br />';
    }
echo "  <table width='1093' border='0' cellspacing='0'>";
echo "  <tr>";
echo "    <td width='75'> </td>";
echo "    <td width='200' bgcolor='$row_color'>" .date("d-M-Y H:i", strtotime($row['vertrekdatum2']))."</td>";
echo "    <td width='70' bgcolor='$row_color'><img src='http://globe-trekking.com/vg/img/flags/".$row['countryflag']."'>   <abbr title=\"".htmlspecialchars($row['luchthavennaam'])."\">".$row['luchthavencode']."</abbr></td>";
echo "    <td width='70' bgcolor='$row_color'>   naar   </td>";
echo "    <td width='130' bgcolor='$row_color'><img src='http://globe-trekking.com/vg/img/flags/".$row['countryflagaankomst']."'>   <abbr title=\"".htmlspecialchars($row['aankomstnaam'])."\">".$row['aankomstluchthavencode']."</abbr></td>";
echo "    <td width='150' bgcolor='$row_color'>".$row['inschrijvingnmr']."</td>";
echo "    <td width='250' bgcolor='$row_color'>".$row['vliegtuignaam'] ."</td>";
echo "    <td width='250' bgcolor='$row_color'>" . $interval->y . " jaar en " . $interval->m." maanden </td>";
echo "  </tr>";
echo "</table>";
    $prevcat = $cat;
    $prevsubcat = $subcat;
      // Add 1 to the row count
$row_count++;
}
}
mysqli_close($mysqli);

?>
</code>```

答:
put your code .. you are using $precat and $prevsubcat in your if conditions before declaring and defining it.

```<code> $prevcat = $cat;
 $prevsubcat = $subcat;
</code>```

after

```<code>$cat = $row['luchtvaartmaatschappij'];
$subcat = $row['toestelmeterlr'];
</code>```

like this

```<code>$cat = $row['luchtvaartmaatschappij'];
$subcat = $row['toestelmeterlr'];
$prevcat = $cat;
$prevsubcat = $subcat;
</code>```

Body:
I am in the process of converting my old PHP from mysql to mysqli and am running into this error during my conversion. The code worked without throwing errors under mysql but for some reason I get the 'Undefined variable: prevcat in /xx/xx/xx/xx/xx/xx/vluchtbijtoestel.php on line 102' error now. I've tried adding $prevcat = $cat to the variables list but that then breaks the code.

My code:

<?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

// Define your colors for the alternating rows
$color1 = "#F0F8FF";
$color2 = "#FFFFFF";
$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT vg.gegevenID, lvm.luchtvaartmaatschappij, lvm.sm_logo, vg.vertrekdatum2, vg.vertrekluchthaven, vg.aankomstluchthaven, vg.toestel, vg.inschrijvingnmr, vlg.vliegtuignaam, vg.vluchtnmr, t.toestel AS toestelnaam, lh.luchthavencode, lh.luchthavennaam, lh.countryflag, lh2.luchthavencode AS aankomstluchthavencode, lh2.countryflag AS countryflagaankomst, vlg.erlr, vlg.firstflight, DATEDIFF(vlg.firstflight,vg.vertrekdatum2) Age1, lh2.luchthavennaam AS aankomstnaam, CONCAT(t.toestel,' ', vlg.erlr) as toestelmeterlr

    FROM (tbl_vliegtuiggegevens vlg

    INNER JOIN (tbl_luchtvaartmaatschappij lvm INNER JOIN tbl_vluchtgegevens vg ON lvm.luchtvaartmaatschappijID = vg.luchtvaartmaatschappij) ON (vlg.inschrijvingnmr = vg.inschrijvingnmr) AND (vlg.lvmID = lvm.luchtvaartmaatschappijID)) INNER JOIN tbl_toestel t ON vg.toestel = t.toestelID

    LEFT JOIN tbl_luchthaven lh
    ON vg.vertrekluchthaven = lh.luchthavenID

    LEFT JOIN tbl_luchthaven lh2
    ON vg.aankomstluchthaven = lh2.luchthavenID

    GROUP BY  lvm.luchtvaartmaatschappij, toestelmeterlr, vg.inschrijvingnmr, vg.vertrekdatum2

    ORDER BY lvm.luchtvaartmaatschappij, toestelmeterlr, vg.vertrekdatum2 DESC, vg.inschrijvingnmr; ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "

    Luchtvaartmaatschappij

    Toestel

    vertrekdatum
    vliegroute
    registratie
    vliegtuignaam
    vliegtuig leeftijd op reisdatum

";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {

    $row_color = ($row_count % 2) ? $color1 : $color2;
    $date1 = date_create($row['firstflight']);
    $date2 = date_create($row['vertrekdatum2']);
    $interval = date_diff($date1, $date2);
    $cat = $row['luchtvaartmaatschappij'];
    $subcat = $row['toestelmeterlr'];
    $item = $row['inschrijvingnmr'];

    if($cat != $prevcat){

echo "
";
echo "
";
echo "

	";
echo "
";
echo "
";
echo "         " .$cat. "
	";
echo "
";
echo "
";
        echo '      '. $subcat.'
';//if the category has changed, we also want to show the new subcat
    }elseif($subcat != $prevsubcat){
        echo '
      ' .$subcat.'
';
    }
echo "
";
echo "
";
echo "     	";
echo "    " .date("d-M-Y H:i", strtotime($row['vertrekdatum2']))."	";
echo "       ".$row['luchthavencode']."	";
echo "       naar   	";
echo "       ".$row['aankomstluchthavencode']."	";
echo "    ".$row['inschrijvingnmr']."	";
echo "    ".$row['vliegtuignaam'] ."	";
echo "    " . $interval->y . " jaar en " . $interval->m." maanden 	";
echo "
";
echo "
";
    $prevcat = $cat;
    $prevsubcat = $subcat;
      // Add 1 to the row count
$row_count++;
}
}
mysqli_close($mysqli);

?>

Body:
put your code .. you are using $precat and $prevsubcat in your if conditions before declaring and defining it.

 $prevcat = $cat;
 $prevsubcat = $subcat;

after

$cat = $row['luchtvaartmaatschappij'];
$subcat = $row['toestelmeterlr'];

like this

$cat = $row['luchtvaartmaatschappij'];
$subcat = $row['toestelmeterlr'];
$prevcat = $cat;
$prevsubcat = $subcat;


问:
When Importing a File, Error States File is not Named. Python
Fast Question

in my file i wrote
from foggerlib.frog import Frog

my datamember is self.F = frog.Frog(perameters)

line 13, in init()

self.F = frog.Frog(self, x, y, w, h, dx, dy, s, hg, vg)
NameError: name 'frog' is not defined

why is this happening?

答: You imported capital 'F' Frog.  You may be able to replace frog.Frog with simply Frog.</p>


问:
Div with fixed width and inline element
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code: </p>

```<code>    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title></title>
            <meta charset="UTF-8" />

        </head>
    <body>
        <div style="width:500px;"><p>Some text</p></div>
        <img src="someImage.jpeg " />
    </body>
    </html>
</code>```

答:
Div is a non-replaced element and, by default, a block-level element.

The width of non-replaced, block level elements in normal flow always meets this equality:

```'margin-left' + 'border-left-width' + 'padding-left' +
'width' +
'padding-right' + 'border-right-width' + 'margin-right'
= width of containing block```

So when you reduce the "width" to 500px, one or more of the other properties (either or both margins) are automatically adjusted so that the equality still holds. That is, the full width of the containing block is always fully used, and there is no space available for your inline element.

Title: Div with fixed width and inline element

Body:
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code:

    <!DOCTYPE html>

            <title></title>
            <meta charset="UTF-8" />

Some text

Body:
Div is a non-replaced element and, by default, a block-level element.

The width of non-replaced, block level elements in normal flow always meets this equality:

'margin-left' + 'border-left-width' + 'padding-left' +
'width' +
'padding-right' + 'border-right-width' + 'margin-right'
= width of containing block

So when you reduce the "width" to 500px, one or more of the other properties (either or both margins) are automatically adjusted so that the equality still holds. That is, the full width of the containing block is always fully used, and there is no space available for your inline element.


问:
Can't find tsconfig.json command in Atom's toggle panel
I have installed atom-script package in Atom and it worked for a while well, now I can't find in toggle panel Create tsconfig.json file command anymore. What has happened? How do I add tsconfig.json file to my project then? </p>

答:
Atom was updated last week and now doesn't create the tsconfig file within toggle panel. You need to use 'tsc --init' now to create the tsconfig file. After it is created, you need to add two lines of code so your tsconfig file will look like this:

```<code>{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false
},
"compileOnSave": true,
"buildOnSave": true
}
</code>```

The last two lines are added so when you save the typescript file, it will automatically compile the javascript file.

Body:
Atom was updated last week and now doesn't create the tsconfig file within toggle panel. You need to use 'tsc --init' now to create the tsconfig file. After it is created, you need to add two lines of code so your tsconfig file will look like this:

{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false
},
"compileOnSave": true,
"buildOnSave": true
}

The last two lines are added so when you save the typescript file, it will automatically compile the javascript file.


问:
excessive dependence on ajax
I am a newbie to web development. I am trying to develop a web site and it uses fairly large
number of ajax requests. In between i came across a friend who said that excessive dependency
on ajax request can be a performance concern and makes the browser to utilize huge amount of
network utility and cpu usage. Is this true..?

Does excessive dependency on ajax pose serious performance issues.?

答:
If you are using a lot of Ajax requests, you are going to want to do some things to speed up your application

1)  Make the server as fast as possible by using caching, returning limited sets of data, etc.

2)  Make sure you actually need every ajax request.  For example, you can wire a select box up to an ajax response, but if the data rarely changes, maybe you should load it only once, when the user loads the app.

3)  Dont load too much data -- loading a table with 1000 rows in it via ajax can take a while, both to get the data and to render the response.  If possible, use paging or similar techniques to get the request size down.

Any ajax enabled site can have usability issues if the network is slow, if the server is slow, if the browser is slow.  This is just part of the game, and the fun and joy of modern web development.  Do what you can to mitigate these types of issues.

Asking if you can have excessive dependency on ajax is kind of like asking if you can have excessive dependencies on 'divs'.  Ajax is a tool, and like all tools, there are ways to use it properly.

Title: excessive dependence on ajax


答:
It's because even if you set a fixed width to a div it's default display CSS property value is always going to be block - which occupies the entire width. This happens because the
 tag defines a horizontal division or a section in HTML.

FOR EXAMPLE:

In the code given below, there is not display property defined and therefore it takes the default value as block which is why the image goes below the div.

  <title></title>
  <meta charset="UTF-8" />

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

```
</div>
</div>
</p>

<p>And in this example, the <code>display</code> property is set to <code>inline-block</code> due to which the image stays in the same line as the paragraph (view the code snippet in full page).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8" />

</head>

<body>
  <div style="width:500px; background: #cccccc; display: inline-block;">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
  <img src="https://www.w3schools.com/css/img_fjords.jpg" />
</body>

</html></code>```

Hope this helps :)

Title: Div with fixed width and inline element

Body:
It's because even if you set a fixed width to a div it's default display CSS property value is always going to be block - which occupies the entire width. This happens because the <div> tag defines a horizontal division or a section in HTML.

FOR EXAMPLE:

In the code given below, there is not display property defined and therefore it takes the default value as block which is why the image goes below the div.

<html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8" />

</head>

<body>
  <div style="width:500px; background: #cccccc;">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
  <img src="https://www.w3schools.com/css/img_fjords.jpg" />
</body>

</html>

And in this example, the display property is set to inline-block due to which the image stays in the same line as the paragraph (view the code snippet in full page).

<html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8" />

</head>

<body>
  <div style="width:500px; background: #cccccc; display: inline-block;">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
  <img src="https://www.w3schools.com/css/img_fjords.jpg" />
</body>

</html>

Hope this helps :)


问:
Angular service for localstorage
So as a project I have been asked to make a small-scale app using Angular. For the localstorage i want to use a seperate js as a service.

What I'm trying to do is use a controller-page to give an html-page the ability to call the localstorage using the service. The reason for this being that I want to access the localstorage from multiple html-pages.

I'm posting my code below and help is greatly appreciated.

profilecontroller:

```<code>app.controller("ProfileController", function($scope, DataService) {
  $scope.profile = DataService.getProfile();
});
</code>```

profilehtml:

```<code><html>
<head>
    <link rel="stylesheet" href="CSS/stylesheet.css">
</head>

<body>
    <div class="page">
        <h1> Overflow test for longer pages </h1> <br>

        <div id = "textholder" ng-repeat="data in profile">
           <span>{{data.id}}</span>
        </div>
    </div>
</body>
</code>```

service:

```<code>app.service("DataService", function(){
  console.log("DataService");

  var localProfile = JSON.parse(localStorage.getItem("profile"));

  if(localProfile != undefined && localProfile.length>0)
  { this.profiles = localProfile; }

  else {
    this.profile = [
        { id: "1526", username: "berserk",      password: "berserk",    age: "31",          sex: "male"},
        { id: "1358", username: "Johnathan",    password: "test",       age: "17",          sex: "male"},
        { id: "2539", username: "Britney",      password: "test",       age: "18",          sex: "female"},
        { id: "1486", username: "Kevin",        password: "test",       age: "7",           sex: "male"},
        { id: "7777", username: "jesus",        password: "holy",       age: "unknown",     sex: "male"},
        { id: "6666", username: "satan",        password: "hell",       age: "unknown",     sex: "unknown"}
    ];
  }

  this.getProfile = function() {
     return this.profile;
  }
});
</code>```

答:
There are few mistakes in the above code,

(i)You need to inject the DataService to the controller.

(ii) You can just return the profiles as it is without using $scope

```<code>app.service("DataService", function() {
  console.log("DataService");
  var localProfile = JSON.parse(localStorage.getItem("profile"));
  var profiles = JSON.parse(localStorage.getItem("profile"));

  if (localProfile != undefined && localProfile.length > 0) {
    this.profiles = localProfile;
  } else {
    this.profiles = [{
      id: "1526",
      username: "berserk",
      password: "berserk",
      age: "31"
    }, {
      id: "1358",
      username: "Johnathan",
      password: "test",
      age: "17"
    }, {
      id: "2539",
      username: "Britney",
      password: "test",
      age: "18"
    }, {
      id: "1486",
      username: "Kevin",
      password: "test",
      age: "7"
    }];
  }

  this.getProfile = function() {
    return this.profiles;
  }
});
</code>```

DEMO

Title: Angular service for localstorage

Body:
So as a project I have been asked to make a small-scale app using Angular. For the localstorage i want to use a seperate js as a service.

What I'm trying to do is use a controller-page to give an html-page the ability to call the localstorage using the service. The reason for this being that I want to access the localstorage from multiple html-pages.

I'm posting my code below and help is greatly appreciated.

profilecontroller:

app.controller("ProfileController", function($scope, DataService) {
  $scope.profile = DataService.getProfile();
});

profilehtml:

    <link rel="stylesheet" href="CSS/stylesheet.css">

 Overflow test for longer pages

           {{data.id}}

service:

app.service("DataService", function(){
  console.log("DataService");

  var localProfile = JSON.parse(localStorage.getItem("profile"));

  if(localProfile != undefined && localProfile.length>0)
  { this.profiles = localProfile; }

  else {
    this.profile = [
        { id: "1526", username: "berserk",      password: "berserk",    age: "31",          sex: "male"},
        { id: "1358", username: "Johnathan",    password: "test",       age: "17",          sex: "male"},
        { id: "2539", username: "Britney",      password: "test",       age: "18",          sex: "female"},
        { id: "1486", username: "Kevin",        password: "test",       age: "7",           sex: "male"},
        { id: "7777", username: "jesus",        password: "holy",       age: "unknown",     sex: "male"},
        { id: "6666", username: "satan",        password: "hell",       age: "unknown",     sex: "unknown"}
    ];
  }

  this.getProfile = function() {
     return this.profile;
  }
});

Body:
There are few mistakes in the above code,

(i)You need to inject the DataService to the controller.

(ii) You can just return the profiles as it is without using $scope

app.service("DataService", function() {
  console.log("DataService");
  var localProfile = JSON.parse(localStorage.getItem("profile"));
  var profiles = JSON.parse(localStorage.getItem("profile"));

  if (localProfile != undefined && localProfile.length > 0) {
    this.profiles = localProfile;
  } else {
    this.profiles = [{
      id: "1526",
      username: "berserk",
      password: "berserk",
      age: "31"
    }, {
      id: "1358",
      username: "Johnathan",
      password: "test",
      age: "17"
    }, {
      id: "2539",
      username: "Britney",
      password: "test",
      age: "18"
    }, {
      id: "1486",
      username: "Kevin",
      password: "test",
      age: "7"
    }];
  }

  this.getProfile = function() {
    return this.profiles;
  }
});

DEMO