问:
How to use vue-matrial tables in jsx?
I tried to create a table layout with vue matrial using jsx (typescript).

My attempt:

```<code>import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';

let c = 0;

@Component
export default class RadarAdminPage extends Vue {

    search = null;
    searched = [] as Array<any>;
    items = [{
        id: c++,
        name: "Paxon Lotterington",
        email: "plotteringtoni@netvibes.com",
        gender: "Female",
        title: "Marketing Assistant"
    }] as Array<any>;

    addItem() {
        this.items.push({
            id: c++,
            name: "Paxon Lotterington",
            email: "plotteringtoni@netvibes.com",
            gender: "Female",
            title: "Marketing Assistant"
        });

        this.searched = this.items;
    }
    searchOnTable() {
        console.log("a");
    }
    created() {
        this.searched = this.items;
    }
    render() {
        return (
            <div class="row">
                <div class="col-12">
                    <card>
                        <div>
                            <md-table v-model={this.searched} md-sort="name" md-sort-order="asc" md-card md-fixed-header>
                                <md-table-toolbar>
                                    <div class="md-toolbar-section-start">
                                        <h1 class="md-title">Users</h1>
                                    </div>

                                    <md-field md-clearable class="md-toolbar-section-end">
                                        <md-input placeholder="Search by name..." vModel={this.search} onInput={this.searchOnTable} />
                                    </md-field>
                                </md-table-toolbar>

                                <md-table-row slot="md-table-row" slot-scope="{ item }">
                                    <md-table-cell md-label="ID" md-sort-by="id" md-numeric>{"{{ item.id }}"}</md-table-cell>
                                    <md-table-cell md-label="Name" md-sort-by="name"> test</md-table-cell>
                                    <md-table-cell md-label="Email" md-sort-by="email"> test</md-table-cell>
                                    <md-table-cell md-label="Gender" md-sort-by="gender"> test</md-table-cell>
                                    <md-table-cell md-label="Job Title" md-sort-by="title"> test</md-table-cell>
                                </md-table-row>
                            </md-table>
                        </div>
                    </card>
                </div >
            </div >
        )
    }
}
</code>```

But i cant get it to work in any way.

It also render an artifact row at the bottom. Is it possible at all to use slot-scope with jsx?

答:
I also played with vuetify and ended up with similar results, until i figured it out and then i was also able to get it to work under vue-matrial.

Here is an example that renders two tables, with vuetify and vue-matrial.

```<code>import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';

import { VDataTable, VProgressLinear } from "vuetify-tsx";
import { VDataTable as Test } from 'vuetify/lib';

let c = 0;

@Component
export default class RadarAdminPage extends Vue {

    headers = [
        {
            text: "name",
            align: "left",
            sortable: true,
            value: "name"
        },
        {
            text: "Queue Name",
            value: "queue"
        }
    ]

    search = null;
    searched = [] as Array<any>;
    items = [ ] as Array<any>;

    addItem() {
        this.items.push({
            id: c++,
            name: "Paxon Lotterington",
            email: "plotteringtoni@netvibes.com",
            gender: "Female",
            title: "Marketing Assistant"
        });

        this.searched = this.items;
    }
    searchOnTable() {
        console.log("a");
    }
    created() {
        this.searched = this.items;
    }
    render() {
        console.log(this)
        return (
            <div class="row">
                <div class="col-12">

                    <VDataTable itemKey="id" slot="items:props" items={this.searched} headers={this.headers} scopedSlots={{
                        items: function (prop) {

                            return [
                                <td>{prop}</td>,
                                <td class="text-xs-right">vb</td>
                            ]
                        }
                    } as any}>
                        <VProgressLinear slot="progress" color="blue" indeterminate={true} />

                    </VDataTable>

                    <div>
                        <md-table value={this.searched} md-sort="name" md-sort-order="asc" md-card md-fixed-header scopedSlots={
                            {
                                "md-table-empty-state": (prop)=> {
                                    return (
                                        <md-table-empty-state
                                            md-label="No users found" md-description="`No user found for this '${search}' query. Try a different search term or create a new user.`">
                                            <md-button class="md-primary md-raised" onClick={this.addItem}>Create New User</md-button>
                                        </md-table-empty-state>
                                    )
                                },
                                "md-table-row": function (prop) {

                                    return (
                                        <md-table-row slot="md-table-row" >
                                            <md-table-cell md-label="ID" md-sort-by="id" md-numeric>{prop.item.id}</md-table-cell>
                                            <md-table-cell md-label="Name" md-sort-by="name">{prop.item.name}</md-table-cell>
                                            <md-table-cell md-label="Email" md-sort-by="email"> {prop.item.email}</md-table-cell>
                                            <md-table-cell md-label="Gender" md-sort-by="gender"> {prop.item.gender}</md-table-cell>
                                            <md-table-cell md-label="Job Title" md-sort-by="title"> {prop.item.title}</md-table-cell>
                                        </md-table-row>
                                    )
                                }
                            }
                        }>
                            <md-table-toolbar>
                                <div class="md-toolbar-section-start">
                                    <h1 class="md-title">Users</h1>
                                </div>

                                <md-field md-clearable class="md-toolbar-section-end">
                                    <md-input placeholder="Search by name..." vModel={this.search} onInput={this.searchOnTable} />
                                </md-field>
                            </md-table-toolbar>

                        </md-table>
                    </div>

                </div >
            </div >
        )
    }
}
</code>```

Title: How to use vue-matrial tables in jsx?

Body:
I tried to create a table layout with vue matrial using jsx (typescript).

My attempt:

import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';

let c = 0;

@Component
export default class RadarAdminPage extends Vue {

    search = null;
    searched = [] as Array<any>;
    items = [{
        id: c++,
        name: "Paxon Lotterington",
        email: "plotteringtoni@netvibes.com",
        gender: "Female",
        title: "Marketing Assistant"
    }] as Array<any>;

    addItem() {
        this.items.push({
            id: c++,
            name: "Paxon Lotterington",
            email: "plotteringtoni@netvibes.com",
            gender: "Female",
            title: "Marketing Assistant"
        });

        this.searched = this.items;
    }
    searchOnTable() {
        console.log("a");
    }
    created() {
        this.searched = this.items;
    }
    render() {
        return (

                    <card>

                            <md-table v-model={this.searched} md-sort="name" md-sort-order="asc" md-card md-fixed-header>
                                <md-table-toolbar>

Users

                                    <md-field md-clearable class="md-toolbar-section-end">
                                        <md-input placeholder="Search by name..." vModel={this.search} onInput={this.searchOnTable} />
                                    </md-field>
                                </md-table-toolbar>

                                <md-table-row slot="md-table-row" slot-scope="{ item }">
                                    <md-table-cell md-label="ID" md-sort-by="id" md-numeric>{"{{ item.id }}"}</md-table-cell>
                                    <md-table-cell md-label="Name" md-sort-by="name"> test</md-table-cell>
                                    <md-table-cell md-label="Email" md-sort-by="email"> test</md-table-cell>
                                    <md-table-cell md-label="Gender" md-sort-by="gender"> test</md-table-cell>
                                    <md-table-cell md-label="Job Title" md-sort-by="title"> test</md-table-cell>
                                </md-table-row>
                            </md-table>

                    </card>

        )
    }
}

But i cant get it to work in any way.

It also render an artifact row at the bottom. Is it possible at all to use slot-scope with jsx?

Body:
I also played with vuetify and ended up with similar results, until i figured it out and then i was also able to get it to work under vue-matrial.

Here is an example that renders two tables, with vuetify and vue-matrial.

import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';

import { VDataTable, VProgressLinear } from "vuetify-tsx";
import { VDataTable as Test } from 'vuetify/lib';

let c = 0;

@Component
export default class RadarAdminPage extends Vue {

    headers = [
        {
            text: "name",
            align: "left",
            sortable: true,
            value: "name"
        },
        {
            text: "Queue Name",
            value: "queue"
        }
    ]

    search = null;
    searched = [] as Array<any>;
    items = [ ] as Array<any>;

    addItem() {
        this.items.push({
            id: c++,
            name: "Paxon Lotterington",
            email: "plotteringtoni@netvibes.com",
            gender: "Female",
            title: "Marketing Assistant"
        });

        this.searched = this.items;
    }
    searchOnTable() {
        console.log("a");
    }
    created() {
        this.searched = this.items;
    }
    render() {
        console.log(this)
        return (
            <div class="row">
                <div class="col-12">

                    <VDataTable itemKey="id" slot="items:props" items={this.searched} headers={this.headers} scopedSlots={{
                        items: function (prop) {

                            return [
                                <td>{prop}</td>,
                                <td class="text-xs-right">vb</td>
                            ]
                        }
                    } as any}>
                        <VProgressLinear slot="progress" color="blue" indeterminate={true} />

                    </VDataTable>

                    <div>
                        <md-table value={this.searched} md-sort="name" md-sort-order="asc" md-card md-fixed-header scopedSlots={
                            {
                                "md-table-empty-state": (prop)=> {
                                    return (
                                        <md-table-empty-state
                                            md-label="No users found" md-description="`No user found for this '${search}' query. Try a different search term or create a new user.`">
                                            <md-button class="md-primary md-raised" onClick={this.addItem}>Create New User</md-button>
                                        </md-table-empty-state>
                                    )
                                },
                                "md-table-row": function (prop) {

                                    return (
                                        <md-table-row slot="md-table-row" >
                                            <md-table-cell md-label="ID" md-sort-by="id" md-numeric>{prop.item.id}</md-table-cell>
                                            <md-table-cell md-label="Name" md-sort-by="name">{prop.item.name}</md-table-cell>
                                            <md-table-cell md-label="Email" md-sort-by="email"> {prop.item.email}</md-table-cell>
                                            <md-table-cell md-label="Gender" md-sort-by="gender"> {prop.item.gender}</md-table-cell>
                                            <md-table-cell md-label="Job Title" md-sort-by="title"> {prop.item.title}</md-table-cell>
                                        </md-table-row>
                                    )
                                }
                            }
                        }>
                            <md-table-toolbar>
                                <div class="md-toolbar-section-start">
                                    <h1 class="md-title">Users</h1>
                                </div>

                                <md-field md-clearable class="md-toolbar-section-end">
                                    <md-input placeholder="Search by name..." vModel={this.search} onInput={this.searchOnTable} />
                                </md-field>
                            </md-table-toolbar>

                        </md-table>
                    </div>

                </div >
            </div >
        )
    }
}


