问:
NullPointerException when popBackStackImmediate()
I have problem with fragment's backStack. Firstly, my structure is: I have activity with fragmentManager, new fragments added with method add() and with adding to back stack. So, when I have at list 2 fragments in backstack and when I have orientation changing, activity is recreated, and fragment restored, but when I call onBackPressed() and call popBackStackImmediate() I get an exception:  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference.

It seem's, that we have null fragment in back stack, but I've checked it, this fragments weren't null. So, can you help solve this problem?

I add fragments like this:

```<code>FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

fragmentTransaction
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

if (previousFragment != null) {
   fragmentTransaction.hide(previousFragment);
}

fragmentTransaction.add(containerViewId, fragment, fragmentTag)
            .addToBackStack(fragmentTag)
            .commit();
</code>```

In onBackPressed() I have same behaivor:

```<code> if (fragmentManager.getBackStackEntryCount() == 1) {
    finish();
 } else {
   super.onBackPressed();
 }
</code>```

Full stackTrace is:

```<code> java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference
                                                                             at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:826)
                                                                             at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2587)
                                                                             at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2377)
                                                                             at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2332)
                                                                             at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851)
                                                                             at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
                                                                             at net.lampa.tablet.nightexpress.view.activities.OrderFinalActivity.onBackPressed(OrderFinalActivity.java:147)
                                                                             at net.lampa.tablet.nightexpress.view.activities.OrderFinalActivity.onOptionsItemSelected(OrderFinalActivity.java:183)
                                                                             at android.app.Activity.onMenuItemSelected(Activity.java:2914)
                                                                             at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:380)
                                                                             at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                                                                             at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                                                                             at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                                                                             at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:187)
                                                                             at android.view.View.performClick(View.java:5204)
                                                                             at android.view.View$PerformClick.run(View.java:21153)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

line 164 is:

```<code>super.onBackPressed()
</code>```

Full code of base activity with adding logic:

```<code>public abstract class BaseActivity extends AppCompatActivity {

private Unbinder uninder;

protected BaseFragment currentFragment;
protected BaseFragment previousFragment;
protected FragmentManager fragmentManager;

private Map<Integer, ArrayList<String>> filterTagsMap = new TreeMap<>();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Class cls = getClass();
    if (!cls.isAnnotationPresent(Layout.class)) {
        return; // Layout annotation is required
    }
    Annotation annotation = cls.getAnnotation(Layout.class);
    setContentView(((Layout) annotation).id());
    uninder = ButterKnife.bind(this);

    if(fragmentManager == null) {
        fragmentManager = getSupportFragmentManager();
    }

    currentFragment = getDefaultFragment();

    inject();  // inject dependencies
    setupDefaultValues();
}

public ApplicationComponent getApplicationComponent() {
    return ((NEApplication) getApplication()).getApplicationComponent();
}

public abstract void setupDefaultValues();

public void closeCurrentFragmentInBackStack() {
    fragmentManager.popBackStackImmediate();
}

