问:
RecyclerView: Inconsistency detected. Invalid item position
Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened:

java.lang.IndexOutOfBoundsException:
      Inconsistency detected. Invalid item position 2(offset:2).state:3

To me, it looks like an internal error inside RecyclerView, as I can't think of any way of this being caused directly by our code...

Has anyone encountered this problem?

What would be the solution?

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is not easy to reproduce, but it is fatal when it happens.

The full stack-trace:

```<code>W/dalvikvm( 7546): threadid=1: thread exiting with uncaught exception (group=0x41987d40)
    E/AndroidRuntime( 7546): FATAL EXCEPTION: main
    E/AndroidRuntime( 7546): Process: com.oblong.mezzedroid, PID: 7546
    E/AndroidRuntime( 7546): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3382)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.RecyclerViewContainer$LiLinearLayoutManager.onLayoutChildren(RecyclerViewContainer.java:179)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.LiRecyclerView.onLayout(LiRecyclerView.java:30)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at com.oblong.mezzedroid.workspace.content.bins.BinsContainerLayout.onLayout(BinsContainerLayout.java:22)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2132)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
    E/AndroidRuntime( 7546):    at andro
</code>```

答:
You only need to clear your list on OnPostExecute() and not while doing Pull to Refresh

```<code>// Setup refresh listener which triggers new data loading
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                AsyncTask<String,Void,String> task = new get_listings();
                task.execute(); // clear listing inside onPostExecute

            }
        });
</code>```

I discovered that this happens when you scroll during a pull to refresh, since I was clearing the list before the async task , resulting to  java.lang.IndexOutOfBoundsException: Inconsistency detected.

```<code>        swipeContainer.setRefreshing(false);
        //TODO : This is very crucial , You need to clear before populating new items
        listings.clear();
</code>```

That way you won't end with an inconsistency

Body:
Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened:

java.lang.IndexOutOfBoundsException:
      Inconsistency detected. Invalid item position 2(offset:2).state:3

To me, it looks like an internal error inside RecyclerView, as I can't think of any way of this being caused directly by our code...

Has anyone encountered this problem?

What would be the solution?

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is not easy to reproduce, but it is fatal when it happens.

The full stack-trace:

W/dalvikvm( 7546): threadid=1: thread exiting with uncaught exception (group=0x41987d40)
    E/AndroidRuntime( 7546): FATAL EXCEPTION: main
    E/AndroidRuntime( 7546): Process: com.oblong.mezzedroid, PID: 7546
    E/AndroidRuntime( 7546): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3382)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.RecyclerViewContainer$LiLinearLayoutManager.onLayoutChildren(RecyclerViewContainer.java:179)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.LiRecyclerView.onLayout(LiRecyclerView.java:30)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at com.oblong.mezzedroid.workspace.content.bins.BinsContainerLayout.onLayout(BinsContainerLayout.java:22)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2132)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
    E/AndroidRuntime( 7546):    at andro

Body:
You only need to clear your list on OnPostExecute() and not while doing Pull to Refresh

// Setup refresh listener which triggers new data loading
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                AsyncTask<String,Void,String> task = new get_listings();
                task.execute(); // clear listing inside onPostExecute

            }
        });

I discovered that this happens when you scroll during a pull to refresh, since I was clearing the list before the async task , resulting to  java.lang.IndexOutOfBoundsException: Inconsistency detected.

        swipeContainer.setRefreshing(false);
        //TODO : This is very crucial , You need to clear before populating new items
        listings.clear();

That way you won't end with an inconsistency


来源: stackexchange

问:
Groupby on one column of pandas dataframe, and train feature and target (X, y) of each group with a common sklearn pipeline using GridsearchCv
I have a pandas dataframe with the following structure:

```<code>    pd.DataFrame({"user_id": ['user_id1', 'user_id1', 'user_id1', 'user_id2', 'user_id2'],
      'meeting': ['text1', 'text2', 'text3', 'text4', 'text5'], 'label': ['a,b', 'a', 'a,c', 'x', 'x,y' ]})
</code>```

There a total of 12 user_id's. I have a pipeline as follows:

```<code>    knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                 ('model', OneVsRestClassifier(KNeighborsClassifier())])
</code>```

a parameter grid as follows:

```<code>    param_grid_1 = {'tf_idf__max_df': (0.25, 0.5, 0.75),
             'tf_idf__ngram_range': [(1, 1), (1, 2), (2,2) (1, 3)],
              'model__estimator_n_neighbors' : [np.range(1,30)]
             }
</code>```

And finally GridSearchCV:

```<code>    Grid_Search_tune = GridSearchCV(knn_tfidf, param_grid_1, cv=2)
</code>```

I need to create a model for each user with the corresponding X and y values. For one user, I can do the following:

```<code>    t = df[df.user_id == 'user_id1']
</code>```

Extract X and y from t. Pass y to a Multi labelBinarizer(), then after instantiating the pipeline, param_grid and GridsearchCV, I can do:

```<code>    Grid_Search_tune.fit(X, y)
</code>```

Doing this 12 times for each user is repetitive. So I looped through the grouped pandas Dataframe. Here is what I have done:

```<code>    g = df.groupby('user_id')

    for names, groups in g:

X = groups.meeting_subject.as_matrix()
labels = [x.split(', ') for x in groups.priority_label.tolist()]
mlb = MultiLabelBinarizer()
y = mlb.fit_transform(labels)

knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                     ('model', OneVsRestClassifier(KNeighborsClassifier()))])

param_grid_1 = {'tf_idf__max_df': (0.25, 0.5, 0.75),
                 'tf_idf__ngram_range': [(1, 2), (2,2), (1, 3)], 'model__estimator__n_neighbors': np.arange(1,4)}

Grid_Search_tune = GridSearchCV(knn_tfidf, param_grid_1, cv=2)

all_estimators = Grid_Search_tune.fit(X, y)

best_of_all_estimators = Grid_Search_tune.best_estimator_

print(best_of_all_estimators)
</code>```

This gives me an output like:

```<code>    user_id1
    Pipeline(memory=None,
 steps=[('tf_idf', TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
    dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
    lowercase=True, max_df=0.25, max_features=None, min_df=1,
    ngram_range=(2, 2), norm=u'l2', preprocessor=None, smooth_idf=T...tric_params=None, n_jobs=1, n_neighbors=1, p=2,
       weights='uniform'),
      n_jobs=1))])
</code>```

user_id2

```<code>    Pipeline(memory=None,
 steps=[('tf_idf', TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
    dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
    lowercase=True, max_df=0.25, max_features=None, min_df=1,
    ngram_range=(1, 2), norm=u'l2', preprocessor=None, smooth_idf=T...tric_params=None, n_jobs=1, n_neighbors=1, p=2,
       weights='uniform'),
      n_jobs=1))])
</code>```

And so on till user_id12 and the corresponding pipeline. I don't know if this is the correct way of doing it, and from here on I am lost. If I do:

```<code>    best_of_all_estimators.predict(['some_text_string'])
</code>```

I get a prediction for all the 12 models. How do I key or index my models with the for loop variable 'names' so that when I do:

```<code>    knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                 ('model', OneVsRestClassifier(KNeighborsClassifier())])
</code>```0

Say I choose user_id3 , and then

```<code>    knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                 ('model', OneVsRestClassifier(KNeighborsClassifier())])
</code>```1

I enter 'some random string'. The model trained for the X and y belonging to user_id3 is pulled up and a prediction is done on that model, and not for all the models. A very similar question is linked here. training an ML model on selected parts of a data frame. I am beginner and I'm really struggling! Please, please help! Thanks a ton in advance.

答:
Apparently Pipeline doesn't support changing the number of samples, such as in groupby or other aggregation.

Here is a similar question and possible workaround.

sklearn: Have an estimator that filters samples

ContentLicense: CC BY-SA 3.0

Body:
I have a pandas dataframe with the following structure:

    pd.DataFrame({"user_id": ['user_id1', 'user_id1', 'user_id1', 'user_id2', 'user_id2'],
      'meeting': ['text1', 'text2', 'text3', 'text4', 'text5'], 'label': ['a,b', 'a', 'a,c', 'x', 'x,y' ]})

There a total of 12 user_id's. I have a pipeline as follows:

    knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                 ('model', OneVsRestClassifier(KNeighborsClassifier())])

a parameter grid as follows:

    param_grid_1 = {'tf_idf__max_df': (0.25, 0.5, 0.75),
             'tf_idf__ngram_range': [(1, 1), (1, 2), (2,2) (1, 3)],
              'model__estimator_n_neighbors' : [np.range(1,30)]
             }

And finally GridSearchCV:

    Grid_Search_tune = GridSearchCV(knn_tfidf, param_grid_1, cv=2)

I need to create a model for each user with the corresponding X and y values. For one user, I can do the following:

    t = df[df.user_id == 'user_id1']

Extract X and y from t. Pass y to a Multi labelBinarizer(), then after instantiating the pipeline, param_grid and GridsearchCV, I can do:

    Grid_Search_tune.fit(X, y)

Doing this 12 times for each user is repetitive. So I looped through the grouped pandas Dataframe. Here is what I have done:

    g = df.groupby('user_id')

    for names, groups in g:

X = groups.meeting_subject.as_matrix()
labels = [x.split(', ') for x in groups.priority_label.tolist()]
mlb = MultiLabelBinarizer()
y = mlb.fit_transform(labels)

knn_tfidf = Pipeline([('tf_idf', TfidfVectorizer(stop_words='english')),
                     ('model', OneVsRestClassifier(KNeighborsClassifier()))])

param_grid_1 = {'tf_idf__max_df': (0.25, 0.5, 0.75),
                 'tf_idf__ngram_range': [(1, 2), (2,2), (1, 3)], 'model__estimator__n_neighbors': np.arange(1,4)}