来源: stackexchange

问:
How do you calculate the average of an array of arrays in Python?
Say we have the following:

a = [(R1, G1, B1),
     (R2, G2, B2),
     (R3, G3, B3)]
```

<p>How can I calculate the averages of the arrays and put it in a new array? Like the following:</p>

<pre class="lang-py prettyprint-override"><code>a = [(R, B, G)]
</code>```

Where R, G, B are the averages of R1, R2 and R3 etc.

答:
It can be done in a comprehension:

```<code>avgs = [sum(vals)/len(a) for vals in zip(*a)]
</code>```

As an example:

```<code>>>> a = [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
>>> avgs = [sum(vals)/len(a) for vals in zip(*a)]
>>> avgs
[1.0, 2.0, 3.0]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say we have the following:

a = [(R1, G1, B1),
     (R2, G2, B2),
     (R3, G3, B3)]

How can I calculate the averages of the arrays and put it in a new array? Like the following:

a = [(R, B, G)]

Where R, G, B are the averages of R1, R2 and R3 etc.

Body:
It can be done in a comprehension:

avgs = [sum(vals)/len(a) for vals in zip(*a)]

As an example:

>>> a = [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
>>> avgs = [sum(vals)/len(a) for vals in zip(*a)]
>>> avgs
[1.0, 2.0, 3.0]


问:
How to merge two columns of JTable
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

```<code>String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";
</code>```

But it gave me an error:

```<code>[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'
</code>```

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?

答:
Try using "&" instead of "||" if you really need to do it on query level.
I'm not sure if parentheses are needed.</p>

ContentLicense: CC BY-SA 3.0

Title: How to merge two columns of JTable

Body:
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";

But it gave me an error:

[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?


问:
It seems that the SQLite table had stopped being populated for unknown reason
The application worked fine, but then the method Cursor.moveToFirst() started returning false, and the Application's list has stopped appearing in a Fragment.

I think it all started after I changed a constat's name: IMAGE_URI to IMAGE_URL, and imageUri to imageUrl. Not sure though.

I tried debugging and searching for similar cases but there are many varied causes. When debugging, I couldn't get to the onCreate of the SQLiteHelper class in order to find out what happens during the population of the table (It seems that the table exists since an empty db of the table is being created), So I can't debug nor search for similar issues since no relevant output is found in the Logcat.

GetDatabase

This class is used for some of the communication with the SQLiteOpenHelper class.

```<code>public class GetDatabase {

    private static final int DB_VERSION = 1; //required for the constructor
    public static final String dbName = "moviesList";

    private SQLiteOpenHelper sqLiteOpenHelper;
    private SQLiteDatabase db ;

    public GetDatabase(Context context) {
        Log.d("GetDatabase", "Cont.");

        this.sqLiteOpenHelper = new SQLiteHelper(context, dbName, null, DB_VERSION);
    }

    public void open() {
       db = sqLiteOpenHelper.getWritableDatabase();
    }

    public void close() {
        if (sqLiteOpenHelper != null) {
            sqLiteOpenHelper.close();
        }
    }

    public ArrayList<Movie> getMovies() {
        String[] columns = {
                Movie.ID,
                Movie.TITLE,
                Movie.IMAGE_URL,
                Movie.RATING,
                Movie.RELEASE_YEAR,
                Movie.GENRE
        };

        // sorting orders
        String sortOrder =
                Movie.RELEASE_YEAR + " ASC";
        ArrayList<Movie> moviesList = new ArrayList<>();

        Cursor cursor = db.query(TABLE_NAME, //Table to query
                columns,
                null,
                null,
                null,
                null,
                sortOrder);

        if (cursor.moveToFirst()) {
            do {
                Movie movie = new Movie();
                movie.setMovieId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Movie.ID))));
                movie.setTitle(cursor.getString(cursor.getColumnIndex(Movie.TITLE)));
                movie.setImageUrl(cursor.getString(cursor.getColumnIndex(Movie.IMAGE_URL)));
                movie.setRating(cursor.getDouble(cursor.getColumnIndex(Movie.RATING)));
                movie.setReleaseYear(cursor.getInt(cursor.getColumnIndex(Movie.RELEASE_YEAR)));
                movie.setGenre(cursor.getString(cursor.getColumnIndex(Movie.GENRE)));
                // Adding a movie to the list
                moviesList.add(movie);
            } while (cursor.moveToNext());
        }
        Log.d(TAG, "The movies list from sqlite: " + moviesList);
        cursor.close();
        db.close();

        return moviesList;
    }

    private Cursor getData(int id) {
        return db.rawQuery( "select * from " + TABLE_NAME + " where id="+id+"", null );
    }

    public Cursor getMovieDetails(int movieId) {// For viewing details of a specific item

        Cursor cursor = getData(movieId);
        cursor.moveToFirst();

        return cursor;
    }
}

</code>```

SQliteHelper

The SQLiteOpenHelper class

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "movies.db";
    private static final int DB_VERSION = 1; //required for the constructor
    private static final String TABLE_NAME = "movies";

    private String fileName = "movies.json";
    private String appName = "MoviesList";
    private String path = getExternalStorageDirectory() + "/" + appName + "/" + fileName;

    private String jsonString = null;

    private SQLiteDatabase db;

    // The cont. for saving to SQLite .Called from SplashActivity after downloading the JSON
    public SQLiteHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        Log.d(TAG, "At SQLiteHelper");

        createSQLIteTable(db);
        if(tableIsEmpty(db)) {
            try {
                parseJsonAndInsertToSQLIte(db);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private void createSQLIteTable(SQLiteDatabase db) {

        //creating a table for SQLite
        String CREATE_SQL_TABLE_STRING = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME
                + " ("
                + Movie.ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
                + Movie.TITLE + " TEXT,"
                + Movie.IMAGE_URL + " TEXT,"
                + Movie.RATING + " TEXT,"
                + Movie.RELEASE_YEAR + " TEXT,"
                + Movie.GENRE + " TEXT "
                + ")";

        Log.i(TAG,"created sql table: "+CREATE_SQL_TABLE_STRING);

        db.execSQL(CREATE_SQL_TABLE_STRING);
    }

    private void parseJsonAndInsertToSQLIte(SQLiteDatabase db) throws JSONException {
        // parsing the json
        String jsonString = getJsonFileData();
        JSONArray moviesArray = new JSONArray(jsonString);
        ContentValues insertValues;

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject jsonObject = moviesArray.getJSONObject(i);

            String title = jsonObject.getString("title");
            String imageUrl = jsonObject.getString("imageUrl");
            String rating = jsonObject.getString("rating");
            String releaseYear = jsonObject.getString("releaseYear");
            String genre = jsonObject.getString("genre");

            insertValues = new ContentValues();

            insertValues.put(Movie.TITLE, title);
            insertValues.put(Movie.IMAGE_URL, imageUrl);
            insertValues.put(Movie.RATING, rating);
            insertValues.put(Movie.RELEASE_YEAR, releaseYear);
            insertValues.put(Movie.GENRE, genre);
            long res = db.insert(TABLE_NAME, null, insertValues);

            Log.i(TAG, "parsed and inserted to sql - row: " + res);
        }
    }

    private String getJsonFileData() {
        //loading the jsonString
        try {
            InputStream in = new FileInputStream(new File(path));
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder output = new StringBuilder();
            while ((jsonString = reader.readLine()) != null) {
                output.append(jsonString);
            }
            System.out.println(output.toString());   //Prints the string content read from input stream

            jsonString = output.toString();
            Log.d(TAG, "the jsonString was loaded");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return jsonString;
    }
}
</code>```

If I don't solve this, I think the entire application is worthless, since I don't know what mistake needs to be corrected.

Thanks!

答:
Clear your application data from setting and run your application again. Since you have made changes in database column, it will not reflect unless you clear data.

Or

Do proper handling with DB version. Drop all tables in onUpgrade method and increase DB version every time you made changes in DB structure.

EDIT: Clear Data window

Body:
The application worked fine, but then the method Cursor.moveToFirst() started returning false, and the Application's list has stopped appearing in a Fragment.

I think it all started after I changed a constat's name: IMAGE_URI to IMAGE_URL, and imageUri to imageUrl. Not sure though.

I tried debugging and searching for similar cases but there are many varied causes. When debugging, I couldn't get to the onCreate of the SQLiteHelper class in order to find out what happens during the population of the table (It seems that the table exists since an empty db of the table is being created), So I can't debug nor search for similar issues since no relevant output is found in the Logcat.

GetDatabase

This class is used for some of the communication with the SQLiteOpenHelper class.

public class GetDatabase {

    private static final int DB_VERSION = 1; //required for the constructor
    public static final String dbName = "moviesList";

    private SQLiteOpenHelper sqLiteOpenHelper;
    private SQLiteDatabase db ;

    public GetDatabase(Context context) {
        Log.d("GetDatabase", "Cont.");

        this.sqLiteOpenHelper = new SQLiteHelper(context, dbName, null, DB_VERSION);
    }

    public void open() {
       db = sqLiteOpenHelper.getWritableDatabase();
    }

    public void close() {
        if (sqLiteOpenHelper != null) {
            sqLiteOpenHelper.close();
        }
    }