public void showFragment(int containerViewId, BaseFragment fragment, boolean needToRefreshBackStack) {

    if (needToRefreshBackStack && fragmentManager.getBackStackEntryCount() > 0) {
        int indexToDelete = (fragment.getClass().getSimpleName()
                .equals(fragmentManager.getBackStackEntryAt(0).getName())) ? 0 : 1;
        int backStackFragmentsCount = fragmentManager.getBackStackEntryCount();
        for (int i = backStackFragmentsCount - 1; i >= indexToDelete; i--) {
            int backStackId = fragmentManager.getBackStackEntryAt(i).getId();
            fragmentManager.popBackStack(backStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    previousFragment = currentFragment;
    currentFragment = fragment;

    String fragmentTag = fragment.getClass().getSimpleName();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    if (previousFragment != null) {
        fragmentTransaction.hide(previousFragment);
    }
    fragmentTransaction.add(containerViewId, fragment, fragmentTag)
            .addToBackStack(fragmentTag)
            .commit();

}

protected abstract BaseFragment getDefaultFragment();

@Override
protected void onDestroy() {
    uninder.unbind();
    uninder = null;
    super.onDestroy();
}
}
</code>```

答:
The condition of popping the fragment itself is written logically in reverse. super.onBackPressed() will pop the fragment if it is present in the backstack.So if the getBackStackEntryCount() is greater than zero you need to call the super method or else finish the activity when there is no fragments in backstack.

```<code>if (fragmentManager.getBackStackEntryCount() >=0) {
    getSupportFragmentManager().popBackStackImmediate()
} else {
    super.onBackPressed();
}
</code>```

Body:
I have problem with fragment's backStack. Firstly, my structure is: I have activity with fragmentManager, new fragments added with method add() and with adding to back stack. So, when I have at list 2 fragments in backstack and when I have orientation changing, activity is recreated, and fragment restored, but when I call onBackPressed() and call popBackStackImmediate() I get an exception:  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference.

It seem's, that we have null fragment in back stack, but I've checked it, this fragments weren't null. So, can you help solve this problem?

I add fragments like this:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

fragmentTransaction
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

if (previousFragment != null) {
   fragmentTransaction.hide(previousFragment);
}

fragmentTransaction.add(containerViewId, fragment, fragmentTag)
            .addToBackStack(fragmentTag)
            .commit();

In onBackPressed() I have same behaivor:

 if (fragmentManager.getBackStackEntryCount() == 1) {
    finish();
 } else {
   super.onBackPressed();
 }

Full stackTrace is:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference
                                                                             at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:826)
                                                                             at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2587)
                                                                             at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2377)
                                                                             at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2332)
                                                                             at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851)
                                                                             at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
                                                                             at net.lampa.tablet.nightexpress.view.activities.OrderFinalActivity.onBackPressed(OrderFinalActivity.java:147)
                                                                             at net.lampa.tablet.nightexpress.view.activities.OrderFinalActivity.onOptionsItemSelected(OrderFinalActivity.java:183)
                                                                             at android.app.Activity.onMenuItemSelected(Activity.java:2914)
                                                                             at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:380)
                                                                             at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                                                                             at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                                                                             at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                                                                             at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:187)
                                                                             at android.view.View.performClick(View.java:5204)
                                                                             at android.view.View$PerformClick.run(View.java:21153)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

line 164 is:

super.onBackPressed()

Full code of base activity with adding logic:

public abstract class BaseActivity extends AppCompatActivity {

private Unbinder uninder;

protected BaseFragment currentFragment;
protected BaseFragment previousFragment;
protected FragmentManager fragmentManager;

private Map<Integer, ArrayList<String>> filterTagsMap = new TreeMap<>();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Class cls = getClass();
    if (!cls.isAnnotationPresent(Layout.class)) {
        return; // Layout annotation is required
    }
    Annotation annotation = cls.getAnnotation(Layout.class);
    setContentView(((Layout) annotation).id());
    uninder = ButterKnife.bind(this);

    if(fragmentManager == null) {
        fragmentManager = getSupportFragmentManager();
    }

    currentFragment = getDefaultFragment();

    inject();  // inject dependencies
    setupDefaultValues();
}

public ApplicationComponent getApplicationComponent() {
    return ((NEApplication) getApplication()).getApplicationComponent();
}

public abstract void setupDefaultValues();

public void closeCurrentFragmentInBackStack() {
    fragmentManager.popBackStackImmediate();
}

public void showFragment(int containerViewId, BaseFragment fragment, boolean needToRefreshBackStack) {

    if (needToRefreshBackStack && fragmentManager.getBackStackEntryCount() > 0) {
        int indexToDelete = (fragment.getClass().getSimpleName()
                .equals(fragmentManager.getBackStackEntryAt(0).getName())) ? 0 : 1;
        int backStackFragmentsCount = fragmentManager.getBackStackEntryCount();
        for (int i = backStackFragmentsCount - 1; i >= indexToDelete; i--) {
            int backStackId = fragmentManager.getBackStackEntryAt(i).getId();
            fragmentManager.popBackStack(backStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    previousFragment = currentFragment;
    currentFragment = fragment;

    String fragmentTag = fragment.getClass().getSimpleName();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    if (previousFragment != null) {
        fragmentTransaction.hide(previousFragment);
    }
    fragmentTransaction.add(containerViewId, fragment, fragmentTag)
            .addToBackStack(fragmentTag)
            .commit();

}

protected abstract BaseFragment getDefaultFragment();

@Override
protected void onDestroy() {
    uninder.unbind();
    uninder = null;
    super.onDestroy();
}
}

Body:
The condition of popping the fragment itself is written logically in reverse. super.onBackPressed() will pop the fragment if it is present in the backstack.So if the getBackStackEntryCount() is greater than zero you need to call the super method or else finish the activity when there is no fragments in backstack.

if (fragmentManager.getBackStackEntryCount() >=0) {
    getSupportFragmentManager().popBackStackImmediate()
} else {
    super.onBackPressed();
}


来源: stackexchange

问:
Python Selenium: Unable to click on a user name field
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

```<code><div aria-hidden="true" style="cursor:text" data-bind="text: hintText, css: hintCss" class="placeholder">someone@example.com</div>
</code>```

What would be the best way to locate this page object?

Thanks

答:
To click() the User Name field you can use either of the following line of code :

Using class and text attributes :

```<code>driver.findElement(By.xpath("//div[@class='placeholder' and contains(text(),'someone@example.com')]"));
</code>```

Using class and aria-hidden attributes :

```<code>driver.findElement(By.xpath("//div[@class='placeholder' and @aria-hidden='true']"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

someone@example.com

What would be the best way to locate this page object?

Thanks

Body:
To click() the User Name field you can use either of the following line of code :

Using class and text attributes :

driver.findElement(By.xpath("//div[@class='placeholder' and contains(text(),'someone@example.com')]"));

Using class and aria-hidden attributes :

driver.findElement(By.xpath("//div[@class='placeholder' and @aria-hidden='true']"));


问:
Sensenet: Search by Content List fields on Query Builder
I'm trying to make an query on Query builder. This query should search by content using the Content List fields.
In the documentation is indicated that I can use CQL but it seems that in this case is not working.

The query that I'm trying to make is:

```<code>TypeIs:File AND #Location:Lisbon
</code>```

答:
The # char should be url encoded (because the query will be executed by an ajax request through OData). So use it this way:</p>

```<code>TypeIs:File AND %23Location:Lisbon
</code>```

Body:
I'm trying to make an query on Query builder. This query should search by content using the Content List fields.
In the documentation is indicated that I can use CQL but it seems that in this case is not working.

The query that I'm trying to make is:

TypeIs:File AND #Location:Lisbon

Body:
The # char should be url encoded (because the query will be executed by an ajax request through OData). So use it this way:

TypeIs:File AND %23Location:Lisbon


问:
AngularJS multiple expressions concatenating in interpolation with a URL
I know this is long, but please bear with me. The problem is easy to understand, just takes some writing to fully explain it.

Right now I'm getting this error

```<code>Error: [$interpolate:noconcat] Error while interpolating:
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.
See http://docs.angularjs.org/api/ng.$sce
</code>```

I've done all the reading in the documentation, but I still can't find a workaround for my problem.

I'm using $http.get on a private online source that has data that is similar to the form of a json file (so I can't modify the data). The data looks like this:

```<code>...
"items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"N5Eg36Gl054SUNiWWc-Su3t5O-k/A7os41NAa_66TUu-1I-VxH70Rp0\"",
   "id": {
      "kind": "youtube#video",
      "videoID": "MEoSax3BEms"
      },
   },
   {
    "kind": "youtube#searchResult",
    "etag": "\"N5Eg36Gl054SUNiWWc-Su3t5O-k/VsH9AmnQecyYBLJrl1g3dhewrQo\"",
    "id": {
       "kind": "youtube#video",
       "videoID": "oUBqFlRjVXU"
       },
    },
...
</code>```

I'm trying to interpolate the videoId of each item into my HTML iframe that embeds the YouTube video. In my controller.js file, I'm setting the promise object after the $http.get as such

```<code>$http.get('privatesource').success(function(data) {
  $scope.videoList = data.items;
});
</code>```

So now the variable "$scope.videoList" is mapped to data.items, which has a lot of video elements. In my HTML file, I can retrieve the videoID of each video by using

```<code><ul class="videos">
  <li ng-repeat="video in videoList">
    <span>{{video.id.videoID}}</span>
  </li>
</ul>
</code>```

and this lists all the videoID's.
But if I try to concatenate these values to a URL, like https://youtube.com/embed/, it does not work.

```<code><div ng-repeat="video in videoList">
    <iframe id="ytplayer" type="text/html" width="640" height="360"
     ng-src="https://www.youtube.com/embed/{{video.id.videoId}}"
     frameborder="0" allowfullscreen></iframe>
</div>
</code>```

Is there a way that I can get the videoID to be interpolated into the youtube URL? I've tried whitelisting by using the $sceDelegateProvider as follows but it still does not work

```<code>$sceDelegateProvider.resourceUrlWhitelist([
  'self',
  'https://www.youtube.com/**']);
</code>```

Any help is appreciated. Thanks!

答:
My version is angular.min.1.5.8.js
I had the same issue with a form. I resolved it by changing the attribute action=URL by ng-action=URL.

Note: this does not work because ng-action is not a real directive.

Body:
I know this is long, but please bear with me. The problem is easy to understand, just takes some writing to fully explain it.

Right now I'm getting this error

Error: [$interpolate:noconcat] Error while interpolating:
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.
See http://docs.angularjs.org/api/ng.$sce

I've done all the reading in the documentation, but I still can't find a workaround for my problem.

I'm using $http.get on a private online source that has data that is similar to the form of a json file (so I can't modify the data). The data looks like this:

...
"items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"N5Eg36Gl054SUNiWWc-Su3t5O-k/A7os41NAa_66TUu-1I-VxH70Rp0\"",
   "id": {
      "kind": "youtube#video",
      "videoID": "MEoSax3BEms"
      },
   },
   {
    "kind": "youtube#searchResult",
    "etag": "\"N5Eg36Gl054SUNiWWc-Su3t5O-k/VsH9AmnQecyYBLJrl1g3dhewrQo\"",
    "id": {
       "kind": "youtube#video",
       "videoID": "oUBqFlRjVXU"
       },
    },
...

I'm trying to interpolate the videoId of each item into my HTML iframe that embeds the YouTube video. In my controller.js file, I'm setting the promise object after the $http.get as such

$http.get('privatesource').success(function(data) {
  $scope.videoList = data.items;
});

So now the variable "$scope.videoList" is mapped to data.items, which has a lot of video elements. In my HTML file, I can retrieve the videoID of each video by using

    {{video.id.videoID}}

and this lists all the videoID's.
But if I try to concatenate these values to a URL, like https://youtube.com/embed/, it does not work.

Is there a way that I can get the videoID to be interpolated into the youtube URL? I've tried whitelisting by using the $sceDelegateProvider as follows but it still does not work

$sceDelegateProvider.resourceUrlWhitelist([
  'self',
  'https://www.youtube.com/**']);

Any help is appreciated. Thanks!

ContentLicense: CC BY-SA 4.0


问:
Why page number is not enabled correctly in listview and datapager
I am using listview and datapager for display. I use two level of listview, where inner listview item can be 6 types. I use my own datasource. I only need to display 1 inner listviewitem per page. It display each page correctly, but page number is not set right, eg, when 2nd page (other as well) is click, 2nd page number is not disabled while 1st page number is still disabled. Here is the code:</p>

```<code>   <div style="margin: 10px;">
        <asp:ListView ID="rptExercise2" runat="server"
            ItemPlaceholderID="itemPlaceHolder1" OnItemDataBound="ExerciseBound" OnPagePropertiesChanging="ChangeExercise">
            <LayoutTemplate>
                <asp:PlaceHolder ID="itemPlaceHolder1" runat="server" />
            </LayoutTemplate>

            <ItemTemplate>
            <h2><asp:Label ID="lbName" runat="server" /></h2>
            <asp:ListView ID="rptContent2" runat="server" ItemPlaceholderID="itemPlaceHolder2" OnItemDataBound="ContentBound">
                <LayoutTemplate>
                    <asp:PlaceHolder ID="itemPlaceHolder2" runat="server" />
                </LayoutTemplate>

                <ItemTemplate>
                    <div style="padding: 5px;" >
                        <div>
                        <asp:Label ID="lbID" runat="server" Text='<%# Eval("ID") %>' Visible="false" />

                        <asp:Label ID="lbWrapper" runat="server" Text='<%# Eval("Wrapper") %>' Visible="false" />

                        <asp:Label ID="lbAudioQuestion" runat="server" Visible="false" />

                        <div style="text-align: right;"><asp:Label ID="lbAudioAnswer" runat="server" Visible="false" /></div>

                        <div style="text-align: right;"><asp:TextBox ID="tbAnswer" runat="server" TextMode="MultiLine" CssClass="tb" Width="50%" Height="60" Visible="false" /></div>

                        <div style="margin-left: 20px;"><asp:RadioButtonList ID="rblChoice" runat="server" Visible="false" /></div>
                        </div>
                    </div>
                </ItemTemplate>
            </asp:ListView>

            <asp:Panel ID="pnFeedback" runat="server" Visible="false" CssClass="Feedback">
                <div style="margin: 10px;">
                    <div style="float: left;">
                    Score: <br /><asp:TextBox ID="tbScore" runat="server" CssClass="tb" Width="40" /> / <asp:Label ID="lbScore" runat="server" /></div>
                    </div>
                    <asp:Label ID="lbResultID" runat="server" Visible="false" />
                    <div style="float: left;">
                    Feedback<br />
                    <asp:TextBox ID="tbFeedback" runat="server" TextMode="MultiLine" CssClass="tb" Width="200" Height="60" />
                    </div>

                    <div style="float: left;">
                    Recording<br />
                    <asp:Label ID="lbFeedbackAudio" runat="server" />
                    </div>
                    <br style="clear: both;" />
                </div>
            </asp:Panel>

            </ItemTemplate>
            <EmptyItemTemplate>
                <div>
                    Sorry, no exercise is found for this lesson.
                </div>
            </EmptyItemTemplate>

        </asp:ListView>

        <asp:DataPager ID="DataPager" runat="server" PagedControlID="rptExercise2"
            PageSize="1">
            <Fields>
                <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
                <asp:NumericPagerField ButtonCount="10" ButtonType="Button" />
                <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
            </Fields>
        </asp:DataPager>

public partial class MyPracClass : System.Web.UI.Page
{
    // Current page number
    int i = 0;

    protected classLessons les;
    protected classExercises exc;
    protected List<classExercises> exercises;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["LessonID"] == null)
        {
            return;
        }

        classLessons les = new classLessons(Convert.ToInt32(Request["LessonID"]));
        exc = new classExercises();
        exercises = exc.GetExercisesByLessonID(les.ID);

        if (!IsPostBack)
        {
            lbLessonName.Text = les.Name;
            lbDescription.Text = les.Description;
            //SetPageNumber();

            rptExercise2.DataSource = exercises;
            rptExercise2.DataBind();
        }
    }

    protected void ExerciseBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem item = (ListViewDataItem)e.Item;

            Label lbName = (Label)item.FindControl("lbName");
            string excName = "Exercise " + (i+1) + ": " + exercises[i].Subject;
            lbName.Text = excName;

            Label lbFeedbackAudio = (Label)item.FindControl("lbFeedbackAudio");
            classContent ct = new classContent();
            string test = "exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback";
            lbFeedbackAudio.Text = ct.GetPlayingString("exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback");

            ListView rptContent2 = (ListView)item.FindControl("rptContent2");
            Panel pnFeedback = (Panel)item.FindControl("pnFeedback");

            if (exercises[i] != null && rptContent2 != null)
            {
                classContent cct = new classContent();

                rptContent2.DataSource = cct.GetContentByExerciseID(exercises[i].ID);
                rptContent2.DataBind();
            }

            var result = new classResults();

            result.GetResultByExerciseID(Convert.ToInt32(exercises[i].ID));

            if (result.ID > 0)
            {
                pnFeedback.Visible = true;
                Label lbID = (Label)item.FindControl("lbResultID");
                Label lbScore = (Label)item.FindControl("lbScore");
                lbScore.Text = exercises[i].Score.ToString();
                TextBox tbScore = (TextBox)item.FindControl("tbScore");
                TextBox tbFeedback = (TextBox)item.FindControl("tbFeedback");

                lbID.Text = result.ID.ToString();
                tbScore.Text = result.Score.ToString();
                tbFeedback.Text = result.Feedback;
            }
        }
    }

    protected void ChangeExercise(object sender, PagePropertiesChangingEventArgs e)
    {
        // Get current page number
        i = e.StartRowIndex / e.MaximumRows;

        rptExercise2.DataSource = exercises;
        rptExercise2.DataBind();
    }

    //protected void DataPager_PreRender(object sender, EventArgs e)
    //{
    //    // Get current page number
    //    //i = e.StartRowIndex / e.MaximumRows;

    //    rptExercise2.DataSource = exercises;
    //    rptExercise2.DataBind();
    //}

    protected void ContentBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            var qry = (classContent)dataItem.DataItem;

            Label lbAudioQuestion = (Label)e.Item.FindControl("lbAudioQuestion");
            Label lbAudioAnswer = (Label)e.Item.FindControl("lbAudioAnswer");
            Label lbWrapper = (Label)e.Item.FindControl("lbWrapper");
            TextBox tbAnswer = (TextBox)e.Item.FindControl("tbAnswer");
            RadioButtonList rblChoice = (RadioButtonList)e.Item.FindControl("rblChoice");

            switch (qry.Type)
            {
                case classContent.ContentType.AudioQuestion:
                    lbAudioQuestion.Visible = true;
                    lbAudioQuestion.Text = qry.GetPlayingString(qry.Wrapper);
                    break;
                case classContent.ContentType.TextQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.VideoQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.AudioAnswer:
                    lbAudioAnswer.Visible = true;
                    lbAudioAnswer.Text = qry.GetRecordingString("content" + qry.ID + "student" + Session["StudentID"]);
                    break;
                case classContent.ContentType.TextAnswer:
                    tbAnswer.Visible = true;
                    break;
                case classContent.ContentType.ChoiceAnswer:
                    rblChoice.DataSource = qry.GetChoiceOptions(qry.ID);
                    rblChoice.DataTextField = "Value";
                    rblChoice.DataValueField = "IsAnswer";
                    rblChoice.DataBind();
                    rblChoice.Visible = true;
                    break;
                default: break; ;
            }

            classAnswers ans = new classAnswers();

            var contentAnswer = ans.GetAnswerByContentID(qry.ID);

            if (contentAnswer.ID > 0)
            {
                switch (qry.Type)
                {
                    case classContent.ContentType.TextAnswer:
                        tbAnswer.Text = contentAnswer.Answer;
                        break;
                    case classContent.ContentType.ChoiceAnswer:
                        rblChoice.SelectedIndex = Convert.ToInt32(contentAnswer.Answer);
                        break;
                    default: break; ;
                }
            }

        }

    }
</code>```

答:
This article tells you everything you might need about utilizing a DataPager control https://web.archive.org/web/20201202213937/https://www.4guysfromrolla.com/articles/011310-1.aspx (see the last section of the article)

The article clearly explains about applying/modifying individual page numbers in the paging area. So I think you will simply have to write a CSS class to disable the current page number's button/link and enable the remaining page numbers.

Hope this helps...

ContentLicense: CC BY-SA 2.5

Body:
I am using listview and datapager for display. I use two level of listview, where inner listview item can be 6 types. I use my own datasource. I only need to display 1 inner listviewitem per page. It display each page correctly, but page number is not set right, eg, when 2nd page (other as well) is click, 2nd page number is not disabled while 1st page number is still disabled. Here is the code:

        <asp:ListView ID="rptExercise2" runat="server"
            ItemPlaceholderID="itemPlaceHolder1" OnItemDataBound="ExerciseBound" OnPagePropertiesChanging="ChangeExercise">
            <LayoutTemplate>
                <asp:PlaceHolder ID="itemPlaceHolder1" runat="server" />
            </LayoutTemplate>

            <ItemTemplate>

<asp:Label ID="lbName" runat="server" />

            <asp:ListView ID="rptContent2" runat="server" ItemPlaceholderID="itemPlaceHolder2" OnItemDataBound="ContentBound">
                <LayoutTemplate>
                    <asp:PlaceHolder ID="itemPlaceHolder2" runat="server" />
                </LayoutTemplate>

                <ItemTemplate>

                        <asp:Label ID="lbID" runat="server" Text='<%# Eval("ID") %>' Visible="false" />

                        <asp:Label ID="lbWrapper" runat="server" Text='<%# Eval("Wrapper") %>' Visible="false" />

                        <asp:Label ID="lbAudioQuestion" runat="server" Visible="false" />

<asp:Label ID="lbAudioAnswer" runat="server" Visible="false" />

<asp:TextBox ID="tbAnswer" runat="server" TextMode="MultiLine" CssClass="tb" Width="50%" Height="60" Visible="false" />

<asp:RadioButtonList ID="rblChoice" runat="server" Visible="false" />

                </ItemTemplate>
            </asp:ListView>

            <asp:Panel ID="pnFeedback" runat="server" Visible="false" CssClass="Feedback">

                    Score:
<asp:TextBox ID="tbScore" runat="server" CssClass="tb" Width="40" /> / <asp:Label ID="lbScore" runat="server" />

                    <asp:Label ID="lbResultID" runat="server" Visible="false" />

                    Feedback

                    <asp:TextBox ID="tbFeedback" runat="server" TextMode="MultiLine" CssClass="tb" Width="200" Height="60" />

                    Recording

                    <asp:Label ID="lbFeedbackAudio" runat="server" />

            </asp:Panel>

            </ItemTemplate>
            <EmptyItemTemplate>

                    Sorry, no exercise is found for this lesson.

            </EmptyItemTemplate>

        </asp:ListView>

        <asp:DataPager ID="DataPager" runat="server" PagedControlID="rptExercise2"
            PageSize="1">
            <Fields>
                <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
                <asp:NumericPagerField ButtonCount="10" ButtonType="Button" />
                <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
            </Fields>
        </asp:DataPager>

public partial class MyPracClass : System.Web.UI.Page
{
    // Current page number
    int i = 0;

    protected classLessons les;
    protected classExercises exc;
    protected List<classExercises> exercises;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["LessonID"] == null)
        {
            return;
        }

        classLessons les = new classLessons(Convert.ToInt32(Request["LessonID"]));
        exc = new classExercises();
        exercises = exc.GetExercisesByLessonID(les.ID);

        if (!IsPostBack)
        {
            lbLessonName.Text = les.Name;
            lbDescription.Text = les.Description;
            //SetPageNumber();

            rptExercise2.DataSource = exercises;
            rptExercise2.DataBind();
        }
    }

    protected void ExerciseBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem item = (ListViewDataItem)e.Item;

            Label lbName = (Label)item.FindControl("lbName");
            string excName = "Exercise " + (i+1) + ": " + exercises[i].Subject;
            lbName.Text = excName;

            Label lbFeedbackAudio = (Label)item.FindControl("lbFeedbackAudio");
            classContent ct = new classContent();
            string test = "exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback";
            lbFeedbackAudio.Text = ct.GetPlayingString("exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback");

            ListView rptContent2 = (ListView)item.FindControl("rptContent2");
            Panel pnFeedback = (Panel)item.FindControl("pnFeedback");

            if (exercises[i] != null && rptContent2 != null)
            {
                classContent cct = new classContent();

                rptContent2.DataSource = cct.GetContentByExerciseID(exercises[i].ID);
                rptContent2.DataBind();
            }

            var result = new classResults();

            result.GetResultByExerciseID(Convert.ToInt32(exercises[i].ID));

            if (result.ID > 0)
            {
                pnFeedback.Visible = true;
                Label lbID = (Label)item.FindControl("lbResultID");
                Label lbScore = (Label)item.FindControl("lbScore");
                lbScore.Text = exercises[i].Score.ToString();
                TextBox tbScore = (TextBox)item.FindControl("tbScore");
                TextBox tbFeedback = (TextBox)item.FindControl("tbFeedback");

                lbID.Text = result.ID.ToString();
                tbScore.Text = result.Score.ToString();
                tbFeedback.Text = result.Feedback;
            }
        }
    }

    protected void ChangeExercise(object sender, PagePropertiesChangingEventArgs e)
    {
        // Get current page number
        i = e.StartRowIndex / e.MaximumRows;

        rptExercise2.DataSource = exercises;
        rptExercise2.DataBind();
    }

    //protected void DataPager_PreRender(object sender, EventArgs e)
    //{
    //    // Get current page number
    //    //i = e.StartRowIndex / e.MaximumRows;

    //    rptExercise2.DataSource = exercises;
    //    rptExercise2.DataBind();
    //}

    protected void ContentBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            var qry = (classContent)dataItem.DataItem;

            Label lbAudioQuestion = (Label)e.Item.FindControl("lbAudioQuestion");
            Label lbAudioAnswer = (Label)e.Item.FindControl("lbAudioAnswer");
            Label lbWrapper = (Label)e.Item.FindControl("lbWrapper");
            TextBox tbAnswer = (TextBox)e.Item.FindControl("tbAnswer");
            RadioButtonList rblChoice = (RadioButtonList)e.Item.FindControl("rblChoice");

            switch (qry.Type)
            {
                case classContent.ContentType.AudioQuestion:
                    lbAudioQuestion.Visible = true;
                    lbAudioQuestion.Text = qry.GetPlayingString(qry.Wrapper);
                    break;
                case classContent.ContentType.TextQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.VideoQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.AudioAnswer:
                    lbAudioAnswer.Visible = true;
                    lbAudioAnswer.Text = qry.GetRecordingString("content" + qry.ID + "student" + Session["StudentID"]);
                    break;
                case classContent.ContentType.TextAnswer:
                    tbAnswer.Visible = true;
                    break;
                case classContent.ContentType.ChoiceAnswer:
                    rblChoice.DataSource = qry.GetChoiceOptions(qry.ID);
                    rblChoice.DataTextField = "Value";
                    rblChoice.DataValueField = "IsAnswer";
                    rblChoice.DataBind();
                    rblChoice.Visible = true;
                    break;
                default: break; ;
            }

            classAnswers ans = new classAnswers();

            var contentAnswer = ans.GetAnswerByContentID(qry.ID);

            if (contentAnswer.ID > 0)
            {
                switch (qry.Type)
                {
                    case classContent.ContentType.TextAnswer:
                        tbAnswer.Text = contentAnswer.Answer;
                        break;
                    case classContent.ContentType.ChoiceAnswer:
                        rblChoice.SelectedIndex = Convert.ToInt32(contentAnswer.Answer);
                        break;
                    default: break; ;
                }
            }

        }

    }