Grid_Search_tune = GridSearchCV(knn_tfidf, param_grid_1, cv=2)

all_estimators = Grid_Search_tune.fit(X, y)

best_of_all_estimators = Grid_Search_tune.best_estimator_

print(best_of_all_estimators)

This gives me an output like:

    user_id1
    Pipeline(memory=None,
 steps=[('tf_idf', TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
    dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
    lowercase=True, max_df=0.25, max_features=None, min_df=1,
    ngram_range=(2, 2), norm=u'l2', preprocessor=None, smooth_idf=T...tric_params=None, n_jobs=1, n_neighbors=1, p=2,
       weights='uniform'),
      n_jobs=1))])

user_id2

    Pipeline(memory=None,
 steps=[('tf_idf', TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
    dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
    lowercase=True, max_df=0.25, max_features=None, min_df=1,
    ngram_range=(1, 2), norm=u'l2', preprocessor=None, smooth_idf=T...tric_params=None, n_jobs=1, n_neighbors=1, p=2,
       weights='uniform'),
      n_jobs=1))])

And so on till user_id12 and the corresponding pipeline. I don't know if this is the correct way of doing it, and from here on I am lost. If I do:

    best_of_all_estimators.predict(['some_text_string'])

I get a prediction for all the 12 models. How do I key or index my models with the for loop variable 'names' so that when I do:

    str(raw_input('Choose user_id from above list:'))

Say I choose user_id3 , and then

    str(raw_input('Enter text string:'))

I enter 'some random string'. The model trained for the X and y belonging to user_id3 is pulled up and a prediction is done on that model, and not for all the models. A very similar question is linked here. training an ML model on selected parts of a data frame. I am beginner and I'm really struggling! Please, please help! Thanks a ton in advance.


问:
Rails and Paperclip... don't save the original image, just the styles?
In paperclip when you save an image with lots of style and sizes it also saves the original.

But in my app it's not necessary to save the original, just the style will do, what I was wondering was how do you not save the original. Just store it in memory or in a temporary area and then not save it once the style have been generated.

Ideally it would not save original at all. I guess one solution would be to save the original, process the style and delete afterwards, however I'm trying to save on bandwidth and deleting the original after it has been saved kindof defeats the point.

Cheers!

答: check this: How do I tell paperclip to not save the original file?</p>

ContentLicense: CC BY-SA 2.5


问:
Material Icons in framework7 load on pc browser but not in Android app
I'm writing an app using Framework7 and I need some material icons. I added in the html file the path for the material icons provided by them:

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

Then i called icons using the tag:

```<code><i class="material-icons">icon_name_here</i>
</code>```

Well, when I load the app in the pc browser icons are correctly rendered, but when I upload the code to Adobe PhoneGap that builds the .apk, when I install it on a device and run it the app loads but the icons are not rendered, instead I read their names.

What do I can do to solve the prob?
Thank guys!

答:
It might be a Content Security Policy issue. I build from my PC using Cordova and have never uploaded to Adobe Phonegap, but I imagine Phonegap does enforce some security by limiting the sources of data to your app. If indeed it is Content Security Policy issue, you will have to explicitly declare googleapis.com as a possible source of content for your app.

You can find details of implementing Content Security Policy in this answer

Body:
I'm writing an app using Framework7 and I need some material icons. I added in the html file the path for the material icons provided by them:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Then i called icons using the tag:

icon_name_here

Well, when I load the app in the pc browser icons are correctly rendered, but when I upload the code to Adobe PhoneGap that builds the .apk, when I install it on a device and run it the app loads but the icons are not rendered, instead I read their names.

What do I can do to solve the prob?
Thank guys!


答:
The way I would tackle a job like this, is with the wonderful Find/Replace feature in any run-of-the-mill text editor. (Ctrl+H is usually the hotkey/shortcut)

Start by trimming the fat,

replace all " with nothing.

replace all .0000 with nothing.

The challenging bit is to get the first column inserted before every 2nd/3rd column value.
The quickest way would be to replace all , with ,1.1.1.1.0,. But this would be putting the first column as the third. Simply cut the last one and put it to the beginning to correct that.

The issue with this approach is that you have more than just 1.1.1.1.0 as a first column value. If there aren't too many different values, I would tackle each "block" separately. Just cut the block out and do the previous find/replace in a blank document, repeat for each block.

Yes there is a little bit of manual work here with chopping and changing, but that's usually how it goes with data cleanup!

Finally, replace all : with , (for the 2nd/3rd column separation)

Title: Data cleaning of csv file with many separated criteria