    public ArrayList<Movie> getMovies() {
        String[] columns = {
                Movie.ID,
                Movie.TITLE,
                Movie.IMAGE_URL,
                Movie.RATING,
                Movie.RELEASE_YEAR,
                Movie.GENRE
        };

        // sorting orders
        String sortOrder =
                Movie.RELEASE_YEAR + " ASC";
        ArrayList<Movie> moviesList = new ArrayList<>();

        Cursor cursor = db.query(TABLE_NAME, //Table to query
                columns,
                null,
                null,
                null,
                null,
                sortOrder);

        if (cursor.moveToFirst()) {
            do {
                Movie movie = new Movie();
                movie.setMovieId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Movie.ID))));
                movie.setTitle(cursor.getString(cursor.getColumnIndex(Movie.TITLE)));
                movie.setImageUrl(cursor.getString(cursor.getColumnIndex(Movie.IMAGE_URL)));
                movie.setRating(cursor.getDouble(cursor.getColumnIndex(Movie.RATING)));
                movie.setReleaseYear(cursor.getInt(cursor.getColumnIndex(Movie.RELEASE_YEAR)));
                movie.setGenre(cursor.getString(cursor.getColumnIndex(Movie.GENRE)));
                // Adding a movie to the list
                moviesList.add(movie);
            } while (cursor.moveToNext());
        }
        Log.d(TAG, "The movies list from sqlite: " + moviesList);
        cursor.close();
        db.close();

        return moviesList;
    }

    private Cursor getData(int id) {
        return db.rawQuery( "select * from " + TABLE_NAME + " where id="+id+"", null );
    }

    public Cursor getMovieDetails(int movieId) {// For viewing details of a specific item

        Cursor cursor = getData(movieId);
        cursor.moveToFirst();

        return cursor;
    }
}

SQliteHelper

The SQLiteOpenHelper class

public class SQLiteHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "movies.db";
    private static final int DB_VERSION = 1; //required for the constructor
    private static final String TABLE_NAME = "movies";

    private String fileName = "movies.json";
    private String appName = "MoviesList";
    private String path = getExternalStorageDirectory() + "/" + appName + "/" + fileName;

    private String jsonString = null;

    private SQLiteDatabase db;

    // The cont. for saving to SQLite .Called from SplashActivity after downloading the JSON
    public SQLiteHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        Log.d(TAG, "At SQLiteHelper");

        createSQLIteTable(db);
        if(tableIsEmpty(db)) {
            try {
                parseJsonAndInsertToSQLIte(db);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private void createSQLIteTable(SQLiteDatabase db) {

        //creating a table for SQLite
        String CREATE_SQL_TABLE_STRING = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME
                + " ("
                + Movie.ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
                + Movie.TITLE + " TEXT,"
                + Movie.IMAGE_URL + " TEXT,"
                + Movie.RATING + " TEXT,"
                + Movie.RELEASE_YEAR + " TEXT,"
                + Movie.GENRE + " TEXT "
                + ")";

        Log.i(TAG,"created sql table: "+CREATE_SQL_TABLE_STRING);

        db.execSQL(CREATE_SQL_TABLE_STRING);
    }

    private void parseJsonAndInsertToSQLIte(SQLiteDatabase db) throws JSONException {
        // parsing the json
        String jsonString = getJsonFileData();
        JSONArray moviesArray = new JSONArray(jsonString);
        ContentValues insertValues;

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject jsonObject = moviesArray.getJSONObject(i);

            String title = jsonObject.getString("title");
            String imageUrl = jsonObject.getString("imageUrl");
            String rating = jsonObject.getString("rating");
            String releaseYear = jsonObject.getString("releaseYear");
            String genre = jsonObject.getString("genre");

            insertValues = new ContentValues();

            insertValues.put(Movie.TITLE, title);
            insertValues.put(Movie.IMAGE_URL, imageUrl);
            insertValues.put(Movie.RATING, rating);
            insertValues.put(Movie.RELEASE_YEAR, releaseYear);
            insertValues.put(Movie.GENRE, genre);
            long res = db.insert(TABLE_NAME, null, insertValues);

            Log.i(TAG, "parsed and inserted to sql - row: " + res);
        }
    }

    private String getJsonFileData() {
        //loading the jsonString
        try {
            InputStream in = new FileInputStream(new File(path));
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder output = new StringBuilder();
            while ((jsonString = reader.readLine()) != null) {
                output.append(jsonString);
            }
            System.out.println(output.toString());   //Prints the string content read from input stream

            jsonString = output.toString();
            Log.d(TAG, "the jsonString was loaded");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return jsonString;
    }
}

If I don't solve this, I think the entire application is worthless, since I don't know what mistake needs to be corrected.

Thanks!


问:
How can I escape braces in string to be fed to sub process
```<code>    import subprocess
    profile_val = 'ishan'
    cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update' + ' ' + profile_val)
    subprocess.call(cmd.split())
</code>```

It not escaping braces in {likes} and treats like as separate part command and fails.

答:
No, your problem is that you're using split() to construct the list of arguments to the command to execute. You're also using quotes, which are shell syntax even though you're not invoking a shell.

Just use an array in the first place, so not to have to split:

cmd = ('instaloader', '--post-metadata-txt={likes} likes, {comments} comments, {caption}', '--login=blabla_id', '--fast-update', profile_val)
subprocess.call(cmd)
```

Body:
    import subprocess
    profile_val = 'ishan'
    cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update' + ' ' + profile_val)
    subprocess.call(cmd.split())

It not escaping braces in {likes} and treats like as separate part command and fails.

OwnerDisplayName: Stephane Chazelas


问:
How to access selectedItems of a ListBox from ShellViewModel.cs file?
So here is my problem:

I want to access the items (and their properties), which are bound to a ListBox via a Bindable Collection, in a method of another class. (ShellViewModel)
More precise: I want to know which Items in this List are currently selected.

I'm using C#,Caliburn.Micro and the design pattern should be MVVM.

If the Button "Evaluate" is pressed, according to the selected ListBoxItems, different Methods get called.

So the XAML-Code in the ShellView is working fine, and also the "functional" code "works", but it is just working if I code directly in the xaml.cs-file. (big no,no)

Because I'm quite new to this topics, I've tried to create a new instance of the View for the access, but this will just give me control over the ListBox without "knowing" which Items are selected in the original instance.

Here is the general ListBox

```<code><ListBox x:Name="MainListBox" ItemsSource="{Binding SCollection}"
           Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="6" Grid.RowSpan="1"
           SelectionMode="Multiple"
                  ScrollViewer.VerticalScrollBarVisibility="Visible"
            ScrollViewer.HorizontalScrollBarVisibility="Visible"
                 MaxHeight="300" MinHeight="200" MaxWidth="340" Margin="5">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="0,5">
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3,5,5,5" />
                            <TextBlock Text="{Binding Path=Info}" FontWeight="SemiBold" Padding="3,5,5,5" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>
</code>```

```<code><Button x:Name="Evaluate" Background="Blue" Grid.Column="1" Grid.Row="7" MinWidth="80" Margin="5" Content="Test" Grid.ColumnSpan="1" />
</code>```

So here are some questions:

Is there a similar solution like the binding of "SelectedItem" via xaml, which is bound to accessible variable, for multiple selected Items?(maybe I just missed something there?)

Is there a way to access the "original" instance of the ListBox(and therefore "live"-selected Items)?

To be clear:
Only problem, besides maybe other better solutions out there, is that, I want the called Method "Evaluate", which is bound to the button, have access to the great knowledge of which Items are selected in my ListBox.

答:
I believe I understood your concern correctly. For the Evaluate method to have the knowledge of which Items has been selected, you can adopt the following strategy.

Add a boolean property in your Collection Type called IsSelected, which would help in tracking the items which are selected. For example,

```<code>public class Contact : PropertyChangedBase
{
    public string Name { get; set; }
    public string Info { get; set; }
    public bool IsSelected { get; set; }
}
</code>```

Now assuming your Collection is defined as following.

public ObservableCollection SCollection { get; set; } = new ObservableCollection();

You can filter the Selected items in Evaluate Method as following.

```<code>public void Evaluate()
{
    var selected = SCollection.Where(x => x.IsSelected);
}
</code>```

Update

You would need to Set the IsSelected Property to true during the selection in the List box. This can be done as following.

```<code><ListBox x:Name="MainListBox" ItemsSource="{Binding SCollection}"
                 SelectionMode="Multiple"
                 ScrollViewer.VerticalScrollBarVisibility="Visible"
                 ScrollViewer.HorizontalScrollBarVisibility="Visible"
                 MaxHeight="300" MinHeight="200" MaxWidth="340" Margin="5">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="0,5">
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3,5,5,5" />
                            <TextBlock Text="{Binding Path=Info}" FontWeight="SemiBold" Padding="3,5,5,5" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
</code>```

Example Screenshot

Body:
So here is my problem:

I want to access the items (and their properties), which are bound to a ListBox via a Bindable Collection, in a method of another class. (ShellViewModel)
More precise: I want to know which Items in this List are currently selected.

I'm using C#,Caliburn.Micro and the design pattern should be MVVM.

If the Button "Evaluate" is pressed, according to the selected ListBoxItems, different Methods get called.

So the XAML-Code in the ShellView is working fine, and also the "functional" code "works", but it is just working if I code directly in the xaml.cs-file. (big no,no)

Because I'm quite new to this topics, I've tried to create a new instance of the View for the access, but this will just give me control over the ListBox without "knowing" which Items are selected in the original instance.

Here is the general ListBox

<ListBox x:Name="MainListBox" ItemsSource="{Binding SCollection}"
           Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="6" Grid.RowSpan="1"
           SelectionMode="Multiple"
                  ScrollViewer.VerticalScrollBarVisibility="Visible"
            ScrollViewer.HorizontalScrollBarVisibility="Visible"
                 MaxHeight="300" MinHeight="200" MaxWidth="340" Margin="5">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="0,5">
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3,5,5,5" />
                            <TextBlock Text="{Binding Path=Info}" FontWeight="SemiBold" Padding="3,5,5,5" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

<Button x:Name="Evaluate" Background="Blue" Grid.Column="1" Grid.Row="7" MinWidth="80" Margin="5" Content="Test" Grid.ColumnSpan="1" />

So here are some questions:

Is there a similar solution like the binding of "SelectedItem" via xaml, which is bound to accessible variable, for multiple selected Items?(maybe I just missed something there?)

Is there a way to access the "original" instance of the ListBox(and therefore "live"-selected Items)?

To be clear:
Only problem, besides maybe other better solutions out there, is that, I want the called Method "Evaluate", which is bound to the button, have access to the great knowledge of which Items are selected in my ListBox.

Body:
I believe I understood your concern correctly. For the Evaluate method to have the knowledge of which Items has been selected, you can adopt the following strategy.

Add a boolean property in your Collection Type called IsSelected, which would help in tracking the items which are selected. For example,

public class Contact : PropertyChangedBase
{
    public string Name { get; set; }
    public string Info { get; set; }
    public bool IsSelected { get; set; }
}

Now assuming your Collection is defined as following.

public ObservableCollection SCollection { get; set; } = new ObservableCollection();

You can filter the Selected items in Evaluate Method as following.

public void Evaluate()
{
    var selected = SCollection.Where(x => x.IsSelected);
}

Update

You would need to Set the IsSelected Property to true during the selection in the List box. This can be done as following.

<ListBox x:Name="MainListBox" ItemsSource="{Binding SCollection}"
                 SelectionMode="Multiple"
                 ScrollViewer.VerticalScrollBarVisibility="Visible"
                 ScrollViewer.HorizontalScrollBarVisibility="Visible"
                 MaxHeight="300" MinHeight="200" MaxWidth="340" Margin="5">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="0,5">
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3,5,5,5" />
                            <TextBlock Text="{Binding Path=Info}" FontWeight="SemiBold" Padding="3,5,5,5" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>

Example Screenshot


问:
Download csvs to desktop from csv links
Problem:

Don't know if google fu is failing me again but I am unable to download csvs from a list of urls. I have used requests and bs4 to gather the urls (the final list is correct) - see process below for more info.

I then followed  one of the answers given here using urllib to download: Trying to download data from URL with CSV File,  as well as a number other stackoverflow python answers for downloading csvs.

Currently I am stuck with an

HTTP Error 404: Not Found

(below stack trace is from last attempt where passing User-Agent)

```<code>----> 9 f = urllib.request.urlopen(req)
     10 print(f.read().decode('utf-8'))
     #other lines

--> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    651
    652 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 404: Not Found
</code>```

I tried the solution here of adding a User-Agent: Web Scraping using Python giving HTTP Error 404: Not Found , though I would have expected a 403 not 404 error code - but seems to have worked for a number of OPs.

This still failed with same error. I am pretty sure I can solve this by simply using selenium and passing the csv urls to .get but I want to know if I can solve this with requests alone.

Outline:

I visit this this page:

https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice

I grab all the monthly version links e.g. Patients Registered at a GP Practice May 2019, I then visit each of those pages and grab all the csv links within.

I loop the final dictionary of filename:download_url pairs attempting to download the files.

Question:

Can anyone see what I am doing wrong or how to fix this so I can download the files without resorting to selenium? I'm also unsure of the most efficient way to accomplish this - perhaps urllib is not actually required at all and just requests will suffice?

Python:

Without user-agent:

```<code>import requests
from bs4 import BeautifulSoup as bs
import urllib

base = 'https://digital.nhs.uk/'
all_files = []

with requests.Session() as s:
    r = s.get('https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice')
    soup = bs(r.content, 'lxml')
    links = [base + item['href'] for item in soup.select('.cta__button')]

    for link in links:
        r = s.get(link)
        soup = bs(r.content, 'lxml')
        file_links = {item.text.strip().split('\n')[0]:base + item['href'] for item in soup.select('[href$=".csv"]')}
        if file_links:
            all_files.append(file_links)  #ignore empty dicts as for some months there is no data yet
        else:
            print('no data : ' + link)

all_files = {k: v for d in all_files for k, v in d.items()}  #flatten list of dicts to single dict

path = r'C:\Users\User\Desktop'

for k,v in all_files.items():
    #print(k,v)
    print(v)
    response = urllib.request.urlopen(v)
    html = response.read()

    with open(path + '\\' + k + '.csv', 'wb') as f:
        f.write(html)
    break  #as only need one test case
</code>```

Test with adding User-Agent:

```<code>req = urllib.request.Request(
    v,
    data=None,
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    }
)