问:
Angular 2 Get Dynamic FormGroup name
https://angular.io/api/forms/FormGroupName here how get FormGroupName.

How to get/patch/update values if FormGroupName is dynamic?

```<code>    <div class="row" *ngFor="let itemrow of searchForm.controls.addresses.controls; let ind=index" [formGroupName]="ind">
   <input class="form-control" formControlName="name">
   <input class="form-control" formControlName="time">
</div>
</code>```

searchForm.value object:

```<code>"addresses": [
    {
      "address": "",
      "name": 0,
      "time": 0,
 },
    {
      "address": "",
      "name": 0,
      "time": 0,
    }
  ]
</code>```

How to update inputs value inside currentGFormGroupName ?

答:
You could create new form group in code

Component

```<code>export class AppComponent {
  addresses = [
    {
      address: 'aa',
      name: 'aa',
      time: 'aa'
    },
    {
      address: 'bb',
      name: 'bb',
      time: 'bb'
    }
  ];

  formGroup: FormGroup;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = new FormGroup({});
    let addressGroup = new FormGroup({});

    this.addresses.map((group, index) => {
      const name = 'group-' + index.toString();
      const formGroup = this.fb.group({
        address: [group.address],
        name: [group.name],
        time: [group.time]
      });
      addressGroup.addControl(name, formGroup);
    })

    this.formGroup.addControl('addresses', addressGroup);
  }

}
</code>```