Body:
I am struggling in cleaning up and organize the file I attached.
I would need to "clean" the csv file organized in lists and sublists separated by different criteria such as : , comma and {.
I need three columns that show:
-in the first column the number that identify the profession such as "1.1.1.1.0";
-the second column I need the number that identify the characteristic of the profession: there are "attitudini", that has characteristics from "D10a" to "D9b" ; after that there are "competenze" from "C10a" to "C9b"
-the last column should report the value of each characteristic defined in the previous column, for example for the occupation 1.1.1.1.0, attitude D10a is equal to 60.

I give you a subsample example here with just two occupation but I would clean the whole sample with 786 occupations. If necessary I can send you the whole one.
many thanks to whoever can give me some hints.

Best

Roberta

{ "1.1.1.1.0":{ "attitudini":{ "D10a":"60.00000", "D10b":"51.00000", "D11a":"50.00000", "D11b":"39.00000", "D12a":"25.00000", "D12b":"28.00000", "D13a":"45.00000", "D13b":"48.00000", "D14a":"70.00000", "D14b":"71.00000", "D15a":"85.00000", "D15b":"74.00000", "D16a":"50.00000", "D16b":"48.00000", "D17a":"40.00000", "D17b":"40.00000", "D18a":"35.00000", "D18b":"31.00000", "D19a":"40.00000", "D19b":"48.00000", "D1a":"80.00000", "D1b":"82.00000", "D20a":"50.00000", "D20b":"57.00000", "D21a":"90.00000", "D21b":"68.00000", "D22a":"0.00000", "D22b":"0.00000", "D23a":"0.00000", "D23b":"0.00000", "D24a":"0.00000", "D24b":"0.00000", "D25a":"0.00000", "D25b":"0.00000", "D26a":"0.00000", "D26b":"0.00000", "D27a":"0.00000", "D27b":"0.00000", "D28a":"0.00000", "D28b":"0.00000", "D29a":"0.00000", "D29b":"0.00000", "D2a":"75.00000", "D2b":"71.00000", "D30a":"0.00000", "D30b":"0.00000", "D31a":"0.00000", "D31b":"0.00000", "D32a":"0.00000", "D32b":"0.00000", "D33a":"0.00000", "D33b":"0.00000", "D34a":"0.00000", "D34b":"0.00000", "D35a":"0.00000", "D35b":"0.00000", "D36a":"10.00000", "D36b":"8.00000", "D37a":"0.00000", "D37b":"0.00000", "D38a":"0.00000", "D38b":"0.00000", "D39a":"0.00000", "D39b":"0.00000", "D3a":"85.00000", "D3b":"83.00000", "D40a":"0.00000", "D40b":"0.00000", "D41a":"15.00000", "D41b":"14.00000", "D42a":"0.00000", "D42b":"0.00000", "D43a":"0.00000", "D43b":"0.00000", "D44a":"0.00000", "D44b":"0.00000", "D45a":"0.00000", "D45b":"0.00000", "D46a":"0.00000", "D46b":"0.00000", "D47a":"0.00000", "D47b":"0.00000", "D48a":"15.00000", "D48b":"17.00000", "D49a":"10.00000", "D49b":"8.00000", "D4a":"75.00000", "D4b":"77.00000", "D50a":"5.00000", "D50b":"6.00000", "D51a":"45.00000", "D51b":"54.00000", "D52a":"85.00000", "D52b":"94.00000", "D5a":"55.00000", "D5b":"51.00000", "D6a":"70.00000", "D6b":"65.00000", "D7a":"80.00000", "D7b":"85.00000", "D8a":"70.00000", "D8b":"65.00000", "D9a":"60.00000", "D9b":"54.00000", "fk_livello5":"1.1.1.1.0" }, "competenze":{ "C10a":"70.00000", "C10b":"74.00000", "C11a":"90.00000", "C11b":"77.00000", "C12a":"70.00000", "C12b":"74.00000", "C13a":"70.00000", "C13b":"80.00000", "C14a":"75.00000", "C14b":"77.00000", "C15a":"50.00000", "C15b":"45.00000", "C16a":"60.00000", "C16b":"54.00000", "C17a":"80.00000", "C17b":"80.00000", "C18a":"35.00000", "C18b":"37.00000", "C19a":"10.00000", "C19b":"8.00000", "C1a":"90.00000", "C1b":"82.00000", "C20a":"55.00000", "C20b":"54.00000", "C21a":"5.00000", "C21b":"6.00000", "C22a":"0.00000", "C22b":"0.00000", "C23a":"20.00000", "C23b":"20.00000", "C24a":"0.00000", "C24b":"0.00000", "C25a":"0.00000", "C25b":"0.00000", "C26a":"0.00000", "C26b":"0.00000", "C27a":"45.00000", "C27b":"40.00000", "C28a":"0.00000", "C28b":"0.00000", "C29a":"50.00000", "C29b":"68.00000", "C2a":"75.00000", "C2b":"83.00000", "C30a":"35.00000", "C30b":"43.00000", "C31a":"85.00000", "C31b":"83.00000", "C32a":"70.00000", "C32b":"57.00000", "C33a":"45.00000", "C33b":"48.00000", "C34a":"25.00000", "C34b":"28.00000", "C35a":"75.00000", "C35b":"63.00000", "C3a":"80.00000", "C3b":"77.00000", "C4a":"75.00000", "C4b":"85.00000", "C5a":"25.00000", "C5b":"25.00000", "C6a":"35.00000", "C6b":"31.00000", "C7a":"85.00000", "C7b":"85.00000", "C8a":"75.00000", "C8b":"74.00000", "C9a":"45.00000", "C9b":"37.00000", "fk_livello5":"1.1.1.1.0" }, "compiti":{ "p1":"votare normative o trasformare in leggi le proposte di legge", "p10":"leggere i giornali e tenersi aggiornati", "p11":"nominare gli amministratori di aziende partecipate dello stato italiano", "p12":"partecipare a commissioni parlamentari", "p13":"partecipare a convegni, conferenze o congressi", "p14":"trasformare in leggi gli atti del governo", "p2":"svolgere attività istruttoria (interrogazioni, interpellanze, ecc.)", "p3":"tenere i rapporti con il partito di appartenenza", "p4":"partecipare a dibattiti e a trasmissioni radiotelevisive", "p5":"recepire istanze provenienti dal sociale", "p6":"tenere i rapporti con l'elettorato (favorire la partecipazione dei cittadini, divulgare i risultati ottenuti, ecc.)", "p7":"discutere o emendare provvedimenti", "p8":"progettare e avanzare proposte di legge", "p9":"condurre indagini conoscitive su alcuni settori particolari del paese" }, "condizioni_lavoro":{ "H1":"95.00000", "H10":"20.00000", "H11":"55.00000", "H12":"85.00000", "H13":"75.00000", "H14":"25.00000", "H15":"95.00000", "H16":"25.00000", "H17":"50.00000", "H18":"10.00000", "H19":"0.00000", "H2":"80.00000", "H20":"20.00000", "H21":"55.00000", "H22":"20.00000", "H23":"0.00000", "H24":"0.00000", "H25":"0.00000", "H26":"0.00000", "H27":"0.00000", "H28":"0.00000", "H29":"0.00000", "H3":"100.00000", "H30":"0.00000", "H31":"0.00000", "H32":"0.00000", "H33":"0.00000", "H34":"80.00000", "H35":"0.00000", "H36":"25.00000", "H37":"0.00000", "H38":"5.00000", "H39":"35.00000", "H4":"100.00000", "H40":"15.00000", "H41":"5.00000", "H42":"20.00000", "H43":"0.00000", "H44":"0.00000", "H45":"70.00000", "H46":"70.00000", "H47":"90.00000", "H48":"80.00000", "H49":"20.00000", "H5":"95.00000", "H50":"75.00000", "H51":"60.00000", "H52":"70.00000", "H53":"90.00000", "H54":"85.00000", "H55":"0.00000", "H56":"10.00000", "H57":"64.00000", "H6":"90.00000", "H7":"85.00000", "H8":"80.00000", "H9":"75.00000", "fk_livello5":"1.1.1.1.0" }, "conoscenze":{ "B10a":"15.00000", "B10b":"11.00000", "B11a":"0.00000", "B11b":"0.00000", "B12a":"15.00000", "B12b":"11.00000", "B13a":"15.00000", "B13b":"17.00000", "B14a":"30.00000", "B14b":"25.00000", "B15a":"5.00000", "B15b":"3.00000", "B16a":"20.00000", "B16b":"20.00000", "B17a":"20.00000", "B17b":"20.00000", "B18a":"50.00000", "B18b":"48.00000", "B19a":"55.00000", "B19b":"57.00000", "B1a":"45.00000", "B1b":"43.00000", "B20a":"45.00000", "B20b":"54.00000", "B21a":"15.00000", "B21b":"11.00000", "B22a":"0.00000", "B22b":"0.00000", "B23a":"40.00000", "B23b":"45.00000", "B24a":"75.00000", "B24b":"74.00000", "B25a":"55.00000", "B25b":"60.00000", "B26a":"10.00000", "B26b":"11.00000", "B27a":"70.00000", "B27b":"62.00000", "B28a":"60.00000", "B28b":"65.00000", "B29a":"65.00000", "B29b":"57.00000", "B2a":"50.00000", "B2b":"57.00000", "B30a":"95.00000", "B30b":"86.00000", "B31a":"30.00000", "B31b":"28.00000", "B32a":"80.00000", "B32b":"74.00000", "B33a":"40.00000", "B33b":"34.00000", "B3a":"70.00000", "B3b":"62.00000", "B4a":"10.00000", "B4b":"11.00000", "B5a":"85.00000", "B5b":"77.00000", "B6a":"55.00000", "B6b":"48.00000", "B7a":"30.00000", "B7b":"34.00000", "B8a":"10.00000", "B8b":"11.00000", "B9a":"25.00000", "B9b":"25.00000", "fk_livello5":"1.1.1.1.0" }, "gwa":{ "G10a":"90.00000", "G10b":"91.00000", "G11a":"65.00000", "G11b":"68.00000", "G12a":"90.00000", "G12b":"88.00000", "G13a":"70.00000", "G13b":"71.00000", "G14a":"80.00000", "G14b":"71.00000", "G15a":"95.00000", "G15b":"82.00000", "G16a":"5.00000", "G16b":"3.00000", "G17a":"0.00000", "G17b":"0.00000", "G18a":"0.00000", "G18b":"0.00000", "G19a":"55.00000", "G19b":"42.00000", "G1a":"85.00000", "G1b":"88.00000", "G20a":"0.00000", "G20b":"0.00000", "G21a":"0.00000", "G21b":"0.00000", "G22a":"0.00000", "G22b":"0.00000", "G23a":"0.00000", "G23b":"0.00000", "G24a":"60.00000", "G24b":"57.00000", "G25a":"50.00000", "G25b":"51.00000", "G26a":"85.00000", "G26b":"82.00000", "G27a":"75.00000", "G27b":"79.00000", "G28a":"85.00000", "G28b":"85.00000", "G29a":"45.00000", "G29b":"37.00000", "G2a":"60.00000", "G2b":"51.00000", "G30a":"50.00000", "G30b":"45.00000", "G31a":"60.00000", "G31b":"71.00000", "G32a":"75.00000", "G32b":"79.00000", "G33a":"65.00000", "G33b":"60.00000", "G34a":"70.00000", "G34b":"60.00000", "G35a":"55.00000", "G35b":"54.00000", "G36a":"70.00000", "G36b":"54.00000", "G37a":"75.00000", "G37b":"68.00000", "G38a":"45.00000", "G38b":"43.00000", "G39a":"25.00000", "G39b":"28.00000", "G3a":"40.00000", "G3b":"40.00000", "G40a":"30.00000", "G40b":"28.00000", "G41a":"30.00000", "G41b":"28.00000", "G4a":"15.00000", "G4b":"14.00000", "G5a":"45.00000", "G5b":"40.00000", "G6a":"50.00000", "G6b":"48.00000", "G7a":"50.00000", "G7b":"51.00000", "G8a":"55.00000", "G8b":"65.00000", "G9a":"45.00000", "G9b":"48.00000", "fk_livello5":"1.1.1.1.0" }, "stili_lavoro":{ "F1":"75.00000", "F10":"70.00000", "F11":"95.00000", "F12":"80.00000", "F13":"100.00000", "F14":"75.00000", "F15":"80.00000", "F16":"90.00000", "F2":"85.00000", "F3":"90.00000", "F4":"80.00000", "F5":"70.00000", "F6":"80.00000", "F7":"60.00000", "F8":"80.00000", "F9":"85.00000", "fk_livello5":"1.1.1.1.0" }, "valori_professione":{ "E1":"60.00000", "E10":"40.00000", "E11":"70.00000", "E12":"40.00000", "E13":"0.00000", "E14":"90.00000", "E15":"60.00000", "E16":"50.00000", "E17":"40.00000", "E18":"20.00000", "E19":"70.00000", "E2":"60.00000", "E20":"20.00000", "E21":"50.00000", "E3":"80.00000", "E4":"30.00000", "E5":"50.00000", "E6":"90.00000", "E7":"10.00000", "E8":"30.00000", "E9":"50.00000", "fk_livello5":"1.1.1.1.0" } }, "1.1.1.2.0":{ "attitudini":{ "D10a":"58.00000", "D10b":"50.00000", "D11a":"49.00000", "D11b":"49.00000", "D12a":"22.00000", "D12b":"25.00000", "D13a":"29.00000", "D13b":"34.00000", "D14a":"63.00000", "D14b":"58.00000", "D15a":"72.00000", "D15b":"68.00000", "D16a":"50.00000", "D16b":"50.00000", "D17a":"33.00000", "D17b":"37.00000", "D18a":"14.00000", "D18b":"14.00000", "D19a":"18.00000", "D19b":"20.00000", "D1a":"87.00000", "D1b":"78.00000", "D20a":"62.00000", "D20b":"57.00000", "D21a":"79.00000", "D21b":"71.00000", "D22a":"1.00000", "D22b":"1.00000", "D23a":"0.00000", "D23b":"0.00000", "D24a":"1.00000", "D24b":"1.00000", "D25a":"0.00000", "D25b":"0.00000", "D26a":"0.00000", "D26b":"0.00000", "D27a":"0.00000", "D27b":"0.00000", "D28a":"0.00000", "D28b":"0.00000", "D29a":"0.00000", "D29b":"0.00000", "D2a":"92.00000", "D2b":"79.00000", "D30a":"0.00000", "D30b":"0.00000", "D31a":"0.00000", "D31b":"0.00000", "D32a":"0.00000", "D32b":"0.00000", "D33a":"0.00000", "D33b":"0.00000", "D34a":"0.00000", "D34b":"0.00000", "D35a":"0.00000", "D35b":"0.00000", "D36a":"3.00000", "D36b":"1.00000", "D37a":"0.00000", "D37b":"0.00000", "D38a":"0.00000", "D38b":"0.00000", "D39a":"0.00000", "D39b":"0.00000", "D3a":"89.00000", "D3b":"82.00000", "D40a":"0.00000", "D40b":"0.00000", "D41a":"11.00000", "D41b":"13.00000", "D42a":"7.00000", "D42b":"11.00000", "D43a":"4.00000", "D43b":"4.00000", "D44a":"4.00000", "D44b":"4.00000", "D45a":"4.00000", "D45b":"4.00000", "D46a":"1.00000", "D46b":"1.00000", "D47a":"1.00000", "D47b":"1.00000", "D48a":"7.00000", "D48b":"4.00000", "D49a":"8.00000", "D49b":"7.00000", "D4a":"83.00000", "D4b":"78.00000", "D50a":"12.00000", "D50b":"10.00000", "D51a":"22.00000", "D51b":"23.00000", "D52a":"71.00000", "D52b":"65.00000", "D5a":"64.00000", "D5b":"67.00000", "D6a":"57.00000", "D6b":"57.00000", "D7a":"75.00000", "D7b":"73.00000", "D8a":"80.00000", "D8b":"74.00000", "D9a":"79.00000", "D9b":"73.00000", "fk_livello5":"1.1.1.2.0" }, "competenze":{ "C10a":"70.00000", "C10b":"68.00000", "C11a":"67.00000", "C11b":"66.00000", "C12a":"72.00000", "C12b":"75.00000", "C13a":"75.00000", "C13b":"76.00000", "C14a":"83.00000", "C14b":"79.00000", "C15a":"53.00000", "C15b":"50.00000", "C16a":"70.00000", "C16b":"66.00000", "C17a":"80.00000", "C17b":"76.00000", "C18a":"66.00000", "C18b":"64.00000", "C19a":"5.00000", "C19b":"7.00000", "C1a":"97.00000", "C1b":"84.00000", "C20a":"32.00000", "C20b":"35.00000", "C21a":"3.00000", "C21b":"3.00000", "C22a":"0.00000", "C22b":"0.00000", "C23a":"29.00000", "C23b":"24.00000", "C24a":"0.00000", "C24b":"0.00000", "C25a":"0.00000", "C25b":"0.00000", "C26a":"0.00000", "C26b":"0.00000", "C27a":"58.00000", "C27b":"57.00000", "C28a":"0.00000", "C28b":"0.00000", "C29a":"53.00000", "C29b":"57.00000", "C2a":"92.00000", "C2b":"84.00000", "C30a":"55.00000", "C30b":"55.00000", "C31a":"79.00000", "C31b":"78.00000", "C32a":"79.00000", "C32b":"72.00000", "C33a":"75.00000", "C33b":"66.00000", "C34a":"36.00000", "C34b":"34.00000", "C35a":"72.00000", "C35b":"70.00000", "C3a":"84.00000", "C3b":"79.00000", "C4a":"92.00000", "C4b":"85.00000", "C5a":"26.00000", "C5b":"30.00000", "C6a":"13.00000", "C6b":"15.00000", "C7a":"83.00000", "C7b":"79.00000", "C8a":"79.00000", "C8b":"72.00000", "C9a":"43.00000", "C9b":"41.00000", "fk_livello5":"1.1.1.2.0" }, "compiti":{ "p1":"progettare e avanzare proposte di legge", "p10":"curare i rapporti con le istituzioni", "p11":"curare i rapporti con rappresentanti politici, sindacali, economici e sociali", "p12":"emettere ordinanze o delibere", "p13":"organizzare o partecipare a eventi (convegni, comizi, congressi, manifestazioni, ecc.)", "p14":"organizzare/partecipare a riunioni", "p15":"recepire istanze provenienti dal territorio", "p16":"curare i rapporti con soggetti o enti esterni", "p17":"discutere o emendare provvedimenti", "p18":"formulare pareri o proposte", "p19":"gestire le risorse finanziarie", "p2":"prendere parte alle sedute del consiglio o della giunta", "p20":"tenere i rapporti con il partito di appartenenza", "p21":"tenere i rapporti con l'elettorato (favorire la partecipazione dei cittadini, divulgare i risultati ottenuti, ecc.)", "p22":"aggiornarsi sulla normativa vigente", "p23":"curare i rapporti con i mezzi di informazione", "p24":"gestire e/o coordinare le risorse umane", "p25":"istruire procedimenti amministrativi", "p26":"rappresentare il consiglio o la giunta regionale", "p27":"svolgere attività istruttoria (interrogazioni, interpellanze, ecc.)", "p28":"cercare e reperire finanziamenti", "p29":"collaborare con le autorità politiche", "p3":"partecipare alle sedute delle commissioni", "p30":"curare i rapporti con i rappresentanti di altri partiti", "p31":"esercitare vigilanza amministrativa su enti controllati dalla regione", "p32":"verificare i risultati", "p4":"organizzare il lavoro o le attività", "p5":"votare normative o trasformare in leggi le proposte di legge", "p6":"applicare norme o regolamenti", "p7":"far parte di organi istituzionali", "p8":"impostare, sviluppare o controllare la realizzazione dei progetti", "p9":"svolgere attività di controllo sull'azione degli organismi di governo" }, "condizioni_lavoro":{ "H1":"96.05263", "H10":"30.26316", "H11":"64.47368", "H12":"68.42105", "H13":"48.68421", "H14":"2.63158", "H15":"94.73684", "H16":"11.84211", "H17":"21.05263", "H18":"1.31579", "H19":"0.00000", "H2":"65.78947", "H20":"32.89474", "H21":"31.57895", "H22":"18.42105", "H23":"7.89474", "H24":"0.00000", "H25":"0.00000", "H26":"0.00000", "H27":"0.00000", "H28":"0.00000", "H29":"0.00000", "H3":"100.00000", "H30":"0.00000", "H31":"0.00000", "H32":"0.00000", "H33":"0.00000", "H34":"71.05263", "H35":"0.00000", "H36":"23.68421", "H37":"0.00000", "H38":"0.00000", "H39":"30.26316", "H4":"100.00000", "H40":"2.63158", "H41":"0.00000", "H42":"5.26316", "H43":"0.00000", "H44":"0.00000", "H45":"56.57895", "H46":"80.26316", "H47":"67.10526", "H48":"75.00000", "H49":"6.57895", "H5":"93.42105", "H50":"64.47368", "H51":"21.05263", "H52":"68.42105", "H53":"75.00000", "H54":"65.78947", "H55":"3.94737", "H56":"5.26316", "H57":"55.15789", "H6":"92.10526", "H7":"81.57895", "H8":"69.73684", "H9":"75.00000", "fk_livello5":"1.1.1.2.0" }, "conoscenze":{ "B10a":"13.00000", "B10b":"15.00000", "B11a":"3.00000", "B11b":"8.00000", "B12a":"8.00000", "B12b":"6.00000", "B13a":"3.00000", "B13b":"4.00000", "B14a":"29.00000", "B14b":"35.00000", "B15a":"7.00000", "B15b":"11.00000", "B16a":"5.00000", "B16b":"5.00000", "B17a":"5.00000", "B17b":"6.00000", "B18a":"51.00000", "B18b":"53.00000", "B19a":"43.00000", "B19b":"42.00000", "B1a":"57.00000", "B1b":"50.00000", "B20a":"22.00000", "B20b":"24.00000", "B21a":"1.00000", "B21b":"2.00000", "B22a":"11.00000", "B22b":"8.00000", "B23a":"39.00000", "B23b":"42.00000", "B24a":"87.00000", "B24b":"77.00000", "B25a":"54.00000", "B25b":"53.00000", "B26a":"7.00000", "B26b":"8.00000", "B27a":"26.00000", "B27b":"30.00000", "B28a":"26.00000", "B28b":"28.00000", "B29a":"45.00000", "B29b":"44.00000", "B2a":"37.00000", "B2b":"35.00000", "B30a":"87.00000", "B30b":"82.00000", "B31a":"30.00000", "B31b":"23.00000", "B32a":"61.00000", "B32b":"55.00000", "B33a":"25.00000", "B33b":"28.00000", "B3a":"43.00000", "B3b":"43.00000", "B4a":"24.00000", "B4b":"25.00000", "B5a":"61.00000", "B5b":"61.00000", "B6a":"55.00000", "B6b":"52.00000", "B7a":"22.00000", "B7b":"24.00000", "B8a":"11.00000", "B8b":"11.00000", "B9a":"28.00000", "B9b":"28.00000", "fk_livello5":"1.1.1.2.0" }, "gwa":{ "G10a":"82.00000", "G10b":"75.00000", "G11a":"62.00000", "G11b":"60.00000", "G12a":"74.00000", "G12b":"69.00000", "G13a":"79.00000", "G13b":"70.00000", "G14a":"64.00000", "G14b":"65.00000", "G15a":"75.00000", "G15b":"69.00000", "G16a":"0.00000", "G16b":"0.00000", "G17a":"0.00000", "G17b":"0.00000", "G18a":"0.00000", "G18b":"0.00000", "G19a":"39.00000", "G19b":"33.00000", "G1a":"74.00000", "G1b":"70.00000", "G20a":"5.00000", "G20b":"1.00000", "G21a":"5.00000", "G21b":"5.00000", "G22a":"0.00000", "G22b":"0.00000", "G23a":"0.00000", "G23b":"0.00000", "G24a":"32.00000", "G24b":"36.00000", "G25a":"66.00000", "G25b":"58.00000", "G26a":"80.00000", "G26b":"76.00000", "G27a":"88.00000", "G27b":"85.00000", "G28a":"91.00000", "G28b":"80.00000", "G29a":"36.00000", "G29b":"33.00000", "G2a":"50.00000", "G2b":"47.00000", "G30a":"14.00000", "G30b":"18.00000", "G31a":"70.00000", "G31b":"71.00000", "G32a":"47.00000", "G32b":"46.00000", "G33a":"71.00000", "G33b":"70.00000", "G34a":"64.00000", "G34b":"59.00000", "G35a":"33.00000", "G35b":"36.00000", "G36a":"68.00000", "G36b":"70.00000", "G37a":"50.00000", "G37b":"49.00000", "G38a":"55.00000", "G38b":"55.00000", "G39a":"26.00000", "G39b":"25.00000", "G3a":"25.00000", "G3b":"24.00000", "G40a":"33.00000", "G40b":"35.00000", "G41a":"67.00000", "G41b":"69.00000", "G4a":"11.00000", "G4b":"10.00000", "G5a":"26.00000", "G5b":"29.00000", "G6a":"46.00000", "G6b":"46.00000", "G7a":"55.00000", "G7b":"52.00000", "G8a":"38.00000", "G8b":"38.00000", "G9a":"61.00000", "G9b":"54.00000", "fk_livello5":"1.1.1.2.0" }, "stili_lavoro":{ "F1":"80.00000", "F10":"82.00000", "F11":"91.00000", "F12":"74.00000", "F13":"93.00000", "F14":"76.00000", "F15":"72.00000", "F16":"82.00000", "F2":"84.00000", "F3":"80.00000", "F4":"82.00000", "F5":"86.00000", "F6":"84.00000", "F7":"86.00000", "F8":"83.00000", "F9":"86.00000", "fk_livello5":"1.1.1.2.0" }, "valori_professione":{ "E1":"61.00000", "E10":"21.00000", "E11":"61.00000", "E12":"50.00000", "E13":"45.00000", "E14":"66.00000", "E15":"61.00000", "E16":"32.00000", "E17":"26.00000", "E18":"8.00000", "E19":"50.00000", "E2":"47.00000", "E20":"37.00000", "E21":"55.00000", "E3":"74.00000", "E4":"13.00000", "E5":"63.00000", "E6":"58.00000", "E7":"18.00000", "E8":"37.00000", "E9":"39.00000", "fk_livello5":"1.1.1.2.0" } }


问:
Postion absolute effecting padding of parent div
I am trying to fix a button to the right edge of a div.

HTML:

```<code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>
</code>```

CSS:

```<code> #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }
</code>```

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

答:
The reason is that, surprisingly, when a div has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions using float with clear:both property

#header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   color: #ffffff;
   float:right;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
  <div style="clear:both;">

  </div>
</div></code>```

Body:
I am trying to fix a button to the right edge of a div.

HTML:

  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>

CSS:

 #header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   position: absolute;
   top: 10px;
   right: 10px;
   color: #ffffff;
 }

After applying position: absolute:

You can see in the image above that original padding: 20px on the parent div is ignored.

While removing position: absolute:

Brings the original padding back but as you can see the button is then not to the right. Applying float: right has the same effect.

Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn. Apologies if this is a very basic question.

Body:
The reason is that, surprisingly, when a div has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions using float with clear:both property

#header {
   margin-left: 240px;
   background-color: #0070e0;
   padding: 20px;
   position: relative;
 }

 #header > button {
   color: #ffffff;
   float:right;
 }

<div id="header">
  <button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
  <div style="clear:both;">

  </div>
</div>


问:
What SPARQL query can return item by its label and description text?
How should SPARQL query to looks like to return results by having label and description?</p>

答:
Could you please clarify, what is your query, and which dataset are posing it on?

In general, you can use rdfs:label to get labels, and you can filter them by language. The example SPARQL query hereinafter works on DBpedia SPARQL endpoint.

```<code>SELECT *
WHERE {
   ?x ?y ?z . # any triple
   ?x rdfs:label ?label . # getting the label of ?x
   FILTER (lang(?label) = "en") # filtering ?label to English labels
}
LIMIT 100
</code>```

For Wikidata, you can use the SERVICE and then get item description and label. The following query against Wikidata endpoint selects instances of Human, and brings back label and description. By using SERVICE, you can get the variables labels and description by appending 'Label' and 'Description' to the query head variables, e.g., for ?x label, you write ?xLabel.

```<code>SELECT ?x ?xLabel ?xDescription #
WHERE {
  ?x wdt:P31 wd:Q5. # ?x is an instance of Human
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } # English
}
LIMIT 10
</code>```

See Wikidata query examples for more wikidata details.

Body:
Could you please clarify, what is your query, and which dataset are posing it on?

In general, you can use rdfs:label to get labels, and you can filter them by language. The example SPARQL query hereinafter works on DBpedia SPARQL endpoint.

SELECT *
WHERE {
   ?x ?y ?z . # any triple
   ?x rdfs:label ?label . # getting the label of ?x
   FILTER (lang(?label) = "en") # filtering ?label to English labels
}
LIMIT 100

For Wikidata, you can use the SERVICE and then get item description and label. The following query against Wikidata endpoint selects instances of Human, and brings back label and description. By using SERVICE, you can get the variables labels and description by appending 'Label' and 'Description' to the query head variables, e.g., for ?x label, you write ?xLabel.

SELECT ?x ?xLabel ?xDescription #
WHERE {
  ?x wdt:P31 wd:Q5. # ?x is an instance of Human
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } # English
}
LIMIT 10

See Wikidata query examples for more wikidata details.


问:
How to decode U.P.S. Information from UPS MaxiCode Barcode?
I recently purchased a 2D Barcode reader. When scanning a U.P.S. barcode, I get about half of the information I want, and about half of it looks to be encrypted in some way. I have heard there is a UPS DLL.

Example - Everything in bold seems to be encrypted, while the non-bold text contains valuable, legitimate data.

[)>01961163522424800031Z50978063UPSN12312307G:%"6*AH537&M9&QXP2E:)16(E&539R'64O

In other words, this text seems OK - and I can parse the information
[)>01961163522424800031Z50978063UPSN123123 ...

While, this data seems to be encrypted
... 07G:%"6*AH537&M9&QXP2E:)16(E&539R'64O

Any Ideas???

Everything I read on the internet says I should be able to read this thing. I'm just not finding any information on specifics. The "encrypted" info contains street address, package number (like 1/2), weight, and several other items Im dying to get my hands on. I suppose I will contact UPS directly.

答: I expect the unreadable part is not UPS data, but private data intentially obfuscated by agreement between the shipper and receiver.</p>

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: le dorfier


问:
Unicode characters is shuffled in php imagettftext
I am trying to print unicode characters in image using GD library

I have following code

```<code>    $text = "கைவிடப்பட்ட";
    $font = "arial.ttf";
    $im = imagecreatetruecolor(2500, 500);
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 2500, 500, $white);
    imagettftext($im, 16, 0, 10, 20, $black, $font, $text);
    imagepng($im);
    imagedestroy($im);