f = urllib.request.urlopen(req)
print(f.read().decode('utf-8'))
</code>```

答:
looking at the values, it's showing me for your links

```<code>https://digital.nhs.uk/https://files.digital.nhs.uk/publicationimport/pub13xxx/pub13932/gp-reg-patients-04-2014-lsoa.csv
</code>```

I think you want to drop the base +, so use this:

```<code>file_links = {item.text.strip().split('\n')[0]:item['href'] for item in soup.select('[href$=".csv"]')}
</code>```

instead of:

```<code>file_links = {item.text.strip().split('\n')[0]:base + item['href'] for item in soup.select('[href$=".csv"]')}
</code>```

Edit: Full Code:

```<code>import requests
from bs4 import BeautifulSoup as bs

base = 'https://digital.nhs.uk/'
all_files = []

with requests.Session() as s:
    r = s.get('https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice')
    soup = bs(r.content, 'lxml')
    links = [base + item['href'] for item in soup.select('.cta__button')]

    for link in links:
        r = s.get(link)
        soup = bs(r.content, 'lxml')
        file_links = {item.text.strip().split('\n')[0]:item['href'] for item in soup.select('[href$=".csv"]')}
        if file_links:
            all_files.append(file_links)  #ignore empty dicts as for some months there is no data yet
        else:
            print('no data : ' + link)

all_files = {k: v for d in all_files for k, v in d.items()}  #flatten list of dicts to single dict

path = 'C:/Users/User/Desktop/'

for k,v in all_files.items():
    #print(k,v)
    print(v)
    response = requests.get(v)
    html = response.content

    k = k.replace(':', ' -')
    file = path + k + '.csv'

    with open(file, 'wb' ) as f:
        f.write(html)
    break  #as only need one test case
</code>```

Title: Download csvs to desktop from csv links

Body:
Problem:

Don't know if google fu is failing me again but I am unable to download csvs from a list of urls. I have used requests and bs4 to gather the urls (the final list is correct) - see process below for more info.

I then followed  one of the answers given here using urllib to download: Trying to download data from URL with CSV File,  as well as a number other stackoverflow python answers for downloading csvs.

Currently I am stuck with an

HTTP Error 404: Not Found

(below stack trace is from last attempt where passing User-Agent)

----> 9 f = urllib.request.urlopen(req)
     10 print(f.read().decode('utf-8'))
     #other lines

--> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    651
    652 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 404: Not Found

I tried the solution here of adding a User-Agent: Web Scraping using Python giving HTTP Error 404: Not Found , though I would have expected a 403 not 404 error code - but seems to have worked for a number of OPs.

This still failed with same error. I am pretty sure I can solve this by simply using selenium and passing the csv urls to .get but I want to know if I can solve this with requests alone.

Outline:

I visit this this page:

https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice

I grab all the monthly version links e.g. Patients Registered at a GP Practice May 2019, I then visit each of those pages and grab all the csv links within.

I loop the final dictionary of filename:download_url pairs attempting to download the files.

Question:

Can anyone see what I am doing wrong or how to fix this so I can download the files without resorting to selenium? I'm also unsure of the most efficient way to accomplish this - perhaps urllib is not actually required at all and just requests will suffice?

Python:

Without user-agent:

import requests
from bs4 import BeautifulSoup as bs
import urllib

base = 'https://digital.nhs.uk/'
all_files = []

with requests.Session() as s:
    r = s.get('https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice')
    soup = bs(r.content, 'lxml')
    links = [base + item['href'] for item in soup.select('.cta__button')]

    for link in links:
        r = s.get(link)
        soup = bs(r.content, 'lxml')
        file_links = {item.text.strip().split('\n')[0]:base + item['href'] for item in soup.select('[href$=".csv"]')}
        if file_links:
            all_files.append(file_links)  #ignore empty dicts as for some months there is no data yet
        else:
            print('no data : ' + link)

all_files = {k: v for d in all_files for k, v in d.items()}  #flatten list of dicts to single dict

path = r'C:\Users\User\Desktop'

for k,v in all_files.items():
    #print(k,v)
    print(v)
    response = urllib.request.urlopen(v)
    html = response.read()

    with open(path + '\\' + k + '.csv', 'wb') as f:
        f.write(html)
    break  #as only need one test case

Test with adding User-Agent:

req = urllib.request.Request(
    v,
    data=None,
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    }
)

f = urllib.request.urlopen(req)
print(f.read().decode('utf-8'))

Body:
looking at the values, it's showing me for your links

https://digital.nhs.uk/https://files.digital.nhs.uk/publicationimport/pub13xxx/pub13932/gp-reg-patients-04-2014-lsoa.csv

I think you want to drop the base +, so use this:

file_links = {item.text.strip().split('\n')[0]:item['href'] for item in soup.select('[href$=".csv"]')}

instead of:

file_links = {item.text.strip().split('\n')[0]:base + item['href'] for item in soup.select('[href$=".csv"]')}

Edit: Full Code:

import requests
from bs4 import BeautifulSoup as bs

base = 'https://digital.nhs.uk/'
all_files = []

with requests.Session() as s:
    r = s.get('https://digital.nhs.uk/data-and-information/publications/statistical/patients-registered-at-a-gp-practice')
    soup = bs(r.content, 'lxml')
    links = [base + item['href'] for item in soup.select('.cta__button')]

    for link in links:
        r = s.get(link)
        soup = bs(r.content, 'lxml')
        file_links = {item.text.strip().split('\n')[0]:item['href'] for item in soup.select('[href$=".csv"]')}
        if file_links:
            all_files.append(file_links)  #ignore empty dicts as for some months there is no data yet
        else:
            print('no data : ' + link)

all_files = {k: v for d in all_files for k, v in d.items()}  #flatten list of dicts to single dict

path = 'C:/Users/User/Desktop/'

for k,v in all_files.items():
    #print(k,v)
    print(v)
    response = requests.get(v)
    html = response.content

    k = k.replace(':', ' -')
    file = path + k + '.csv'

    with open(file, 'wb' ) as f:
        f.write(html)
    break  #as only need one test case


问:
Laravel FileNotFoundException thrown even though file exists
I ran into a problem today to which I can't seem to find a solution.

I'm creating a class for image upload. The upload itself works fine, but when I try to use the uploaded file for creating a thumbnail, for some reason the file can't be found.

My code:

```<code>private static $imageTypes = [
    "image/jpeg", "image/png", "image/gif", "image/x-ms-bmp"
];