Template

```<code><form [formGroup]="formGroup">
  <div formGroupName="addresses">
    <div *ngFor="let address of addresses; let i = index">
      <div formGroupName="{{'group-'+i}}">
        <input type="text" formControlName="address"/>
        <input type="text" formControlName="name"/>
        <input type="text" formControlName="time"/>
      </div>
    </div>
  </div>
</form>
</code>```

Title: Angular 2 Get Dynamic FormGroup name

Body:
https://angular.io/api/forms/FormGroupName here how get FormGroupName.

How to get/patch/update values if FormGroupName is dynamic?

   <input class="form-control" formControlName="name">
   <input class="form-control" formControlName="time">

searchForm.value object:

"addresses": [
    {
      "address": "",
      "name": 0,
      "time": 0,
 },
    {
      "address": "",
      "name": 0,
      "time": 0,
    }
  ]

How to update inputs value inside currentGFormGroupName ?

Body:
You could create new form group in code

Component

export class AppComponent {
  addresses = [
    {
      address: 'aa',
      name: 'aa',
      time: 'aa'
    },
    {
      address: 'bb',
      name: 'bb',
      time: 'bb'
    }
  ];

  formGroup: FormGroup;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = new FormGroup({});
    let addressGroup = new FormGroup({});

    this.addresses.map((group, index) => {
      const name = 'group-' + index.toString();
      const formGroup = this.fb.group({
        address: [group.address],
        name: [group.name],
        time: [group.time]
      });
      addressGroup.addControl(name, formGroup);
    })

    this.formGroup.addControl('addresses', addressGroup);
  }

}

Template

<form [formGroup]="formGroup">
  <div formGroupName="addresses">
    <div *ngFor="let address of addresses; let i = index">
      <div formGroupName="{{'group-'+i}}">
        <input type="text" formControlName="address"/>
        <input type="text" formControlName="name"/>
        <input type="text" formControlName="time"/>
      </div>
    </div>
  </div>
</form>


问:
Button inside jQuery Datatables which calls PHP script?
I implemented a table using DataTables.

This is the code:

```<code>$( document ).ready(function() {
    var table = $('#tbl_user').DataTable( {
        "ajax": "data_user.php",
        "bPaginate":true,
        "bProcessing": true,
        "pageLength": 10,
        "columns": [
            { mData: 'name' } ,
            { mData: 'address' },
            { mData: 'city' },
            { mData: 'postalcode' },
            { mData: 'email' },
            { mData: 'supervisor' },
            {
                mData: null,
                "bSortable": false,
               "mRender": function(data, type, full) {
                return '<a class="btn btn-info btn-sm" href=update.php?' + 'name=foo' + '>' + 'Edit' + '</a>'; }
            }

        ],
        "dom": 'Bfrtip',
        "buttons": [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });

});
</code>```

There's one issue, though. Let's say I'm going to click the "Edit" button on user "123". The button is supposed to call a PHP script update.php, with "123" as it's parameter. How to do that? I tried:

```<code>return '<a class="btn btn-info btn-sm" href=update.php?' + 'name='+mData:name + '>' + 'Edit' + '</a>'; }
</code>```

Well it doesn't work.

答:
You are very close to what you want to achieve.

Mind you, there are two ways

Via Ajax

Use javascript to open a new page update.php with the param.

It all depends on which one is applicable, the two options follow the same principle.
But, in this example, am gonna stick with option 2. Let me know if you want option 1 too.

Update this section as shown:

```<code>return '<a class="btn btn-info btn-sm" onclick="'+callScript(123)+'">' + 'Edit' + '</a>'; }
</code>```

Then add a function to handle this onclick event

```<code> function callScript(id){

   var  url ="update.php?id="+id;
    window.open(url,"_self")

    }
</code>```

Body:
I implemented a table using DataTables.

This is the code:

$( document ).ready(function() {
    var table = $('#tbl_user').DataTable( {
        "ajax": "data_user.php",
        "bPaginate":true,
        "bProcessing": true,
        "pageLength": 10,
        "columns": [
            { mData: 'name' } ,
            { mData: 'address' },
            { mData: 'city' },
            { mData: 'postalcode' },
            { mData: 'email' },
            { mData: 'supervisor' },
            {
                mData: null,
                "bSortable": false,
               "mRender": function(data, type, full) {
                return '' + 'Edit' + ''; }
            }

        ],
        "dom": 'Bfrtip',
        "buttons": [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });

});

There's one issue, though. Let's say I'm going to click the "Edit" button on user "123". The button is supposed to call a PHP script update.php, with "123" as it's parameter. How to do that? I tried:

return '' + 'Edit' + ''; }

Well it doesn't work.

Body:
You are very close to what you want to achieve.

Mind you, there are two ways

Via Ajax

Use javascript to open a new page update.php with the param.

It all depends on which one is applicable, the two options follow the same principle.
But, in this example, am gonna stick with option 2. Let me know if you want option 1 too.

Update this section as shown:

return '<a class="btn btn-info btn-sm" onclick="'+callScript(123)+'">' + 'Edit' + '</a>'; }

Then add a function to handle this onclick event

 function callScript(id){

   var  url ="update.php?id="+id;
    window.open(url,"_self")

    }


问:
Jupyter asks an unknown password
I recently installed Anaconda (2.7) distribution on a linux box. As you may know, it includes Jupyter notebook server.

My problem is that Jupyter requires a password I don't know. Observe what happens:

```<code>$ jupyter notebook
[W 04:12:51.684 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 04:12:51.702 NotebookApp] JupyterLab alpha preview extension loaded from /home/poko/Software/anaconda2/lib/python2.7/site-packages/jupyterlab
JupyterLab v0.27.0
Known labextensions:
[I 04:12:51.703 NotebookApp] Running the core application with no additional extensions or settings
[I 04:12:51.705 NotebookApp] Serving notebooks from local directory: /home/poko/courses/deeplearning1/nbs
[I 04:12:51.705 NotebookApp] 0 active kernels
[I 04:12:51.705 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/
[I 04:12:51.705 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
</code>```

My browser (either from localhost or across the internet, displays:

It should be noted that:

a) The server listens on all IP, while it should listen just on localhost by default.

b) The auto-generated config file in $HOME/.jupyter is all commented.

Footnote: This is not related to the well-known (but poorly documented) token authentication issue. Indeed, if I call a list, no token is shown:

```<code>poko@W530 ~ $ jupyter notebook list
Currently running servers:
http://localhost:8888/ :: /home/poko
</code>```

答:
Try setting a default password with the command

jupyter notebook password

And then start your notebook with jupyter notebook and enter the same password in the browser.

Probably you had set a default password in the past, that is why it stops generating token and prefers the password.

Title: Jupyter asks an unknown password

Body:
I recently installed Anaconda (2.7) distribution on a linux box. As you may know, it includes Jupyter notebook server.

My problem is that Jupyter requires a password I don't know. Observe what happens:

$ jupyter notebook
[W 04:12:51.684 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 04:12:51.702 NotebookApp] JupyterLab alpha preview extension loaded from /home/poko/Software/anaconda2/lib/python2.7/site-packages/jupyterlab
JupyterLab v0.27.0
Known labextensions:
[I 04:12:51.703 NotebookApp] Running the core application with no additional extensions or settings
[I 04:12:51.705 NotebookApp] Serving notebooks from local directory: /home/poko/courses/deeplearning1/nbs
[I 04:12:51.705 NotebookApp] 0 active kernels
[I 04:12:51.705 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/
[I 04:12:51.705 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

My browser (either from localhost or across the internet, displays:

It should be noted that:

a) The server listens on all IP, while it should listen just on localhost by default.

b) The auto-generated config file in $HOME/.jupyter is all commented.

Footnote: This is not related to the well-known (but poorly documented) token authentication issue. Indeed, if I call a list, no token is shown:

poko@W530 ~ $ jupyter notebook list
Currently running servers:
http://localhost:8888/ :: /home/poko


问:
How can I reset cocos2d game state?
I am not entirely sure how to properly phrase this question so I'll explain what happens. I have a cocos2d game, and after I exit the game and start it again, it starts at the exact same point. Its as if it is "saving."

Is there any way to prevent this?

Thanks

答:
This is how you could reset your game upon resume:

In your application's delegate:

```<code>- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (!_appIsPaused) {
        NSLog(@"app Became Active");
        ....set a state variable here....
    }
}
</code>```

Then in your application's tick method(a method that is ran every frame) check the value of the state variable in your delegate and run a reset method to reset your application to the beginning.  Alternatively, upon resume you could pop an alert (which would pause the app) and ask the player if they want to start from the beginning or resume where they left off.

Title: How can I reset cocos2d game state?

Body:
This is how you could reset your game upon resume:

In your application's delegate:

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (!_appIsPaused) {
        NSLog(@"app Became Active");
        ....set a state variable here....
    }
}

Then in your application's tick method(a method that is ran every frame) check the value of the state variable in your delegate and run a reset method to reset your application to the beginning.  Alternatively, upon resume you could pop an alert (which would pause the app) and ask the player if they want to start from the beginning or resume where they left off.


问:
Handling and optimizing a range slider in R
If you run the script below, You get a data table representing iris data and a range slider which gives you values greater than and equal to the chosen point on the prior circle of your selection in the slider. I want a logic such that when left slider node is kept at say 5 and right slider at 7, I want the data to be displayed "= and above 5" and "< and equal to 7".These values however should be dynamic. Also for the two circles on the sliders, is there a way to give triangle widgets which are small in size. Attaching the snapshot for reference. Thanks and please help.

```<code>#App
library(shiny)
library(shinydashboard)
library(dplyr)
library(scales)
library(DT)

#Declaring the UI
ui <- fluidPage(
titlePanel("Slider Test"),
fluidRow(
column(4,
         sliderInput("range", "Select the Name Similarity %",
                     min = 4, max = 8,
                     value = c(min,max) ))

),

# Create a new row for the table.
fluidRow(
DT::dataTableOutput("table")
)
)
#Declaring the Server
server <- function(input, output) {
output$table <- DT::renderDataTable(DT::datatable({
Prod_total1      <-  subset(iris, as.numeric(sub("%", "",
iris$Sepal.Length)) >= input$range)
  Prod_total1
}))
}
shinyApp(ui, server)
</code>```

答:
in order to access sliderInput values in the range mode please use input$range[1] to access the first extreme and input$range[2] to access the second

```<code>#App
library(shiny)
library(shinydashboard)
library(dplyr)
library(scales)
library(DT)

#Declaring the UI
ui <- fluidPage(
  titlePanel("Slider Test"),
  fluidRow(
    column(4,
           sliderInput("range", "Select the Name Similarity %",
                       min = 4, max = 8,
                       value = c(min,max) ))

  ),

  # Create a new row for the table.
  fluidRow(
    DT::dataTableOutput("table")
  )
)

#Declaring the Server
server <- function(input, output) {
  output$table <- DT::renderDataTable(DT::datatable({
    iris[iris$Sepal.Length >= input$range[1] & iris$Sepal.Length <= input$range[2],]
  }))
}
shinyApp(ui, server)
</code>```