</code>```

Original text here is கைவிடப்பட்ட , but it prints as following , you can see that first letter is replaced.

Edit : I have tried 5 different fonts All results in same(online font preview is showing characters correctly) .  whereas when I echo the string via php(from database) to browser, output is exactly same(கைவிடப்பட்ட), but why imagettftext is switching characters..

答:
I am not sure about GD library and environment but I guess the issue is due to rendering. கை = combination of க + ை and the environment doesn't support the rendering for unicode while displaying. so either check any rendering solution or use non unicode fonts or do below workaround to tackle it in php. </p>

```<code>$text = "கைவிடப்பட்ட";
$imgtext = tamilrender($text);
$font = "arial.ttf";
$im = imagecreatetruecolor(2500, 500);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 2500, 500, $white);
imagettftext($im, 16, 0, 10, 20, $black, $font, $imgtext);
imagepng($im);
imagedestroy($im);

function tamilrender($input)
{$input=  preg_replace("/([க-ஹ])([ைேெ])/u", "$2$1", $input);
$input= preg_replace("/([க-ஹ])ொ/u", "ெ$1ா", $input);
$input= preg_replace("/([க-ஹ])ோ/u", "ே$1ா", $input);
return $input;}
</code>```

Body:
I am trying to print unicode characters in image using GD library

I have following code

    $text = "கைவிடப்பட்ட";
    $font = "arial.ttf";
    $im = imagecreatetruecolor(2500, 500);
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 2500, 500, $white);
    imagettftext($im, 16, 0, 10, 20, $black, $font, $text);
    imagepng($im);
    imagedestroy($im);

Original text here is கைவிடப்பட்ட , but it prints as following , you can see that first letter is replaced.

Edit : I have tried 5 different fonts All results in same(online font preview is showing characters correctly) .  whereas when I echo the string via php(from database) to browser, output is exactly same(கைவிடப்பட்ட), but why imagettftext is switching characters..

Body:
I am not sure about GD library and environment but I guess the issue is due to rendering. கை = combination of க + ை and the environment doesn't support the rendering for unicode while displaying. so either check any rendering solution or use non unicode fonts or do below workaround to tackle it in php.

$text = "கைவிடப்பட்ட";
$imgtext = tamilrender($text);
$font = "arial.ttf";
$im = imagecreatetruecolor(2500, 500);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 2500, 500, $white);
imagettftext($im, 16, 0, 10, 20, $black, $font, $imgtext);
imagepng($im);
imagedestroy($im);

function tamilrender($input)
{$input=  preg_replace("/([க-ஹ])([ைேெ])/u", "$2$1", $input);
$input= preg_replace("/([க-ஹ])ொ/u", "ெ$1ா", $input);
$input= preg_replace("/([க-ஹ])ோ/u", "ே$1ா", $input);
return $input;}


问:
Java Swing Assigning a variable to a URL
Hello I'm developing a swing chat application where the chat history is being stored in an xml file.
I am able to fetch the xml file and display it in a table when done in the NetBeans project

But when converted to a jar file I am unable to use the xml file.
I've tried various things such as the getClass().getResource() method but it retrieves a URL rather than a string and if converted to a string using toString() method it cant be used as a valid path in order to parse the xml file.

Below is the code-->

ServerFrame.java

```<code>     public class ServerFrame extends javax.swing.JFrame {

        public String historyFile;
        public HistoryFrame historyFrame;
        public History hist;  }

        public ServerFrame() {
           historyFile=this.getClass().getResource("History.xml").toString();}

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

            hist = new History(historyFile);
            historyFrame = new HistoryFrame(hist);
            historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            historyFrame.setLocation(this.getLocation());
            historyFrame.setVisible(true);
    }