public function upload(UploadedFile $file, $folder = 'common')
{
    if (!$this->isImage($file)) {
        return false;
    }

    $path = $this->createPath($file, $folder);

    try {
        $file->move($path, $file->getClientOriginalName());
        $filePath = sprintf("%s/%s", $path, $file->getClientOriginalName());
    } catch (FileException $e) {
        return false;
    }

    $realPath = 'public/' . $filePath;
    //dd(File::exists($realPath)); - this returns false
    //dd(File::get($realPath)); - this throws the exception
    $image = Image::make(File::get($realPath));

    // Code for creating a thumbnail - not implemented yet.
    $thumbnailPath = '';

    return [
        'image' => $path,
        'thumbnail' => $thumbnailPath
    ];
}

private function isImage(UploadedFile $file)
{
    $type = $file->getClientMimeType();

    return in_array($type, self::$imageTypes);
}

private function createPath(UploadedFile $file, $folder)
{
    $time = Carbon::now();

    $path = sprintf(
        'Code/images/uploads/%s/%d-%d',
        $folder,
        $time->year,
        $time->month
    );

    return $path;
}
</code>```

I know the file gets uploaded, but I have no idea why it can't be found. I've tried the same action using php artisan tinker and it works there, so the problem is not in the file path.

The only idea that I've come up so far is that is related to directory permissions, but I haven't been able to verify it yet.

答:
I have fallen in the same situation recently, so here is a hint

Laravel after version 5 seems to allow dealing with files (get/put) only when using declared storage defined into filesystems.php

In that case the user must use 'local' or 'public' storage for getting the image or file stored.
According to the code above, please do the following

edit config/filesystems.php find local and make the following change

```<code>'local' => [
   'driver' => 'local',
   'root' => storage_path('app/local/common'),
],
</code>```

In order to read the file (ie 'image1.jpg') (get)

```<code>$afile = storage::disk('public')->get('image1.jpg');
</code>```

In your case:

```<code>$realpath =  'image1.jpg'; //**Just the filename**
$image = Image::make(storage::disk('local')->get($realPath));
</code>```

Hope this helps

Body:
I ran into a problem today to which I can't seem to find a solution.

I'm creating a class for image upload. The upload itself works fine, but when I try to use the uploaded file for creating a thumbnail, for some reason the file can't be found.

My code:

private static $imageTypes = [
    "image/jpeg", "image/png", "image/gif", "image/x-ms-bmp"
];

public function upload(UploadedFile $file, $folder = 'common')
{
    if (!$this->isImage($file)) {
        return false;
    }

    $path = $this->createPath($file, $folder);

    try {
        $file->move($path, $file->getClientOriginalName());
        $filePath = sprintf("%s/%s", $path, $file->getClientOriginalName());
    } catch (FileException $e) {
        return false;
    }

    $realPath = 'public/' . $filePath;
    //dd(File::exists($realPath)); - this returns false
    //dd(File::get($realPath)); - this throws the exception
    $image = Image::make(File::get($realPath));

    // Code for creating a thumbnail - not implemented yet.
    $thumbnailPath = '';

    return [
        'image' => $path,
        'thumbnail' => $thumbnailPath
    ];
}

private function isImage(UploadedFile $file)
{
    $type = $file->getClientMimeType();

    return in_array($type, self::$imageTypes);
}

private function createPath(UploadedFile $file, $folder)
{
    $time = Carbon::now();

    $path = sprintf(
        'Code/images/uploads/%s/%d-%d',
        $folder,
        $time->year,
        $time->month
    );

    return $path;
}

I know the file gets uploaded, but I have no idea why it can't be found. I've tried the same action using php artisan tinker and it works there, so the problem is not in the file path.

The only idea that I've come up so far is that is related to directory permissions, but I haven't been able to verify it yet.

Body:
I have fallen in the same situation recently, so here is a hint

Laravel after version 5 seems to allow dealing with files (get/put) only when using declared storage defined into filesystems.php

In that case the user must use 'local' or 'public' storage for getting the image or file stored.
According to the code above, please do the following

edit config/filesystems.php find local and make the following change

'local' => [
   'driver' => 'local',
   'root' => storage_path('app/local/common'),
],

In order to read the file (ie 'image1.jpg') (get)

$afile = storage::disk('public')->get('image1.jpg');

In your case:

$realpath =  'image1.jpg'; //**Just the filename**
$image = Image::make(storage::disk('local')->get($realPath));

Hope this helps


问:
Use REGEX to swap order of terms around a comma where the terms have a certain class
hopeless at this sort of stuff so grateful for any help.

I have a list of c80000 terms in format like this:

```<code><term>
    <termId>100323N166777388LGH3cj24jYcDY75lTgZl</termId>
    <termName>term1</termName>
    <termType>UNUSE</termType>
       <relation>
      <relationType>USE</relationType>
      <termId>OMITERMO6650</termId>
      <termName>term3, term4</termName>
    </relation>
  </term>
  <term>
    <termId>OMITERMO6650</termId>
      <termName>term3, term4</termName>
    <termType>Pt</termType>
     </term>
</code>```

is it possible to write a regex (or else any other find and replace in notepad++) to swap the order of terms around if there is a comma in a tag which has <termType>Pt</termType> and is referenced in <relation> attributes.  So in the example, term 3 and 4 would be swapped.

Not all PT terms are referenced in <relation>, but where they are they'd need to be swapped too.  Also, not all terms have a comma seperating values in them, so they should be ignored

Hopefully this makes sense, many thanks!

答:
```<code>echo "<termName>term3, term4</termName>" | sed -E 's/<termName>(.*), (.*)<\/termName>/<tN>\2, \1<\/tn>/'
<tn>term4, term3</tn>
</code>```

Of course I just used 'tn' as abbreviation. Regex in Notepad++ might differ - maybe you have to mask the parentheses with backslash. It swaps inside termName everywhere - I hope I understood this right.

It will not be sensitive to comments, and it will not match tags, spanning over multiple rows. But of course, it is easy to test your file beforewards (grep for all 'termnames') for the second case, and comments might not be a problem.

Body:
hopeless at this sort of stuff so grateful for any help.

I have a list of c80000 terms in format like this:

<term>
    <termId>100323N166777388LGH3cj24jYcDY75lTgZl</termId>
    <termName>term1</termName>
    <termType>UNUSE</termType>
       <relation>
      <relationType>USE</relationType>
      <termId>OMITERMO6650</termId>
      <termName>term3, term4</termName>
    </relation>
  </term>
  <term>
    <termId>OMITERMO6650</termId>
      <termName>term3, term4</termName>
    <termType>Pt</termType>
     </term>

is it possible to write a regex (or else any other find and replace in notepad++) to swap the order of terms around if there is a comma in a tag which has <termType>Pt</termType> and is referenced in <relation> attributes.  So in the example, term 3 and 4 would be swapped.

Not all PT terms are referenced in <relation>, but where they are they'd need to be swapped too.  Also, not all terms have a comma seperating values in them, so they should be ignored

Hopefully this makes sense, many thanks!

Body:
echo "<termName>term3, term4</termName>" | sed -E 's/<termName>(.*), (.*)<\/termName>/<tN>\2, \1<\/tn>/'
<tn>term4, term3</tn>

Of course I just used 'tn' as abbreviation. Regex in Notepad++ might differ - maybe you have to mask the parentheses with backslash. It swaps inside termName everywhere - I hope I understood this right.

It will not be sensitive to comments, and it will not match tags, spanning over multiple rows. But of course, it is easy to test your file beforewards (grep for all 'termnames') for the second case, and comments might not be a problem.


问:
RegeneratorRuntime is not defined
I am trying to run Karma-babel-preprocessor and a straight forward ES6 generator:

```<code>//require('babel/polyfill');

  describe("how Generators work", function() {
    it("will allow generator functions", function() {
      /*function * numbers() {
        yield 1;
        yield 2;
        yield 3;
      };*/

      let numbers = {
        [Symbol.iterator]:function*(){
            yield 1;
            yield 2;
            yield 3;
          }
      }

      let sum = 0;

      for(n of numbers){
        sum += n;
      }

      expect(sum).toBe(6);
    });
  });