Body:
If you run the script below, You get a data table representing iris data and a range slider which gives you values greater than and equal to the chosen point on the prior circle of your selection in the slider. I want a logic such that when left slider node is kept at say 5 and right slider at 7, I want the data to be displayed "= and above 5" and "< and equal to 7".These values however should be dynamic. Also for the two circles on the sliders, is there a way to give triangle widgets which are small in size. Attaching the snapshot for reference. Thanks and please help.

#App
library(shiny)
library(shinydashboard)
library(dplyr)
library(scales)
library(DT)

#Declaring the UI
ui <- fluidPage(
titlePanel("Slider Test"),
fluidRow(
column(4,
         sliderInput("range", "Select the Name Similarity %",
                     min = 4, max = 8,
                     value = c(min,max) ))

),

# Create a new row for the table.
fluidRow(
DT::dataTableOutput("table")
)
)
#Declaring the Server
server <- function(input, output) {
output$table <- DT::renderDataTable(DT::datatable({
Prod_total1      <-  subset(iris, as.numeric(sub("%", "",
iris$Sepal.Length)) >= input$range)
  Prod_total1
}))
}
shinyApp(ui, server)

Body:
in order to access sliderInput values in the range mode please use input$range[1] to access the first extreme and input$range[2] to access the second

#App
library(shiny)
library(shinydashboard)
library(dplyr)
library(scales)
library(DT)

#Declaring the UI
ui <- fluidPage(
  titlePanel("Slider Test"),
  fluidRow(
    column(4,
           sliderInput("range", "Select the Name Similarity %",
                       min = 4, max = 8,
                       value = c(min,max) ))

  ),

  # Create a new row for the table.
  fluidRow(
    DT::dataTableOutput("table")
  )
)

#Declaring the Server
server <- function(input, output) {
  output$table <- DT::renderDataTable(DT::datatable({
    iris[iris$Sepal.Length >= input$range[1] & iris$Sepal.Length <= input$range[2],]
  }))
}
shinyApp(ui, server)


问:
Russian characters on svg text tag not showing correctly
I have on the site Svg and there will be Russian texts
but the text is displayed incorrectly when I open the browser.

this is my code

```<code><g>
  <rect id="XMLID_2_" x="409.1" y="102.3" transform="matrix(0.7071 -0.7071 0.7071 0.7071 25.8097 371.5413)" class="cubes hex-init" data-title="backend" data-content="backend-desc" data-color="#333333" width="104.6" height="104.6"/>
  <image style="overflow:visible;" width="256" height="256" id="XMLID_18_" xlink:href="assets/img/time.png"  transform="matrix(0.1826 0 0 0.1826 440 110.7045)"></image>
  <text id="XMLID_22_" transform="matrix(1 0 0 1 425.0002 174.6665)" class="st1 st2">Собственный график</text>
</g>
</code>```

And the rusult is

```<code>РЎРѕР±СЃС‚РІРµРЅРЅС‹Р№ РіСЂР°С„РёРє
</code>```

答:
You can add meta charset in your html head</p>

```<code> <meta charset="UTF-8">
</code>```

Body:
I have on the site Svg and there will be Russian texts
but the text is displayed incorrectly when I open the browser.

this is my code

<g>
  <rect id="XMLID_2_" x="409.1" y="102.3" transform="matrix(0.7071 -0.7071 0.7071 0.7071 25.8097 371.5413)" class="cubes hex-init" data-title="backend" data-content="backend-desc" data-color="#333333" width="104.6" height="104.6"/>
  <image style="overflow:visible;" width="256" height="256" id="XMLID_18_" xlink:href="assets/img/time.png"  transform="matrix(0.1826 0 0 0.1826 440 110.7045)"></image>
  <text id="XMLID_22_" transform="matrix(1 0 0 1 425.0002 174.6665)" class="st1 st2">Собственный график</text>
</g>

And the rusult is

РЎРѕР±СЃС‚РІРµРЅРЅС‹Р№ РіСЂР°С„РёРє

Body:
You can add meta charset in your html head

 <meta charset="UTF-8">


问:
count and groupby together in one query
The following query is fetching some product info on a page which is fine, but I also want to show the number of the product that it occurs as a text, however, I used groupby but I also want to use count on pro_id.

```<code> "SELECT * FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
    pro_id  "
</code>```

答:
Use this query:</p>

```<code>"SELECT pro_id,count(pro_id) FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY pro_id  "
</code>```

Title: count and groupby together in one query

Body:
The following query is fetching some product info on a page which is fine, but I also want to show the number of the product that it occurs as a text, however, I used groupby but I also want to use count on pro_id.

 "SELECT * FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
    pro_id  "

Body:
Use this query:

"SELECT pro_id,count(pro_id) FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY pro_id  "


问:
Ajax function working on local but not online
Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.

Here is my code :

Here the page where I call the function showEspece() :

echo "
";
     echo "
\n";
            echo "
\n";
                echo " Nom 	\n";
                echo " Nombre 	\n";
            echo "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          echo "
\n";
           foreach ($row as $item) {
               echo "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           } ?>
                        <td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" >	 <?php
          echo "
\n";
      }
     echo "
\n\n";
    echo '
';```
</div>
</div>
</p>

<p>Here is the Ajax function :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert('ok');
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr);
      }
    });
  }</code>```

Here is the page call by the Ajax function :

<?php
     include("/includes/connexionBD.php");
         include("includes/entetepage.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

 oci_execute($requete);

     $table = "
\n";
            $table .= "
\n";
                $table .= " Nom 	\n";
                $table .= " Sexe 	\n";
                $table .= " Date naissance 	\n";
            $table .= "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          $table .= "
\n";
           foreach ($row as $item) {
               $table .= "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           }
          $table .= "
\n";
      }
     $table .= "
\n\n";

     echo json_encode($table);
?>```
</div>
</div>
</p>

<p>And that is what error I get on the consol :</p>

```VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)
```

Does someone know where the problem can come from and can help me ?

Sorry fo my bad english :/

答:
Change php response code with the following,

```<code><?php
 include("/includes/connexionBD.php");
     include("includes/entetepage.php");

$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

oci_execute($requete);

    $table = "<table>\n";
        $table .= "<thead>\n";
            $table .= "<td><b> Nom </b></td>\n";
            $table .= "<td><b> Sexe </b></td>\n";
            $table .= "<td><b> Date naissance </b></td>\n";
        $table .= "</thead>\n";
        while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
            $table .= "<tr>\n";
                foreach ($row as $item) {
                    $table .= "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
                }
            $table .= "</tr>\n";
        }
    $table .= "</table>\n\n";

    echo json_encode(array("table"=>$table, JSON_UNESCAPED_SLASHES));
?>
</code>```

change ajax code with the following

```<code>function showEspece(espece, categorie, object)
{
    $.ajax({
        type : 'POST',
        url: 'getespece.php',
        data: {espece: espece, categorie: categorie },
        dataType: 'json',
        success: function(data)
        {
            alert('ok');
            var tbl = $.parseJSON(data);
            var tableau = tbl.table;
            console.log(tableau);
            $('#output').html(tableau);
        },
        error: function(xhr, status, error) {
            console.log(xhr);
        }
   });
}
</code>```

Body:
Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.

Here is my code :

Here the page where I call the function showEspece() :

echo "
";
     echo "
\n";
            echo "
\n";
                echo " Nom 	\n";
                echo " Nombre 	\n";
            echo "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          echo "
\n";
           foreach ($row as $item) {
               echo "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           } ?>
                        <td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" >	 <?php
          echo "
\n";
      }
     echo "
\n\n";
    echo '
';

Here is the Ajax function :

function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert('ok');
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr);
      }
    });
  }

Here is the page call by the Ajax function :

<?php
     include("/includes/connexionBD.php");
         include("includes/entetepage.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

 oci_execute($requete);

     $table = "
\n";
            $table .= "
\n";
                $table .= " Nom 	\n";
                $table .= " Sexe 	\n";
                $table .= " Date naissance 	\n";
            $table .= "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          $table .= "
\n";
           foreach ($row as $item) {
               $table .= "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           }
          $table .= "
\n";
      }
     $table .= "
\n\n";

     echo json_encode($table);
?>

And that is what error I get on the consol :

VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)

Does someone know where the problem can come from and can help me ?

Sorry fo my bad english :/

Body:
Change php response code with the following,

<?php
 include("/includes/connexionBD.php");
     include("includes/entetepage.php");

$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

oci_execute($requete);

    $table = "<table>\n";
        $table .= "<thead>\n";
            $table .= "<td><b> Nom </b></td>\n";
            $table .= "<td><b> Sexe </b></td>\n";
            $table .= "<td><b> Date naissance </b></td>\n";
        $table .= "</thead>\n";
        while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
            $table .= "<tr>\n";
                foreach ($row as $item) {
                    $table .= "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
                }
            $table .= "</tr>\n";
        }
    $table .= "</table>\n\n";

    echo json_encode(array("table"=>$table, JSON_UNESCAPED_SLASHES));