</code>```

History.java

```<code>public class History {

    public String filePath;

    public History(String filePath){

        this.filePath = filePath;
    }

    public void addMessage(Message msg, String time){

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filePath);

            Node data = doc.getFirstChild();

            Element message = doc.createElement("message");
            Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
            Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
            Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
            Element _time = doc.createElement("time"); _time.setTextContent(time);

            message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
            data.appendChild(message);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);

       }
           catch(Exception ex){
        System.out.println("Exceptionmodify xml");
       }
    }

    public void FillTable(HistoryFrame frame){

        DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();

        try{
            File fXmlFile = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("message");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
                }
            }
        }
        catch(Exception ex){
            System.out.println("Filling Exception");
        }
    }
</code>```

I have put the xml file in the src folder of Project directory.The problem seems to be in the docBuilder.parse() since everytime an exception is being generated in the function and it accepts only strings not urls since the system path of the file is different from javapath of the file.

I just need someway to access the xml file within the jar during execution. By access I mean just right filepath of xml file in the jar file and no need of file content.

答:
The problem is here:

```<code>StreamResult result = new StreamResult(new File(filePath));
</code>```

As you already seem to know, a URL is not a file path, and you can’t treat it as one.  You simply cannot do new File(filePath) and expect it to work, ever.  The string you’re storing in filePath is not a file path at all, it’s a URL.

But you have a more fundamental problem:  A resource is read-only.  You can’t write to it, period.  All Java applications are deployed in .jar or .war files, and even if you can access the original archive (and there’s no guarantee you can), you may not have permission to write it (especially in Windows, where it’s likely to be locked), and even if you can write it, the application won’t see the changes.

In short, you should not try to write to a resource.

Instead, treat your resource as a default set of values, and choose a reliable location, such as a temporary file or a file in the user’s home directory, to write the new data:

```<code>File resultFile = File.createTempFile("history", ".xml");
StreamResult result = new StreamResult(resultFile);
</code>```

A side note:  Always expose the stack trace of a caught exception, either with a logging statement, exception chaining, or at the very least, a call to printStackTrace().  Also, do not catch java.lang.Exception;  you should not suppress programmer errors like NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, and so on.  Instead, catch only the exceptions you’re required to catch:

```<code>} catch (ParserConfigurationException | SAXException | IOException | TransformerException ex) {
</code>```

Body:
Hello I'm developing a swing chat application where the chat history is being stored in an xml file.
I am able to fetch the xml file and display it in a table when done in the NetBeans project

But when converted to a jar file I am unable to use the xml file.
I've tried various things such as the getClass().getResource() method but it retrieves a URL rather than a string and if converted to a string using toString() method it cant be used as a valid path in order to parse the xml file.

Below is the code-->

ServerFrame.java

     public class ServerFrame extends javax.swing.JFrame {

        public String historyFile;
        public HistoryFrame historyFrame;
        public History hist;  }

        public ServerFrame() {
           historyFile=this.getClass().getResource("History.xml").toString();}

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

            hist = new History(historyFile);
            historyFrame = new HistoryFrame(hist);
            historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            historyFrame.setLocation(this.getLocation());
            historyFrame.setVisible(true);
    }

History.java

public class History {

    public String filePath;

    public History(String filePath){

        this.filePath = filePath;
    }

    public void addMessage(Message msg, String time){

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filePath);

            Node data = doc.getFirstChild();

            Element message = doc.createElement("message");
            Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
            Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
            Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
            Element _time = doc.createElement("time"); _time.setTextContent(time);

            message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
            data.appendChild(message);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);

       }
           catch(Exception ex){
        System.out.println("Exceptionmodify xml");
       }
    }

    public void FillTable(HistoryFrame frame){

        DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();

        try{
            File fXmlFile = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("message");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
                }
            }
        }
        catch(Exception ex){
            System.out.println("Filling Exception");
        }
    }

I have put the xml file in the src folder of Project directory.The problem seems to be in the docBuilder.parse() since everytime an exception is being generated in the function and it accepts only strings not urls since the system path of the file is different from javapath of the file.

I just need someway to access the xml file within the jar during execution. By access I mean just right filepath of xml file in the jar file and no need of file content.

Body:
The problem is here:

StreamResult result = new StreamResult(new File(filePath));

As you already seem to know, a URL is not a file path, and you can’t treat it as one.  You simply cannot do new File(filePath) and expect it to work, ever.  The string you’re storing in filePath is not a file path at all, it’s a URL.

But you have a more fundamental problem:  A resource is read-only.  You can’t write to it, period.  All Java applications are deployed in .jar or .war files, and even if you can access the original archive (and there’s no guarantee you can), you may not have permission to write it (especially in Windows, where it’s likely to be locked), and even if you can write it, the application won’t see the changes.

In short, you should not try to write to a resource.

Instead, treat your resource as a default set of values, and choose a reliable location, such as a temporary file or a file in the user’s home directory, to write the new data:

File resultFile = File.createTempFile("history", ".xml");
StreamResult result = new StreamResult(resultFile);

A side note:  Always expose the stack trace of a caught exception, either with a logging statement, exception chaining, or at the very least, a call to printStackTrace().  Also, do not catch java.lang.Exception;  you should not suppress programmer errors like NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, and so on.  Instead, catch only the exceptions you’re required to catch:

} catch (ParserConfigurationException | SAXException | IOException | TransformerException ex) {


问:
BigTop docker-hadoop.sh failing to start
I'm using BigTop 1.2.0 the vagrant provisioner is running fine but when I try to use the Docker provisioner the following error is showing:

Command

$ ./docker-hadoop.sh -c 3

Error

Environment check...
  Check docker:
  Docker version 17.09.0-ce, build afdb6d4
  Check docker-compose:
  docker-compose version 1.16.1, build 6d1ac219
  Check ruby: ruby 2.4.2p198 (2017-09-14 revision 59899) [x64-mingw32]
  -e:1:in ': undefined method[]' for nil:NilClass (NoMethodError)
  -e:1:in ': undefined method[]' for nil:NilClass (NoMethodError)
  The scale command is deprecated. Use the up command with the --scale flag instead.
  Creating 20171020215450r21863_bigtop_1 ...
  Creating 20171020215450r21863_bigtop_2 ...
  Creating 20171020215450r21863_bigtop_3 ...

ERROR: for 20171020215450r21863_bigtop_2  Resource ID was not provided
  ERROR: for 20171020215450r21863_bigtop_3  Resource ID was not provided
  ERROR: for 20171020215450r21863_bigtop_1  Resource ID was not provided

Traceback (most recent call last):

     File "docker-compose", line 6, in

     File "compose\cli\main.py", line 68, in main

     File "compose\cli\main.py", line 121, in perform_command

     File "compose\cli\main.py", line 796, in scale

     File "compose\service.py", line 257, in scale
     File "compose\service.py", line 444, in _execute_convergence_start
     File "compose\service.py", line 395, in _execute_convergence_create
     File "compose\parallel.py", line 70, in parallel_execute
  docker.errors.NullResource: Resource ID was not provided
  Failed to execute script docker-compose
  Docker container(s) startup failed!

Thanks in advance.

答:
It seems that you're running docker-hadoop.sh on windows with mingw32. The Docker Provisioner is tested to work on Mac and Amazon Linux for Bigtop releases just because of the resource limitation. So I'm not quite sure what's the story at Windows side ;)

However, from your error log:

undefined method[]' for nil:NilClass (NoMethodError)

I'm pretty sure that the issue is related to our ruby YAML parsing feature:
https://github.com/apache/bigtop/blob/master/provisioner/docker/docker-hadoop.sh#L138

To this end, I'd suggest you to stick with Vagrant Provisioner on Windows.
If you'd like to help us in making the feature compatible with Windows, feel free to reach out to dev@bigtop.apache.org


问:
Sublime text find only <? character
Is there a way to get all content <? but not <?php or <?= in sublime text?

I tried <? \n, it doesn't give me the desired results.

答:
You should search <? by regex, with negative lookahead.

```<code><\?(?!(php|=))
</code>```

Title: Sublime text find only <? character

Body:
You should search <? by regex, with negative lookahead.

<\?(?!(php|=))


问:
How to get employees with their past and current jobs in mongodb?
I am new to NoSQL databases and so I'm struggling with the structure and the queries.

I am currently working with a company dataset in mongodb which has the following structure:

```<code>{
    "_id": "52cdef7c4bab8bd675297d8b",
    "name": "AdventNet",
    "permalink": "abc3",
    "category_code": "enterprise",
    "number_of_employees": 600,
    "founded_year": 1996,
    "relationships": [{
        "is_past": true,
        "title": "CEO and Co-Founder",
        "person": {
            "first_name": "Sridhar",
            "last_name": "Vembu",
            "permalink": "sridhar-vembu"
        }
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "person": {
            "first_name": "Neil",
            "last_name": "Butani",
            "permalink": "neil-butani"
        }
    }, {
        "is_past": true,
        "title": "Western Regional OEM Sales Manager",
        "person": {
            "first_name": "Ian",
            "last_name": "Wenig",
            "permalink": "ian-wenig"
       }
    },
    ...
    }]
}
</code>```

What I would like to achieve is to get a new collection with each employee name and all his/her past and current jobs, for example:

```<code>{
    "_id": "neil-butani",
    "first_name": "Neil",
    "last_name": "butani",
    "employments": [{
        "is_past": false,
        "title": "CEO and Co-Founder",
        "company_name": "AdventNet"
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "company_name": "Example Inc.""
    }]
}
</code>```

In SQL I would write query which joined the employees table with the companies table, but what operators and concept could or should I use to get the desired result in mongodb?

答:
You can $unwind and $group by permalink to collect all employments followed by $out to write into new collection.

Something like

```<code>db.collection_name.aggregate([
  {
    "$unwind": "$relationships"
  },
  {
    "$group": {
      "_id": "$relationships.person.permalink",
      "first_name": {
        "$first": "$relationships.person.first_name"
      },
      "last_name": {
        "$first": "$relationships.person.last_name"
      },
      "employments": {
        "$push": {
          "is_past": "$relationships.is_past",
          "title": "$relationships.title",
          "company_name": "$name"
        }
      }
    }
  },
  {
    "$out": "new collection name"
  }
])
</code>```

Body:
I am new to NoSQL databases and so I'm struggling with the structure and the queries.

I am currently working with a company dataset in mongodb which has the following structure:

{
    "_id": "52cdef7c4bab8bd675297d8b",
    "name": "AdventNet",
    "permalink": "abc3",
    "category_code": "enterprise",
    "number_of_employees": 600,
    "founded_year": 1996,
    "relationships": [{
        "is_past": true,
        "title": "CEO and Co-Founder",
        "person": {
            "first_name": "Sridhar",
            "last_name": "Vembu",
            "permalink": "sridhar-vembu"
        }
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "person": {
            "first_name": "Neil",
            "last_name": "Butani",
            "permalink": "neil-butani"
        }
    }, {
        "is_past": true,
        "title": "Western Regional OEM Sales Manager",
        "person": {
            "first_name": "Ian",
            "last_name": "Wenig",
            "permalink": "ian-wenig"
       }
    },
    ...
    }]
}

What I would like to achieve is to get a new collection with each employee name and all his/her past and current jobs, for example:

{
    "_id": "neil-butani",
    "first_name": "Neil",
    "last_name": "butani",
    "employments": [{
        "is_past": false,
        "title": "CEO and Co-Founder",
        "company_name": "AdventNet"
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "company_name": "Example Inc.""
    }]
}

In SQL I would write query which joined the employees table with the companies table, but what operators and concept could or should I use to get the desired result in mongodb?

Body:
You can $unwind and $group by permalink to collect all employments followed by $out to write into new collection.

Something like

db.collection_name.aggregate([
  {
    "$unwind": "$relationships"
  },
  {
    "$group": {
      "_id": "$relationships.person.permalink",
      "first_name": {
        "$first": "$relationships.person.first_name"
      },
      "last_name": {
        "$first": "$relationships.person.last_name"
      },
      "employments": {
        "$push": {
          "is_past": "$relationships.is_past",
          "title": "$relationships.title",
          "company_name": "$name"
        }
      }
    }
  },
  {
    "$out": "new collection name"
  }
])


问:
I need to input 20 numbers and to output only double location
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.</p>

```<code>#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;