</code>```

From this I generated my test files (ES6 => ES5) with babel:

babel src --watch --out-dir tests

Then I run karma start I get error:

ReferenceError: regeneratorRuntime is not defined".

Relevant bits in karma.conf.js:

```<code>  // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      {pattern: 'tests/*.js', included: true}
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
            'src/*.js': ['babel']
    },
        'babelPreprocessor': {
      options: {
        sourceMap: 'inline'
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    },

// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
</code>```

Full project on github

I am able to use many ES6 features including arrows.  Just no go on Generators.

答:
If you use React, adding polyfills from create-react-app worked for me.

```<code>yarn add --dev react-app-polyfill
</code>```

Then add the following lines to webpack.config.js

```<code>entry: {
  app: [
    'react-app-polyfill/ie9', // Only if you want to support IE 9
    'react-app-polyfill/stable',
    './src/index.jsx',
  ],
},
</code>```

See more examples on the react-app-polyfill GitHub page.

Title: RegeneratorRuntime is not defined

Body:
I am trying to run Karma-babel-preprocessor and a straight forward ES6 generator:

//require('babel/polyfill');

  describe("how Generators work", function() {
    it("will allow generator functions", function() {
      /*function * numbers() {
        yield 1;
        yield 2;
        yield 3;
      };*/

      let numbers = {
        [Symbol.iterator]:function*(){
            yield 1;
            yield 2;
            yield 3;
          }
      }

      let sum = 0;

      for(n of numbers){
        sum += n;
      }

      expect(sum).toBe(6);
    });
  });

From this I generated my test files (ES6 => ES5) with babel:

babel src --watch --out-dir tests

Then I run karma start I get error:

ReferenceError: regeneratorRuntime is not defined".

Relevant bits in karma.conf.js:

  // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      {pattern: 'tests/*.js', included: true}
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
            'src/*.js': ['babel']
    },
        'babelPreprocessor': {
      options: {
        sourceMap: 'inline'
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    },

// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],

Full project on github

I am able to use many ES6 features including arrows.  Just no go on Generators.

Body:
If you use React, adding polyfills from create-react-app worked for me.

yarn add --dev react-app-polyfill

Then add the following lines to webpack.config.js

entry: {
  app: [
    'react-app-polyfill/ie9', // Only if you want to support IE 9
    'react-app-polyfill/stable',
    './src/index.jsx',
  ],
},

See more examples on the react-app-polyfill GitHub page.


问:
allow space at the beginning + dont allow space between string using regex
need regex, to allow space at the beginning  but not allow in between of words.

For ex:
"abc abc" - invalid
"   abc" - valid

答:
```<code>^(([\s])(.[^ ])*)$
</code>```

Gropu 1 ([\s]) match spaces, tabs line brackes if you want only speces
just edit: ([ ])

Gropu 2 (.[^ ])* Mtach any chars without spaces and    line brackes.

Body:
^(([\s])(.[^ ])*)$

Gropu 1 ([\s]) match spaces, tabs line brackes if you want only speces
just edit: ([ ])

Gropu 2 (.[^ ])* Mtach any chars without spaces and    line brackes.


问:
Subquery must return a single row
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

```<code>SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur
</code>```

答:
You are probably trying to write this:

```<code>SELECT c2.compteur,
       ( SUM(c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT SUM(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015)
       )
FROM compteur2015 c1 JOIN
     compteur c2
     ON c1.compteur = c2.compteur
GROUP BY c2.compteur;
</code>```

However, this is more simply written as:

```<code>SELECT c2.compteur,
       ( SUM(c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         SUM(SUM(c1.feb15 + c1.nov15 + c1.dec15)) OVER ()
       )
FROM compteur2015 c1 JOIN
     compteur c2
     ON c1.compteur = c2.compteur
GROUP BY c2.compteur;
</code>```

Title: Subquery must return a single row

Body:
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur

Body:
You are probably trying to write this:

SELECT c2.compteur,
       ( SUM(c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT SUM(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015)
       )
FROM compteur2015 c1 JOIN
     compteur c2
     ON c1.compteur = c2.compteur
GROUP BY c2.compteur;

However, this is more simply written as:

SELECT c2.compteur,
       ( SUM(c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         SUM(SUM(c1.feb15 + c1.nov15 + c1.dec15)) OVER ()
       )
FROM compteur2015 c1 JOIN
     compteur c2
     ON c1.compteur = c2.compteur
GROUP BY c2.compteur;


问:
Current directory from a DLL invoked from Powershell wrong
I have a DLL with a static method which would like to know the current directory.  I load the library

```<code>c:\temp> add-type -path "..."
</code>```

...and call the method

```<code>c:\temp> [MyNamespace.MyClass]::MyMethod()
</code>```

but both Directory.GetCurrentDirectory() and .Environment.CurrentDirectory get the current directory wrong...

what is the correct way to do this?

答:
If the command in your DLL inherits from System.Management.Automation.PSCmdLet, the current PS location is available in SessionState.Path.

public class SomeCommand : PSCmdlet
{
    protected override void BeginProcessing()
    {
      string currentDir = this.SessionState.Path.CurrentLocation.Path;
    }
}

```

<p>To get to the path without a session reference, this code seems to work. This solution I found after going through code that makes GIT autocomplete in PS GIT Completions, specifically this function here.</p>

<pre class="lang-cs prettyprint-override"><code>public class Test
{
  public static IEnumerable<string> GetPath()
  {
    using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace))
    {
      ps.AddScript("pwd");
      var path = ps.Invoke<PathInfo>();
      return path.Select(p => p.Path);
    }
  }
}
</code>```

Output:

```<code>PS C:\some\folder> [Test]::GetPath()
C:\some\folder
</code>```

Body:
I have a DLL with a static method which would like to know the current directory.  I load the library

c:\temp> add-type -path "..."

...and call the method

c:\temp> [MyNamespace.MyClass]::MyMethod()

but both Directory.GetCurrentDirectory() and .Environment.CurrentDirectory get the current directory wrong...

what is the correct way to do this?

Body:
If the command in your DLL inherits from System.Management.Automation.PSCmdLet, the current PS location is available in SessionState.Path.

public class SomeCommand : PSCmdlet
{
    protected override void BeginProcessing()
    {
      string currentDir = this.SessionState.Path.CurrentLocation.Path;
    }
}

To get to the path without a session reference, this code seems to work. This solution I found after going through code that makes GIT autocomplete in PS GIT Completions, specifically this function here.

public class Test
{
  public static IEnumerable<string> GetPath()
  {
    using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace))
    {
      ps.AddScript("pwd");
      var path = ps.Invoke<PathInfo>();
      return path.Select(p => p.Path);
    }
  }
}

Output:

PS C:\some\folder> [Test]::GetPath()
C:\some\folder


问:
How to use CMake to find and link OpenGL(mesa) package in Ubuntu
I am totally new in CMake and OpenGL. I now need to use OpenGL as a library in my project on my Ubuntu 15.04 64bit PC, which is built by CMake 3.0.2.

I have been working on this several days, nearly frustrated. I get confused with a bunch of problems.

mesa and OpenGL

First of all, I installed the mesa package with command sudo apt-get install mesa-common-dev, which get me mesa 10.5.2.

Then I browse the package files with dpkg -L mesa-common-dev:

```<code>/.
/usr
/usr/share
/usr/share/bug
...
/usr/share/bug/mesa-common-dev/control

/usr/share/doc
...
/usr/share/doc/mesa-common-dev/faq.html

/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/pkgconfig
/usr/lib/x86_64-linux-gnu/pkgconfig/dri.pc

/usr/include
/usr/include/GL
/usr/include/GL/gl.h
...
/usr/include/GL/glx_mangle.h
</code>```

QUESTION 1: Where are the shared libraries (.so) and static libraries (.a)?

CMake

I now have a CMakeLists.txt, with the OpenGL module named OPENGL

```<code>...
find_package(OPENGL REQUIRED)  # here is CMakeLists.txt:45
...
include_directories(${OPENGL_INCLUDE_DIRS})
link_directories(${OPENGL_LIBRARY_DIRS})
target_link_libraries(MyProj ... ${OPENGL_LIBRARIES})
...
</code>```

So I definitely need to have a cmake file, say FindOPENGL.cmake, like this (took GLEW's cmake file as a template):

```<code># OPENGL_FOUND             If OPENGL is found
# OPENGL_LIBRARIES         OPENGL libraries
# OPENGL_INCLUDE_DIRS      OPENGL include directories
# OPENGL_LIBRARY_DIRS      OPENGL library directories

if(UNIX)
  set(OPENGL_INC_NAMES gl.h)
  set(OPENGL_LIB_NAMES libGL.so.1.2.0)
endif(UNIX)

# OPENGL static library     # line 17
find_library(OPENGL_LIBRARIES
    NAMES ${OPENGL_LIB_NAMES}
    PATHS /usr/x86_64-linux-gnu/mesa
    DOC "OPENGL library")

# OPENGL library dir        # line 23
find_path(OPENGL_LIBRARY_DIRS
    NAMES ${OPENGL_LIB_NAMES}
    PATHS /usr/x86_64-linux-gnu/mesa
    DOC "OPENGL include directories")

# OPENGL include dir        # line 29
find_path(OPENGL_INCLUDE_DIRS
    NAMES ${OPENGL_INC_NAMES}
    PATHS /usr/include/GL
    DOC "OPENGL include directories")

# Version
set(OPENGL_VERSION 1.13.0)

# Set package standard args
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OPENGL       # here is FindOPENGL.cmake:40
    REQUIRED_VARS OPENGL_LIBRARIES OPENGL_INCLUDE_DIRS OPENGL_LIBRARY_DIRS
    VERSION_VAR OPENGL_VERSION)
</code>```

QUESTION 2: How to link static libraries and shared libraries in cmake file, and what is the difference between line 17/23/29?

I then run cmake and get following errors:

```<code>CMake Error at /usr/share/cmake-3.0/Modules/FindPackageHandleStandardArgs.cmake:136 (message):
  Cound NOT find OPENGL (missing: OPENGL_LIBRARIES OPENGL_LIBRARY_DIRS)
  (found version "1.13.0")
Call Stack (most recent call first):
  /usr/share/cmake-3.0/Modules/FindPackageHandleStandardArgs.cmake:343 (_FPHSA_FAILURE_MESSAGE)
  cmake/modules/FindOPENGL.cmake:40 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:45 (find_package)