?>

change ajax code with the following

function showEspece(espece, categorie, object)
{
    $.ajax({
        type : 'POST',
        url: 'getespece.php',
        data: {espece: espece, categorie: categorie },
        dataType: 'json',
        success: function(data)
        {
            alert('ok');
            var tbl = $.parseJSON(data);
            var tableau = tbl.table;
            console.log(tableau);
            $('#output').html(tableau);
        },
        error: function(xhr, status, error) {
            console.log(xhr);
        }
   });
}


问:
Create UITextFieldDelegate to Limit Character Count in Swift
I am new to delegates and I am trying to experiment with the UITextFieldDelegate. My goal is to limit the character count within this text field to five characters, as if I were creating a zip code text field.

I am using an off the shelf view controller with a text field and I created a delegate file titled ZipCodeDelegate.swift. I have modified the text field in the storyboard to display the number keypad when the user taps the field. Here is my viewController:

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

// MARK: Outlets

@IBOutlet weak var zipTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

And here is my delegate file:

```<code>import Foundation
import UIKit

class ZipCodeDelegate: NSObject, UITextFieldDelegate {

}
</code>```

I am at a loss for what to do next. I am unsure how to limit the character count of the textfield, as well as telling the view controller that this delegate file exists and that it should control said text field.

答:
Use this UITextField delegate for Zipcode and Int Limit Character count

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if string.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) == nil{
        let len = (textField.text?.characters.count)! + string.characters.count
        if len <= 5 {
            return true
        }
    }
    return false
}
</code>```

UITextField delegate method for check the max character limit.

```<code>public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    var oldlength : Int = 0
    if textField.text != nil
    {
        oldlength = (textField.text?.count)!
    }

    let replaceMentLength : Int = string.count
    let rangeLength : Int = range.length

    let newLength : Int = oldlength - rangeLength + replaceMentLength

    return newLength <= charaterLimit || false
}
</code>```

Body:
I am new to delegates and I am trying to experiment with the UITextFieldDelegate. My goal is to limit the character count within this text field to five characters, as if I were creating a zip code text field.

I am using an off the shelf view controller with a text field and I created a delegate file titled ZipCodeDelegate.swift. I have modified the text field in the storyboard to display the number keypad when the user taps the field. Here is my viewController:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

// MARK: Outlets

@IBOutlet weak var zipTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

And here is my delegate file:

import Foundation
import UIKit

class ZipCodeDelegate: NSObject, UITextFieldDelegate {

}

I am at a loss for what to do next. I am unsure how to limit the character count of the textfield, as well as telling the view controller that this delegate file exists and that it should control said text field.

Body:
Use this UITextField delegate for Zipcode and Int Limit Character count

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if string.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) == nil{
        let len = (textField.text?.characters.count)! + string.characters.count
        if len <= 5 {
            return true
        }
    }
    return false
}

UITextField delegate method for check the max character limit.

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    var oldlength : Int = 0
    if textField.text != nil
    {
        oldlength = (textField.text?.count)!
    }

    let replaceMentLength : Int = string.count
    let rangeLength : Int = range.length

    let newLength : Int = oldlength - rangeLength + replaceMentLength

    return newLength <= charaterLimit || false
}


问:
Scala how to handle the exception when the key value pair is not available in properties file using scala
I have the following values in my properties file named message.properties

```<code>gender.type.m=Male
</code>```

i am trying to get the values in my code as below,

```<code>val Prop = ConfigFactory.load("message.properties")

val value=Prop .getString("gender.type.m")

val value=Prop .getString("gender.type.f")
</code>```

since the value is defined for male in my prop file i am able to get the correct value as male when i pass to my getstring("gender.type.m").

however when i am trying to get the value for female i am getting an exception since the value is not defined for female in my properties file.

could some one help me to handle this exception in scala.

答:
you should wrap the property reading in a scala.util.Try:

```<code>val Prop = ConfigFactory.load("message.properties")

val value= Try(Prop.getString("gender.type.m"))

val value= Try(Prop.getString("gender.type.f"))
</code>```

Now you can deal with the failure case in several ways, depending on how familiar you are with Scala.

If you have default values, you can do something like

```<code>val Prop = ConfigFactory.load("message.properties")

val value= Try(Prop.getString("gender.type.m")).getOrElse(<defaultValue>)

val value= Try(Prop.getString("gender.type.f")).getOrElse(<defaultValue>)
</code>```

Ideally, you should do something more interesting in case of failure; at least you should log the error probably.

You can also simply fail if there's no such property. If you are familiar with for comprehensions this is a way to do it:

```<code>val Prop = ConfigFactory.load("message.properties")