for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}

for(i=0;i<n;i++)
{
    if (i%2==0 && i!=1 && i!=0)
    {
        printf("%d\n",num[i]);
    }
}
}
</code>```

答:
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.</p>

```<code>for (i = 2; i < n; i += 2)
{
    printf("%d\n",num[i]);
}
</code>```

Body:
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.

#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;

for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}

for(i=0;i<n;i++)
{
    if (i%2==0 && i!=1 && i!=0)
    {
        printf("%d\n",num[i]);
    }
}
}

Body:
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.

for (i = 2; i < n; i += 2)
{
    printf("%d\n",num[i]);
}


问:
Data Frame Modification in R
the three lines of R code below show a vector a1,b1 and "c1" which is the unique of fields a1. I want to display a data frame of two columns where I should get every element of c1 displayed the number of times equal to the length of elements in "a1", in one column, and the corresponding ID "b1" of that letter in another column. Simply, say a data frame with column "y" in which say letter "a" from "c1" will be represented 6 times back to back(length of string a1), then "b" 6 times, then c and so on. Also corresponding to a in other column, "1" 6 times, then "2" 6 times and so on. Please help and thanks.

```<code>a1 = c("a","b","c","d","a","b")
b1 = c(1,2,3,4,1,2)
c1 = unique(a1)
</code>```

New Change

```<code>a1 = c("a","b","b","d","c","e","f","a","b","c","d")
b1 = c(1,1,1,2,3,2,3,1,1,3,2)
c1 = unique(a1)
</code>```

答:
This achieves what you ask I believe:</p>

```<code>cbind(rep(c1, each = length(a1)),rep(b1, each = length(a1)))
</code>```

Title: Data Frame Modification in R

Body:
the three lines of R code below show a vector a1,b1 and "c1" which is the unique of fields a1. I want to display a data frame of two columns where I should get every element of c1 displayed the number of times equal to the length of elements in "a1", in one column, and the corresponding ID "b1" of that letter in another column. Simply, say a data frame with column "y" in which say letter "a" from "c1" will be represented 6 times back to back(length of string a1), then "b" 6 times, then c and so on. Also corresponding to a in other column, "1" 6 times, then "2" 6 times and so on. Please help and thanks.

a1 = c("a","b","c","d","a","b")
b1 = c(1,2,3,4,1,2)
c1 = unique(a1)

New Change

a1 = c("a","b","b","d","c","e","f","a","b","c","d")
b1 = c(1,1,1,2,3,2,3,1,1,3,2)
c1 = unique(a1)

Body:
This achieves what you ask I believe:

cbind(rep(c1, each = length(a1)),rep(b1, each = length(a1)))


问:
How to pass a vector of strings to execv
I have found that the easiest way to build my program argument list is as a vector of strings. However, execv expects an array of chars for the second argument. What's the easiest way to get it to accept of vector of strings?</p>

答:
Yes, it can be done pretty cleanly by taking advantage of the internal array that vectors use. Best to not use C++ strings in the vector, and const_cast string literals and string.c_str()'s to char*.

This will work, since the standard guarantees its elements are stored contiguously (see https://stackoverflow.com/a/2923290/383983)

```<code>#include <unistd.h>
#include <vector>