</code>```

QUESTION 3: How come I get this error and how can I fix it? Did I do something wrong through the whole procedure?

Update

Thanks for @usr1234567 's answer, I then delete my FindOPENGL.cmake and try to make use of /usr/share/cmake-3.0/Modules/FindOpenGL.cmake. I still get the error missing: OPENGL_gl_LIBRARY. I look into this cmake file for the definition of OPENGL_gl_LIBRARY, and manually check the lib paths in it, unfortunately none of the paths listed exists.

Did I install mesa properly?

答:
As stated, use the built-in FindOpenGL.cmake provided by cmake.

You're missing libgl1-mesa-dev. So try this instead:

```<code>sudo apt install mesa-common-dev libgl1-mesa-dev
</code>```

And optionally, if you want EGL to be found by FindOpenGL.cmake:

```<code>sudo apt install mesa-common-dev libgl1-mesa-dev libgles2-mesa-dev
</code>```

Body:
I am totally new in CMake and OpenGL. I now need to use OpenGL as a library in my project on my Ubuntu 15.04 64bit PC, which is built by CMake 3.0.2.

I have been working on this several days, nearly frustrated. I get confused with a bunch of problems.

mesa and OpenGL

First of all, I installed the mesa package with command sudo apt-get install mesa-common-dev, which get me mesa 10.5.2.

Then I browse the package files with dpkg -L mesa-common-dev:

/.
/usr
/usr/share
/usr/share/bug
...
/usr/share/bug/mesa-common-dev/control

/usr/share/doc
...
/usr/share/doc/mesa-common-dev/faq.html

/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/pkgconfig
/usr/lib/x86_64-linux-gnu/pkgconfig/dri.pc

/usr/include
/usr/include/GL
/usr/include/GL/gl.h
...
/usr/include/GL/glx_mangle.h

QUESTION 1: Where are the shared libraries (.so) and static libraries (.a)?

CMake

I now have a CMakeLists.txt, with the OpenGL module named OPENGL

...
find_package(OPENGL REQUIRED)  # here is CMakeLists.txt:45
...
include_directories(${OPENGL_INCLUDE_DIRS})
link_directories(${OPENGL_LIBRARY_DIRS})
target_link_libraries(MyProj ... ${OPENGL_LIBRARIES})
...

So I definitely need to have a cmake file, say FindOPENGL.cmake, like this (took GLEW's cmake file as a template):

# OPENGL_FOUND             If OPENGL is found
# OPENGL_LIBRARIES         OPENGL libraries
# OPENGL_INCLUDE_DIRS      OPENGL include directories
# OPENGL_LIBRARY_DIRS      OPENGL library directories

if(UNIX)
  set(OPENGL_INC_NAMES gl.h)
  set(OPENGL_LIB_NAMES libGL.so.1.2.0)
endif(UNIX)

# OPENGL static library     # line 17
find_library(OPENGL_LIBRARIES
    NAMES ${OPENGL_LIB_NAMES}
    PATHS /usr/x86_64-linux-gnu/mesa
    DOC "OPENGL library")

# OPENGL library dir        # line 23
find_path(OPENGL_LIBRARY_DIRS
    NAMES ${OPENGL_LIB_NAMES}
    PATHS /usr/x86_64-linux-gnu/mesa
    DOC "OPENGL include directories")

# OPENGL include dir        # line 29
find_path(OPENGL_INCLUDE_DIRS
    NAMES ${OPENGL_INC_NAMES}
    PATHS /usr/include/GL
    DOC "OPENGL include directories")

# Version
set(OPENGL_VERSION 1.13.0)

# Set package standard args
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OPENGL       # here is FindOPENGL.cmake:40
    REQUIRED_VARS OPENGL_LIBRARIES OPENGL_INCLUDE_DIRS OPENGL_LIBRARY_DIRS
    VERSION_VAR OPENGL_VERSION)

QUESTION 2: How to link static libraries and shared libraries in cmake file, and what is the difference between line 17/23/29?

I then run cmake and get following errors:

CMake Error at /usr/share/cmake-3.0/Modules/FindPackageHandleStandardArgs.cmake:136 (message):
  Cound NOT find OPENGL (missing: OPENGL_LIBRARIES OPENGL_LIBRARY_DIRS)
  (found version "1.13.0")
Call Stack (most recent call first):
  /usr/share/cmake-3.0/Modules/FindPackageHandleStandardArgs.cmake:343 (_FPHSA_FAILURE_MESSAGE)
  cmake/modules/FindOPENGL.cmake:40 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:45 (find_package)

QUESTION 3: How come I get this error and how can I fix it? Did I do something wrong through the whole procedure?

Update

Thanks for @usr1234567 's answer, I then delete my FindOPENGL.cmake and try to make use of /usr/share/cmake-3.0/Modules/FindOpenGL.cmake. I still get the error missing: OPENGL_gl_LIBRARY. I look into this cmake file for the definition of OPENGL_gl_LIBRARY, and manually check the lib paths in it, unfortunately none of the paths listed exists.

Did I install mesa properly?

Body:
As stated, use the built-in FindOpenGL.cmake provided by cmake.

You're missing libgl1-mesa-dev. So try this instead:

sudo apt install mesa-common-dev libgl1-mesa-dev

And optionally, if you want EGL to be found by FindOpenGL.cmake:

sudo apt install mesa-common-dev libgl1-mesa-dev libgles2-mesa-dev


问:
captcha does not load in spring
i don't know why my captcha is not loaded in this jsp page! in my other jsp page it works good. i made it through a servlet. like this:

```<code>public class CaptchaServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedImage buffer =new BufferedImage(140, 50, BufferedImage.TYPE_INT_RGB);
        Graphics g = buffer.createGraphics();
        g.fillRect(1,1,138,48);
        Random rr = new Random();
        int x,y,r;
        g.setColor(Color.black);
        for(int i=0;i<119;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            r = 1+rr.nextInt(3);
            g.fillOval(x,y,r,r);
        }
        String str = "";
        String s = "";
        int n = 4 + rr.nextInt(3);
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m;
        boolean found = false;
        for(int i=0;i<n;i++) {
            m = p.matcher(s);
            while (!m.find()) {
                r = 65 + rr.nextInt(63);
                s = s.format("%c", r);
                m = p.matcher(s);
            }
            str = str + s;
            s = "";
        }

        HttpSession session = request.getSession();
        session.setAttribute( "captcha", str );

        //TimesRoman Font.PLAIN SansSerif
        g.setFont(new Font("SansSerif", Font.BOLD, 22));
        for(int i=0;i<str.length();i++) {
            s = str.substring(i,i+1);
            x = 4+20*i+rr.nextInt(5);
            y = 20+rr.nextInt(20);
            g.drawString(s, x, y);
        }
        g.setXORMode(Color.white);
        for(int i=0;i<199;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            g.drawLine(x,y,x,y);
        }
        response.setHeader("Cache-Control", "no-store"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache");        //HTTP 1.0
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(buffer, "png", os);
        os.flush();
        os.close();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
</code>```

and this is my jsp where captcha is called:

```<code> <tr>
      <td><br/><img src="captcha-image.png"></td>
      <td style="margin-right: 5px;" valign="top"><br/>  Enter code
      <br><input type="text" name="captcha_text" value="" style="margin-left: 5px;"></td>
 </tr>
</code>```

when i press ctrl+b on it, it goes to the servlet mapping correctly. but why it is not loaded? in another jsp it is working!

答:
i found it! when i viewed page source, the image source was pointing to localhost:8080/votePoll/{id}/captcha-image.png and not localhost:8080/captcha-image.png which it should be. i don't know why this happened because in my other jsp it wasn't so.

anyway, by changing image source to localhost:8080/captcha-image.png it worked fine!

Title: captcha does not load in spring

Body:
i don't know why my captcha is not loaded in this jsp page! in my other jsp page it works good. i made it through a servlet. like this:

public class CaptchaServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedImage buffer =new BufferedImage(140, 50, BufferedImage.TYPE_INT_RGB);
        Graphics g = buffer.createGraphics();
        g.fillRect(1,1,138,48);
        Random rr = new Random();
        int x,y,r;
        g.setColor(Color.black);
        for(int i=0;i<119;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            r = 1+rr.nextInt(3);
            g.fillOval(x,y,r,r);
        }
        String str = "";
        String s = "";
        int n = 4 + rr.nextInt(3);
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m;
        boolean found = false;
        for(int i=0;i<n;i++) {
            m = p.matcher(s);
            while (!m.find()) {
                r = 65 + rr.nextInt(63);
                s = s.format("%c", r);
                m = p.matcher(s);
            }
            str = str + s;
            s = "";
        }

        HttpSession session = request.getSession();
        session.setAttribute( "captcha", str );

        //TimesRoman Font.PLAIN SansSerif
        g.setFont(new Font("SansSerif", Font.BOLD, 22));
        for(int i=0;i<str.length();i++) {
            s = str.substring(i,i+1);
            x = 4+20*i+rr.nextInt(5);
            y = 20+rr.nextInt(20);
            g.drawString(s, x, y);
        }
        g.setXORMode(Color.white);
        for(int i=0;i<199;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            g.drawLine(x,y,x,y);
        }
        response.setHeader("Cache-Control", "no-store"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache");        //HTTP 1.0
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(buffer, "png", os);
        os.flush();
        os.close();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

and this is my jsp where captcha is called:

  Enter code

<input type="text" name="captcha_text" value="" style="margin-left: 5px;">

when i press ctrl+b on it, it goes to the servlet mapping correctly. but why it is not loaded? in another jsp it is working!


问:
Redirect "ugly" URL to new URL using htaccess
I have already rewritten my old "ugly" URL:

```<code>http://example.com/ppd-brands/generic/?gen_id=Mjky
</code>```

to

```<code>http://example.com/ppd-brands/generic/gen_id/Mjky
</code>```

using the code below

```<code>RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]
</code>```

and it's working.

Now my problem is how can I redirect the old "ugly" URL to the new URL when the user visits the old "ugly" URL?

答:
```<code>RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]
</code>```

Just a precursor... whilst your old "ugly" URL was of the form /ppd-brands/generic/?gen_id=Mjky, you should ideally be rewriting to the actual file that handles the request, eg. index.php, instead of allowing mod_dir to issue an additional internal subrequest to the directory index - which is what I assume is happening here.

For example:

```<code>RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/index.php?gen_id=$1 [L]
</code>```

Now, your main question... to externally redirect from the old "ugly" URL to the new URL. In this case, you need to be careful of a redirect loop, since if we simply redirect then the above rewrite will rewrite it back again in an endless loop. You can't use a mod_alias Redirect (as the other answer suggests) for this reason. (And a mod_alias Redirect can't match the query string either - another reason.)

Aside: Since we changed the above rewrite to include index.php in the rewritten URL, which would appear to differ from the old "ugly" URL, we could perhaps get away with a simple redirect if you are on Apache 2.4 (but Apache 2.2 would result in a conflict because mod_dir would issue an internal subrequest for index.php before we can process the URL with mod_rewrite).

We need to only redirect initial requests, not requests that we have already rewritten. We can do this by checking against the REDIRECT_STATUS environment variable, which is empty on the initial request and set to "200" (as in 200 OK HTTP status) after the first successful rewrite. (Another way is to check against THE_REQUEST, instead of the dynamic/rewritable URL-path.)

For example, try the following before your existing rewrite:

```<code># Redirect "old" to "new"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^gen_id=([^/&]*)
RewriteRule ^(ppd-brands/generic)/(?:index\.php)?$ /$1/gen_id/%1 [QSD,R=302,L]
</code>```

Note that in order to match the query string we need a condition (RewriteCond directive) that checks against the QUERY_STRING server variable. The URL-path matched by the RewriteRule pattern notably excludes the query string.

The index.php in the request URL is optional, so it matches /ppd-brands/generic/?gen_id=Mjky or /ppd-brands/generic/index.php?gen_id=Mjky (if that is the actual URL).

The $1 backreference is simply to save typing/duplication. This will always contain ppd-brands/generic when the directive matches. We could have done the same with "gen_id", but that could make the susbstitution string look a bit too cryptic.

The %1 backreference (note the % prefix) is a backreference to the captured group in the last matched CondPattern (as opposed to $1 which refers to the RewriteRule pattern), ie. the value of the gen_id URL parameter.

The QSD flag (Apache 2.4+) strips the query string from the redirected URL. Otherwise gen_id=XYZ would be passed through to the target URL. If you are still on Apache 2.2 then you would need to append a ? to the end of the substitution string instead (essentially an empty query string). eg. /$1/gen_id/%1?

The "magic" is really the first condition that checks the REDIRECT_STATUS env var. As mentioned above, this ensures that we only process initial requests and not the rewritten request, thus avoiding redirect loop.

Note that this is currently a 302 (temporary) redirect. Only change to a 301 (permanent) once you have tested this works OK. 301s are cached persistently by the browser so can make testing problematic.

And just to clarify... a redirect like this should only be implemented once you have already changed all the URLs in your application. This redirect is to simply redirect search engines, backlinks and anyone who should manually type the URL (unlikely).

Body:
I have already rewritten my old "ugly" URL:

http://example.com/ppd-brands/generic/?gen_id=Mjky

to

http://example.com/ppd-brands/generic/gen_id/Mjky

using the code below

RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]

and it's working.

Now my problem is how can I redirect the old "ugly" URL to the new URL when the user visits the old "ugly" URL?

Body:
RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]

Just a precursor... whilst your old "ugly" URL was of the form /ppd-brands/generic/?gen_id=Mjky, you should ideally be rewriting to the actual file that handles the request, eg. index.php, instead of allowing mod_dir to issue an additional internal subrequest to the directory index - which is what I assume is happening here.

For example:

RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/index.php?gen_id=$1 [L]

Now, your main question... to externally redirect from the old "ugly" URL to the new URL. In this case, you need to be careful of a redirect loop, since if we simply redirect then the above rewrite will rewrite it back again in an endless loop. You can't use a mod_alias Redirect (as the other answer suggests) for this reason. (And a mod_alias Redirect can't match the query string either - another reason.)

Aside: Since we changed the above rewrite to include index.php in the rewritten URL, which would appear to differ from the old "ugly" URL, we could perhaps get away with a simple redirect if you are on Apache 2.4 (but Apache 2.2 would result in a conflict because mod_dir would issue an internal subrequest for index.php before we can process the URL with mod_rewrite).

We need to only redirect initial requests, not requests that we have already rewritten. We can do this by checking against the REDIRECT_STATUS environment variable, which is empty on the initial request and set to "200" (as in 200 OK HTTP status) after the first successful rewrite. (Another way is to check against THE_REQUEST, instead of the dynamic/rewritable URL-path.)

For example, try the following before your existing rewrite:

# Redirect "old" to "new"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^gen_id=([^/&]*)
RewriteRule ^(ppd-brands/generic)/(?:index\.php)?$ /$1/gen_id/%1 [QSD,R=302,L]

Note that in order to match the query string we need a condition (RewriteCond directive) that checks against the QUERY_STRING server variable. The URL-path matched by the RewriteRule pattern notably excludes the query string.

The index.php in the request URL is optional, so it matches /ppd-brands/generic/?gen_id=Mjky or /ppd-brands/generic/index.php?gen_id=Mjky (if that is the actual URL).

The $1 backreference is simply to save typing/duplication. This will always contain ppd-brands/generic when the directive matches. We could have done the same with "gen_id", but that could make the susbstitution string look a bit too cryptic.

The %1 backreference (note the % prefix) is a backreference to the captured group in the last matched CondPattern (as opposed to $1 which refers to the RewriteRule pattern), ie. the value of the gen_id URL parameter.

The QSD flag (Apache 2.4+) strips the query string from the redirected URL. Otherwise gen_id=XYZ would be passed through to the target URL. If you are still on Apache 2.2 then you would need to append a ? to the end of the substitution string instead (essentially an empty query string). eg. /$1/gen_id/%1?

The "magic" is really the first condition that checks the REDIRECT_STATUS env var. As mentioned above, this ensures that we only process initial requests and not the rewritten request, thus avoiding redirect loop.

Note that this is currently a 302 (temporary) redirect. Only change to a 301 (permanent) once you have tested this works OK. 301s are cached persistently by the browser so can make testing problematic.

And just to clarify... a redirect like this should only be implemented once you have already changed all the URLs in your application. This redirect is to simply redirect search engines, backlinks and anyone who should manually type the URL (unlikely).


问:
setSmallIcon() and setLargeIcon() not working in Android Notification
I am pushing the notification from the Firebase Console. I am able to easily receive the notification data and notification also appears but what i am trying to do is change the small icon and the large icon of the notification.

I am using both the methods but none of them seem to work. I have also tried making the small icon using the Vector option via res>New>Vector>Clip Art.
Neither small icon appears nor does the large icon and the notification is also not expandable.

MessagingService.kt

class MessagingService(): FirebaseMessagingService() {

  override fun onMessageReceived(p0: RemoteMessage ? ) {
    super.onMessageReceived(p0)
    showNotification(p0!!.notification!!.title!!, p0!!.notification!!.body!!)
  }

  fun showNotification(title: String, body: String) {
    val icon = BitmapFactory.decodeResource(resources,
      R.drawable.iphn)
    NotificationCompat.Builder(this, "MyNotifications")
      .setLargeIcon(icon)
      .setSmallIcon(R.drawable.ic_notif)
      .setContentTitle(title)
      .setContentText(body)
      .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(icon)
        .bigLargeIcon(null))
      .build()

  }
}
```