for {
 male <- Try(Prop.getString("gender.type.m"))
 female <- Try(Prop.getString("gender.type.f"))
} yield {
  // do something with male and female values
  // if any of them does not exist, then this block won't be executed, and the for comprehension will return a scala.util.Failure

}
</code>```

Body:
I have the following values in my properties file named message.properties

gender.type.m=Male

i am trying to get the values in my code as below,

val Prop = ConfigFactory.load("message.properties")

val value=Prop .getString("gender.type.m")

val value=Prop .getString("gender.type.f")

since the value is defined for male in my prop file i am able to get the correct value as male when i pass to my getstring("gender.type.m").

however when i am trying to get the value for female i am getting an exception since the value is not defined for female in my properties file.

could some one help me to handle this exception in scala.

Body:
you should wrap the property reading in a scala.util.Try:

val Prop = ConfigFactory.load("message.properties")

val value= Try(Prop.getString("gender.type.m"))

val value= Try(Prop.getString("gender.type.f"))

Now you can deal with the failure case in several ways, depending on how familiar you are with Scala.

If you have default values, you can do something like

val Prop = ConfigFactory.load("message.properties")

val value= Try(Prop.getString("gender.type.m")).getOrElse(<defaultValue>)

val value= Try(Prop.getString("gender.type.f")).getOrElse(<defaultValue>)

Ideally, you should do something more interesting in case of failure; at least you should log the error probably.

You can also simply fail if there's no such property. If you are familiar with for comprehensions this is a way to do it:

val Prop = ConfigFactory.load("message.properties")

for {
 male <- Try(Prop.getString("gender.type.m"))
 female <- Try(Prop.getString("gender.type.f"))
} yield {
  // do something with male and female values
  // if any of them does not exist, then this block won't be executed, and the for comprehension will return a scala.util.Failure

}


问:
Kohana Query Builder support for DATEDIFF?
According to this: http://docs.kohanaphp.com/libraries/database/builder#limitations Kohana doesn't support parentheses in database queries. How can I get around this to add this to my query:</p>

```<code>WHERE DATEDIFF(`date`, $today) = 0
</code>```

答:
You can use DB::expr or use double quotes:

```<code>$query->where('DATEDIFF("date", '.$today.')", '=', 0);
</code>```

Note that $today must be validated or escaped before using it!

Body:
According to this: http://docs.kohanaphp.com/libraries/database/builder#limitations Kohana doesn't support parentheses in database queries. How can I get around this to add this to my query:

WHERE DATEDIFF(`date`, $today) = 0

Body:
You can use DB::expr or use double quotes:

$query->where('DATEDIFF("date", '.$today.')", '=', 0);

Note that $today must be validated or escaped before using it!


问:
Make a prediction on csv file, one line at a time
I have a large csv file that i need to take a row of data, one at a time, and score it against a model. I have tried the code below but get an error of "X has 120839 features per sample; expecting 30". I can run the model against the entire dataset and it makes predictions on each row. But i need to do it one line at a time, thank you.

```<code>loaded_model = joblib.load('LR_model.sav')
with open(r'fordTestA.csv', "r") as f:

for line in f:
    line = f.readlines()[1:]  ##minus headers
    result = loaded_model.predict(line)
</code>```

In this scenario, it doesnt seem to split the lines as there is \n after each row. I tried to add

```<code>line = line.rstrip('\n')
</code>```

This gives an error : " 'list' object has no attribute 'rstrip'". Thanks in advance for any feedback.

答:
I'm not familiar with joblib or predict(), but:

```<code>import csv

# other code

with open(r'fordTestA.csv', 'r', newline='') as f:
    rows = csv.reader(f, delimiter=',')
    _ = next(rows) # skip headers
    for row in rows:
        line = list(map(float, row)) # convert row of str to row of float
        results = loaded_model.predict(line)
        # or if you need a ',' delimited string
        line = ','.join(row)
        results = loaded_model.predict(row)
</code>```

Body:
I have a large csv file that i need to take a row of data, one at a time, and score it against a model. I have tried the code below but get an error of "X has 120839 features per sample; expecting 30". I can run the model against the entire dataset and it makes predictions on each row. But i need to do it one line at a time, thank you.

loaded_model = joblib.load('LR_model.sav')
with open(r'fordTestA.csv', "r") as f:

for line in f:
    line = f.readlines()[1:]  ##minus headers
    result = loaded_model.predict(line)

In this scenario, it doesnt seem to split the lines as there is \n after each row. I tried to add

line = line.rstrip('\n')

This gives an error : " 'list' object has no attribute 'rstrip'". Thanks in advance for any feedback.

Body:
I'm not familiar with joblib or predict(), but:

import csv

# other code

with open(r'fordTestA.csv', 'r', newline='') as f:
    rows = csv.reader(f, delimiter=',')
    _ = next(rows) # skip headers
    for row in rows:
        line = list(map(float, row)) # convert row of str to row of float
        results = loaded_model.predict(line)
        # or if you need a ',' delimited string
        line = ','.join(row)
        results = loaded_model.predict(row)


问:
How to customize template metadata.annotations.tags
I've a very simple question: Is it possible to create some custom metadata.annotations.tags within openshift template (in order that they don't fall into the default "Uncategorized" if none is matching what you want) ? If yes how ?

Thank you in advance.

答:
You can't create a new category unless you configure the web console as an admin for the whole cluster, but you can use an existing category. For example:

```<code>        "kind": "Template",
        "apiVersion": "v1",
        "metadata": {
            "name": "notebook-builder",
            "annotations": {
                "openshift.io/display-name": "Jupyter Notebook Builder",
                "description": "Template for creating customised Jupyter Notebook images.",
                "iconClass": "icon-python",
                "tags": "python,jupyter"
            }
        },
</code>```

Here the python tag results in it being added in the Python category.

See tag description for example in:

https://docs.openshift.org/latest/dev_guide/templates.html#writing-description

Body:
You can't create a new category unless you configure the web console as an admin for the whole cluster, but you can use an existing category. For example:

        "kind": "Template",
        "apiVersion": "v1",
        "metadata": {
            "name": "notebook-builder",
            "annotations": {
                "openshift.io/display-name": "Jupyter Notebook Builder",
                "description": "Template for creating customised Jupyter Notebook images.",
                "iconClass": "icon-python",
                "tags": "python,jupyter"
            }
        },

Here the python tag results in it being added in the Python category.

See tag description for example in:

https://docs.openshift.org/latest/dev_guide/templates.html#writing-description


问:
'git push heroku master' is still asking for authentication
I have executed:

```<code>$ heroku login
</code>```

But when I try to push, I'm still asked for authentication:

```<code>$ git push heroku master
Username for 'https://git.heroku.com': <email>
Password for 'https://<email>@git.heroku.com':
</code>```

Then I get a WARNING: Do not authenticate with username and password using Git.

I ran heroku login again and authenticated successfully but I still get the same failure.

I've checked the remote:

```<code>$ git remote -v
heroku https://git@heroku.com/appname.git (fetch)
heroku https://git@heroku.com/appname.git (push)
</code>```

I've also generated a new public key, passed it to Heroku, and validated it: https://devcenter.heroku.com/articles/keys

I am on Windows 8, with Git 1.9.5.

答:
You have probably logged into heroku in two terminals, and if you try to run a command on first terminal, it will report such error, as new authentication was made in the second terminal.

Either login again with heroku login and run commands in that terminal, or run commands in that second window (if you have it still open).

Body:
I have executed:

$ heroku login

But when I try to push, I'm still asked for authentication:

$ git push heroku master
Username for 'https://git.heroku.com': <email>
Password for 'https://<email>@git.heroku.com':

Then I get a WARNING: Do not authenticate with username and password using Git.

I ran heroku login again and authenticated successfully but I still get the same failure.

I've checked the remote:

$ git remote -v
heroku https://git@heroku.com/appname.git (fetch)
heroku https://git@heroku.com/appname.git (push)

I've also generated a new public key, passed it to Heroku, and validated it: https://devcenter.heroku.com/articles/keys

I am on Windows 8, with Git 1.9.5.


问:
How can I schedule a particular file to store on EBS volume in AWS?
I wonder if it is possible to store only a particular zipped file from my EC2 Instance to an EBS Volume? I know that there is an option to schedule a snapshot for EC2 Instance but I only need to backup one file every 30 minutes. The file is automatically generated on a location, I just need to watch it and copy on an EBS volume as soon as it is created.</p>

答:
What you could do, is mount an ebs volume on a specific folder and then use that folder to save the zip you want snapshotted.
Then you can schedule the ebs volume to be snapshotted periodically</p>


问:
Can't save user to mongodb in Spring 5 WebFlux
I try to save User to Mongo database in reactive style with Spring WebFlux, but data isn't saved, so I have Java 8, Spring 5 and mongodb.

This is my config:

My entity:

```<code>@Document
public class User {
    @Id
    private String id;
    private String username;
    private String password;
}
</code>```

My repository:

```<code>public interface UserRepository extends ReactiveMongoRepository<User, String> {
}
</code>```

My web config:

```<code>@Configuration
@EnableWebFlux
public class WebConfig {

    @Autowired
    private UserRepository userRepository;

    @Bean
    public RouterFunction userRoutes() {
        return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                        request -> {
                            Mono<User> user = request.bodyToMono(User.class);
                            Mono<User> userMono = user.doOnNext(userRepository::save)
                            return ServerResponse.().body(userMono, User.class);
                        });
    }
}
</code>```

May be I have to manual execute subscribe after save to repository, but I havn't found such info in spring reference?

UPD:
But if I extract from request User and pass it to userRepository and return result I have got a successful result to save data to mongo. But I am not sure that it is a good approach:

```<code>@Bean
public RouterFunction userRoutes() {
    return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                    request -> {
                        User user = request.bodyToMono(User.class).block();
                        Mono<User> userMono = userRepository.save(user);
                        return ServerResponse.ok().body(userMono, User.class);
                    });
}
</code>```

答:
I have changed doOnNext to flatMap and it works, so it seems to me this is due to the fact that "Transform the item emitted by this Mono asynchronously, returning the value emitted by another Mono" and doOnNext - "Add behavior triggered when the Mono emits a data successfully" and userRepository.save(...) method return Mono that doOnNext add behavious to old Mono and return it(I am loosing response from save method) and flatMap return new Mono which got from save method:</p>

```<code>@Bean
public RouterFunction userRoutes() {
    return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                    request -> {
                        Mono<User> user = request.bodyToMono(User.class);
                            Mono<User> userMono = user.flatMap(userRepository::save);
                            return ServerResponse.status(HttpStatus.CREATED).body(userMono, User.class);
                    });
}
</code>```

Body:
I try to save User to Mongo database in reactive style with Spring WebFlux, but data isn't saved, so I have Java 8, Spring 5 and mongodb.

This is my config:

My entity:

@Document
public class User {
    @Id
    private String id;
    private String username;
    private String password;
}

My repository:

public interface UserRepository extends ReactiveMongoRepository<User, String> {
}

My web config:

@Configuration
@EnableWebFlux
public class WebConfig {

    @Autowired
    private UserRepository userRepository;

    @Bean
    public RouterFunction userRoutes() {
        return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                        request -> {
                            Mono<User> user = request.bodyToMono(User.class);
                            Mono<User> userMono = user.doOnNext(userRepository::save)
                            return ServerResponse.().body(userMono, User.class);
                        });
    }
}

May be I have to manual execute subscribe after save to repository, but I havn't found such info in spring reference?

UPD:
But if I extract from request User and pass it to userRepository and return result I have got a successful result to save data to mongo. But I am not sure that it is a good approach:

@Bean
public RouterFunction userRoutes() {
    return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                    request -> {
                        User user = request.bodyToMono(User.class).block();
                        Mono<User> userMono = userRepository.save(user);
                        return ServerResponse.ok().body(userMono, User.class);
                    });
}

Body:
I have changed doOnNext to flatMap and it works, so it seems to me this is due to the fact that "Transform the item emitted by this Mono asynchronously, returning the value emitted by another Mono" and doOnNext - "Add behavior triggered when the Mono emits a data successfully" and userRepository.save(...) method return Mono that doOnNext add behavious to old Mono and return it(I am loosing response from save method) and flatMap return new Mono which got from save method:

@Bean
public RouterFunction userRoutes() {
    return route(POST("/admin/users").and(accept(APPLICATION_JSON)),
                    request -> {
                        Mono<User> user = request.bodyToMono(User.class);
                            Mono<User> userMono = user.flatMap(userRepository::save);
                            return ServerResponse.status(HttpStatus.CREATED).body(userMono, User.class);
                    });
}