using std::vector;

int main() {
  vector<const char*> command;

  // do a push_back for the command, then each of the arguments
  command.push_back("echo");
  command.push_back("testing");
  command.push_back("1");
  command.push_back("2");
  command.push_back("3");

  // push NULL to the end of the vector (execvp expects NULL as last element)
  command.push_back(NULL);

  // pass the vector's internal array to execvp
  execvp(command[0], const_cast<char* const*>(command.data()));
  return 1;
}
</code>```

Code adapted from: How to pass a vector to execvp

Do a const_cast to avoid the "deprecated conversion from string constant to 'char*'". String literals are implemented as const char* in C++. const_cast is the safest form of cast here, as it only removes the const and does not do any other funny business. execvp() will not edit the values anyway.

If you want to avoid all casts, you have to complicate this code by copying all the values to char* types not really worth it.

Although if the number of arguments you want to pass to execv/execl is known, it's easier to write this in C.

Body:
Yes, it can be done pretty cleanly by taking advantage of the internal array that vectors use. Best to not use C++ strings in the vector, and const_cast string literals and string.c_str()'s to char*.

This will work, since the standard guarantees its elements are stored contiguously (see https://stackoverflow.com/a/2923290/383983)

#include <unistd.h>
#include <vector>

using std::vector;

int main() {
  vector<const char*> command;

  // do a push_back for the command, then each of the arguments
  command.push_back("echo");
  command.push_back("testing");
  command.push_back("1");
  command.push_back("2");
  command.push_back("3");

  // push NULL to the end of the vector (execvp expects NULL as last element)
  command.push_back(NULL);

  // pass the vector's internal array to execvp
  execvp(command[0], const_cast<char* const*>(command.data()));
  return 1;
}

Code adapted from: How to pass a vector to execvp

Do a const_cast to avoid the "deprecated conversion from string constant to 'char*'". String literals are implemented as const char* in C++. const_cast is the safest form of cast here, as it only removes the const and does not do any other funny business. execvp() will not edit the values anyway.

If you want to avoid all casts, you have to complicate this code by copying all the values to char* types not really worth it.

Although if the number of arguments you want to pass to execv/execl is known, it's easier to write this in C.


问:
How to filter the file types in primeng p-fileupload component
I am trying to filter the file dialogue window using p-fileUpload from primeng.
I saw an example to to filter images as image/* and it works but i want ti filter for excel files. I tried file/excel, file/*.xls etc, but no help. Need help.</p>

答:
Try below inputs with accept property in p-fileUpload in Angular

Image filter

accept="image/*"[accepts all image file types]

accept="image/*.jpeg"[accepts only JPEG image file types]

File filter

accept="application/msexcel" [accepts only xls file types]

accept=".xlsm,application/msexcel" [accepts only xls & xlsm file types]

accept="application/msmsword" [accepts only word file types]


问:
Change image layout or wrap in DOCX with Apache POI
I paste image into docx programmatically. But in result the layout does not suit me. Faced a lack of documentation.
I need to change image wrap (layout). For example now I have this:

But want this:

UPD1: What I do: iterate through the paragraphs, then through the runs and find certain run with special bookmark. In this run I add picture:

```<code>XWPFPicture pic =  run.addPicture(
        new ByteArrayInputStream(picSource),
        Document.PICTURE_TYPE_PNG,
        "pic",
        Units.toEMU(100),
        Units.toEMU(30));