ic_notif is the drawable i created using Vector

答:
You can try using ic_notif.png instead of a vector.

Other than that, In the latest Android version, It is recommended to use channelId. you can add this block to add channelId

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "yourChannelId"
        val channel = NotificationChannel(channelId, "your channel Name" ,
                NotificationManager.IMPORTANCE_DEFAULT)
        mNotificationManager.createNotificationChannel(channel)
        mBuilder.setChannelId(channelId)
    }
</code>```

Body:
I am pushing the notification from the Firebase Console. I am able to easily receive the notification data and notification also appears but what i am trying to do is change the small icon and the large icon of the notification.

I am using both the methods but none of them seem to work. I have also tried making the small icon using the Vector option via res>New>Vector>Clip Art.
Neither small icon appears nor does the large icon and the notification is also not expandable.

MessagingService.kt

class MessagingService(): FirebaseMessagingService() {

  override fun onMessageReceived(p0: RemoteMessage ? ) {
    super.onMessageReceived(p0)
    showNotification(p0!!.notification!!.title!!, p0!!.notification!!.body!!)
  }

  fun showNotification(title: String, body: String) {
    val icon = BitmapFactory.decodeResource(resources,
      R.drawable.iphn)
    NotificationCompat.Builder(this, "MyNotifications")
      .setLargeIcon(icon)
      .setSmallIcon(R.drawable.ic_notif)
      .setContentTitle(title)
      .setContentText(body)
      .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(icon)
        .bigLargeIcon(null))
      .build()

  }
}

ic_notif is the drawable i created using Vector

Body:
You can try using ic_notif.png instead of a vector.

Other than that, In the latest Android version, It is recommended to use channelId. you can add this block to add channelId

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "yourChannelId"
        val channel = NotificationChannel(channelId, "your channel Name" ,
                NotificationManager.IMPORTANCE_DEFAULT)
        mNotificationManager.createNotificationChannel(channel)
        mBuilder.setChannelId(channelId)
    }