</code>```

UPD2: Investigated something interesting inside this class:

```<code>org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor
</code>```

method setWrapTight(CTWrapTight var1). May be is it. By still don't know how to apply it to my code.

UPD3: Finally I came to this (currentRun - run with our picture):

```<code>    CTWrapTight ctWrapTight = currentRun.getCTR().getDrawingList().get(0).addNewAnchor().addNewWrapTight();
 CTWrapPath ctWrapPath = ctWrapTight.addNewWrapPolygon();

 CTPoint2D ctStart = ctWrapPath.addNewStart();
 ctStart.setX(0L);
 ctStart.setY(0L);

 CTPoint2D ctLineTo1 = ctWrapPath.addNewLineTo();
 CTPoint2D ctLineTo2 = ctWrapPath.addNewLineTo();
 CTPoint2D ctLineTo3 = ctWrapPath.addNewLineTo();

 ctLineTo1.setX(21384L);
 ctLineTo1.setY(20520L);

 ctLineTo2.setX(21384L);
 ctLineTo2.setY(0L);

 ctLineTo3.setX(0L);
 ctLineTo3.setY(0L);

ctWrapTight.setWrapText(STWrapText.BOTH_SIDES);
</code>```

But it's break down document when I try to open it:

We're sorry. We can't open document because we found a problem with
  its contents.

Dependency are:

```<code><dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>ooxml-schemas</artifactId>
        <version>1.3</version>
    </dependency>
</code>```

答:
While you already found the right classes to use - CTAnchor and successors - there is also the need considering the XML Schema definition of  anchor. And this states there are many more duty elements required than only the ones which are defining wrapping. So using class by class of  org.openxmlformats.schemas.drawingml.x2006 you are probably coding page wise code. My preferred solution for such problems is providing XML having all needed elements updated by some variables. This XML then can be parsed to get the needed object.

Example:

```<code>import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.util.Units;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;

public class WordInsertPictures {

 private static CTAnchor getAnchorWithGraphic(CTGraphicalObject graphicalobject,
                                              String drawingDescr, int width, int height,
                                              int left, int top) throws Exception {

  String anchorXML =
   "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
  +"simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
  +"<wp:simplePos x=\"0\" y=\"0\"/>"
  +"<wp:positionH relativeFrom=\"column\"><wp:posOffset>"+left+"</wp:posOffset></wp:positionH>"
  +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>"+top+"</wp:posOffset></wp:positionV>"
  +"<wp:extent cx=\""+width+"\" cy=\""+height+"\"/>"
  +"<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
  +"<wp:wrapTight wrapText=\"bothSides\">"
  +"<wp:wrapPolygon edited=\"0\">"
  +"<wp:start x=\"0\" y=\"0\"/>"
  +"<wp:lineTo x=\"0\" y=\"21600\"/>" //Square polygon 21600 x 21600 leads to wrap points in fully width x height
  +"<wp:lineTo x=\"21600\" y=\"21600\"/>"// Why? I don't know. Try & error ;-).
  +"<wp:lineTo x=\"21600\" y=\"0\"/>"
  +"<wp:lineTo x=\"0\" y=\"0\"/>"
  +"</wp:wrapPolygon>"
  +"</wp:wrapTight>"
  +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
  +"</wp:anchor>";

  CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);
  CTAnchor anchor = drawing.getAnchorArray(0);
  anchor.setGraphic(graphicalobject);
  return anchor;
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();

  run.setText("The picture in line: ");

  InputStream in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();

  run.setText(" text after the picture.");

  paragraph = document.createParagraph();

  run = paragraph.createRun();
  in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();
  CTDrawing drawing = run.getCTR().getDrawingArray(0);
  CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
  CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "samplePict.jpeg",
                                         Units.toEMU(100), Units.toEMU(30),
                                         Units.toEMU(30), Units.toEMU(0));
  drawing.setAnchorArray(new CTAnchor[]{anchor});
  drawing.removeInline(0);

  run = paragraph.createRun();
  run.setText("The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight.");

  document.write(new FileOutputStream("WordInsertPictures.docx"));
  document.close();
 }
}
</code>```

Body:
I paste image into docx programmatically. But in result the layout does not suit me. Faced a lack of documentation.
I need to change image wrap (layout). For example now I have this:

But want this:

UPD1: What I do: iterate through the paragraphs, then through the runs and find certain run with special bookmark. In this run I add picture:

XWPFPicture pic =  run.addPicture(
        new ByteArrayInputStream(picSource),
        Document.PICTURE_TYPE_PNG,
        "pic",
        Units.toEMU(100),
        Units.toEMU(30));

UPD2: Investigated something interesting inside this class:

org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor

method setWrapTight(CTWrapTight var1). May be is it. By still don't know how to apply it to my code.

UPD3: Finally I came to this (currentRun - run with our picture):

    CTWrapTight ctWrapTight = currentRun.getCTR().getDrawingList().get(0).addNewAnchor().addNewWrapTight();
 CTWrapPath ctWrapPath = ctWrapTight.addNewWrapPolygon();

 CTPoint2D ctStart = ctWrapPath.addNewStart();
 ctStart.setX(0L);
 ctStart.setY(0L);

 CTPoint2D ctLineTo1 = ctWrapPath.addNewLineTo();
 CTPoint2D ctLineTo2 = ctWrapPath.addNewLineTo();
 CTPoint2D ctLineTo3 = ctWrapPath.addNewLineTo();

 ctLineTo1.setX(21384L);
 ctLineTo1.setY(20520L);

 ctLineTo2.setX(21384L);
 ctLineTo2.setY(0L);

 ctLineTo3.setX(0L);
 ctLineTo3.setY(0L);

ctWrapTight.setWrapText(STWrapText.BOTH_SIDES);

But it's break down document when I try to open it:

We're sorry. We can't open document because we found a problem with
  its contents.

Dependency are:

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>ooxml-schemas</artifactId>
        <version>1.3</version>
    </dependency>

Body:
While you already found the right classes to use - CTAnchor and successors - there is also the need considering the XML Schema definition of  anchor. And this states there are many more duty elements required than only the ones which are defining wrapping. So using class by class of  org.openxmlformats.schemas.drawingml.x2006 you are probably coding page wise code. My preferred solution for such problems is providing XML having all needed elements updated by some variables. This XML then can be parsed to get the needed object.

Example:

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.util.Units;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;

public class WordInsertPictures {

 private static CTAnchor getAnchorWithGraphic(CTGraphicalObject graphicalobject,
                                              String drawingDescr, int width, int height,
                                              int left, int top) throws Exception {

  String anchorXML =
   "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
  +"simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
  +"<wp:simplePos x=\"0\" y=\"0\"/>"
  +"<wp:positionH relativeFrom=\"column\"><wp:posOffset>"+left+"</wp:posOffset></wp:positionH>"
  +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>"+top+"</wp:posOffset></wp:positionV>"
  +"<wp:extent cx=\""+width+"\" cy=\""+height+"\"/>"
  +"<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
  +"<wp:wrapTight wrapText=\"bothSides\">"
  +"<wp:wrapPolygon edited=\"0\">"
  +"<wp:start x=\"0\" y=\"0\"/>"
  +"<wp:lineTo x=\"0\" y=\"21600\"/>" //Square polygon 21600 x 21600 leads to wrap points in fully width x height
  +"<wp:lineTo x=\"21600\" y=\"21600\"/>"// Why? I don't know. Try & error ;-).
  +"<wp:lineTo x=\"21600\" y=\"0\"/>"
  +"<wp:lineTo x=\"0\" y=\"0\"/>"
  +"</wp:wrapPolygon>"
  +"</wp:wrapTight>"
  +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
  +"</wp:anchor>";

  CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);
  CTAnchor anchor = drawing.getAnchorArray(0);
  anchor.setGraphic(graphicalobject);
  return anchor;
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();

  run.setText("The picture in line: ");

  InputStream in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();

  run.setText(" text after the picture.");

  paragraph = document.createParagraph();

  run = paragraph.createRun();
  in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();
  CTDrawing drawing = run.getCTR().getDrawingArray(0);
  CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
  CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "samplePict.jpeg",
                                         Units.toEMU(100), Units.toEMU(30),
                                         Units.toEMU(30), Units.toEMU(0));
  drawing.setAnchorArray(new CTAnchor[]{anchor});
  drawing.removeInline(0);

  run = paragraph.createRun();
  run.setText("The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight.");

  document.write(new FileOutputStream("WordInsertPictures.docx"));
  document.close();
 }
}


问:
Return a Message with HTTP Error Response Code in Flask?
How can a message body be added to a 404 response in flask?

The following attempts will generate a 404 but without the message:

```<code>@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        return "I don't care what they say, tomato is not a fruit", 404

    return "yummy"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        flask.abort(404,"I don't care what they say, tomato is not a fruit")

    return "yummy"
</code>```

Thank you in advance for your consideration and response.

答:
You can add the builtin 404 error handler:</p>

```<code>@app.errorhandler(404)
def page_not_found(e):
    return "I don't care what they say, tomato is not a fruit"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
  if fruit_name == "tomato":
     return flask.redirect('/404')
</code>```

Body:
How can a message body be added to a 404 response in flask?

The following attempts will generate a 404 but without the message:

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        return "I don't care what they say, tomato is not a fruit", 404

    return "yummy"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        flask.abort(404,"I don't care what they say, tomato is not a fruit")

    return "yummy"

Thank you in advance for your consideration and response.

Body:
You can add the builtin 404 error handler:

@app.errorhandler(404)
def page_not_found(e):
    return "I don't care what they say, tomato is not a fruit"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
  if fruit_name == "tomato":
     return flask.redirect('/404')