问:
asp.net, radiobuttonlist, show record number in url
i have a radio button list that on selecting, queries a table and displays data in a textarea. now i'm trying to enhance my code so that the value of the radio button is displayed within the URL. that way i can send users links to content displayed by the radio selection (i.e. articles).

So far i've been able to place the "Article_PK" within the url successfully when the user makes a selection. now i'm just stuck on how to get my databind working again. so basically, i need to read in the value of the "Article_PK" in the url to display the data within the textarea. need someone with some mad coding skills to save the day!

code behind --------

```<code>public partial class frm_Articles : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack == false)
        {

            RadioButtonList1.SelectedIndex = 0;
            RadioButtonList1.DataBind();

        }

        else
        {

            string strRedirect;

            strRedirect = "frm_Articles.aspx?Article_PK=" + RadioButtonList1.SelectedValue.ToString();

            Response.Redirect(strRedirect);

        }
    }

    protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

  //

    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        try{
        e.Command.Parameters["@URL_FK"].Value =  Session["URL_PK"];

        }
     catch (Exception ex)
     {

     }

    }

}
</code>```

----- aspx

```<code>  <tr valign="top">
        <td  width="75%">

        <!-- Body -->
            <asp:DetailsView ID="DetailsView3" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="100%" Width="100%" GridLines="None">
                <Fields>

                    <asp:TemplateField HeaderText="ArticleText" ShowHeader="False" SortExpression="ArticleText">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
                        </InsertItemTemplate>
                        <ItemTemplate>

                <%# Eval("ArticleText") %>

                        </ItemTemplate>
                    </asp:TemplateField>
                </Fields>
            </asp:DetailsView>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CSFConnectionString %>" SelectCommand="SELECT [ArticleText], [Title] FROM [TEST_Article] WHERE ([Article_PK] = @Article_PK)" onselecting="SqlDataSource2_Selecting">
                <SelectParameters>
                    <asp:ControlParameter ControlID="RadioButtonList1" DefaultValue="1" Name="Article_PK" PropertyName="SelectedValue" Type="Int32" ConvertEmptyStringToNull="True" />
                </SelectParameters>
            </asp:SqlDataSource>
            </td>
            <td  width="25%" align="left" valign="top">
                                                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TESTConnectionString %>" SelectCommand="SELECT Article_PK, ArticleText, Score, Title, Url_FK FROM TEST_Article WHERE (Url_FK = @URL_FK)" onselecting="SqlDataSource1_Selecting">
                                                    <SelectParameters>
                                                        <asp:Parameter DefaultValue="0" Name="Url_FK" Type="Int32" />
                                                    </SelectParameters>
                                                </asp:SqlDataSource>
                                                <h2>Articles</h2>
                                                <h2>Select an article below:</h2>
                                                <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Title" DataValueField="Article_PK">
                                                </asp:RadioButtonList>
                                                <br />

                                            </td></tr>
</code>```

答:
If you didn't build anything in your PageLoad event to handle the query string, then nothing will happen when the controls does a postback.

Inside your pageLoad event you want something like:

```<code>if(IsPostBack)
{
    if(Request.QueryString["URL_PK"] != null)
    {
    int url_pk;
    if(int.TryParse(Request.QueryString["URL_PK"].ToString(), out url_pk)
    {
         //do whatever you need to do with url pk here
    }
}
</code>```

Set your radio buttons to have autopostback="true" and you should get the desired effect.

Body:
i have a radio button list that on selecting, queries a table and displays data in a textarea. now i'm trying to enhance my code so that the value of the radio button is displayed within the URL. that way i can send users links to content displayed by the radio selection (i.e. articles).

So far i've been able to place the "Article_PK" within the url successfully when the user makes a selection. now i'm just stuck on how to get my databind working again. so basically, i need to read in the value of the "Article_PK" in the url to display the data within the textarea. need someone with some mad coding skills to save the day!

code behind --------

public partial class frm_Articles : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack == false)
        {

            RadioButtonList1.SelectedIndex = 0;
            RadioButtonList1.DataBind();

        }

        else
        {

            string strRedirect;

            strRedirect = "frm_Articles.aspx?Article_PK=" + RadioButtonList1.SelectedValue.ToString();

            Response.Redirect(strRedirect);

        }
    }

    protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

  //

    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        try{
        e.Command.Parameters["@URL_FK"].Value =  Session["URL_PK"];

        }
     catch (Exception ex)
     {

     }

    }

}

----- aspx

            <asp:DetailsView ID="DetailsView3" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="100%" Width="100%" GridLines="None">
                <Fields>

                    <asp:TemplateField HeaderText="ArticleText" ShowHeader="False" SortExpression="ArticleText">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
                        </InsertItemTemplate>
                        <ItemTemplate>

                <%# Eval("ArticleText") %>

                        </ItemTemplate>
                    </asp:TemplateField>
                </Fields>
            </asp:DetailsView>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CSFConnectionString %>" SelectCommand="SELECT [ArticleText], [Title] FROM [TEST_Article] WHERE ([Article_PK] = @Article_PK)" onselecting="SqlDataSource2_Selecting">
                <SelectParameters>
                    <asp:ControlParameter ControlID="RadioButtonList1" DefaultValue="1" Name="Article_PK" PropertyName="SelectedValue" Type="Int32" ConvertEmptyStringToNull="True" />
                </SelectParameters>
            </asp:SqlDataSource>

                                                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TESTConnectionString %>" SelectCommand="SELECT Article_PK, ArticleText, Score, Title, Url_FK FROM TEST_Article WHERE (Url_FK = @URL_FK)" onselecting="SqlDataSource1_Selecting">
                                                    <SelectParameters>
                                                        <asp:Parameter DefaultValue="0" Name="Url_FK" Type="Int32" />
                                                    </SelectParameters>
                                                </asp:SqlDataSource>

Articles

Select an article below:

                                                <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Title" DataValueField="Article_PK">
                                                </asp:RadioButtonList>

Body:
If you didn't build anything in your PageLoad event to handle the query string, then nothing will happen when the controls does a postback.

Inside your pageLoad event you want something like:

if(IsPostBack)
{
    if(Request.QueryString["URL_PK"] != null)
    {
    int url_pk;
    if(int.TryParse(Request.QueryString["URL_PK"].ToString(), out url_pk)
    {
         //do whatever you need to do with url pk here
    }
}

Set your radio buttons to have autopostback="true" and you should get the desired effect.


来源: stackexchange

问:
How to use menu and ListView simultaneously in a Navigation View
I have created a navigation view inside which a dynamic list is created at run time from the data retrieved from server. It works fine, and shows the list once a successful communication has been done with the server. The problem is that I am unable to add items like Settings and About Us to the bottom of the list. The following layout (activity_main.xml) results in menu items overshadowing the list view items:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:elevation="@dimen/padding"
        app:menu="@menu/navigation_items"

        >

        <android.support.v7.widget.ListViewCompat
            android:id="@+id/categories_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:layout_gravity="center"
            android:layout_marginStart="@dimen/margin_side"
            android:layout_marginLeft="@dimen/margin_side"
            android:layout_marginTop="@dimen/nav_header_height"
            android:layout_marginBottom="48dp"
            />

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</code>```

And this is the contents of navigation_items.xml (menu resource):

```<code><menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/nav_bottom"
    android:orderInCategory="0">
    <item
        android:id="@+id/settings"
        android:icon="@drawable/settings"
        android:title="@string/settings" />
    <item
        android:id="@+id/about_us"
        android:icon="@drawable/info"
        android:title="@string/about_us" />

</group>
</menu>
</code>```

The result on emulator is as follows:

答:
The simplest way to achieve what you want is

```<code><com.example.raghu.drawersample.ScrimInsetsRelativeLayout
    android:layout_width="320dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"
    android:fitsSystemWindows="true">

    <android.support.design.widget.NavigationView
        android:layout_alignParentBottom="true"
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/activity_main_drawer" />

    <android.support.v7.widget.RecyclerView
       android:layout_above="@+id/nav_view"
        android:id="@+id/item_list"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:scrollbars="vertical" />

</com.example.raghu.drawersample.ScrimInsetsRelativeLayout>
</code>```

ViewGroup does not have setNavigationItemSelectedListener, then how
  can it be used instead of NavigationView? Also, how do I embed a menu
  inside a ViewGroup?

You are just wrapping your NavigationView and ListView/RecyclerView in  a RelativeLayout

Its upto you whether you use RecyclerView or ListView. You can use  navigationView.setNavigationItemSelectedListener(this) normally.

Picked ScrimInsetsRelativeLayout code from https://github.com/mikepenz/Materialize/blob/develop/library/src/main/java/com/mikepenz/materialize/view/ScrimInsetsRelativeLayout.java

I used that cause i added a header to recylerview and i wanted the status bar to look exactly like in the pic below.

You end up with

I am not sure if appending "settings" to my list view is a good idea

The other way is to add your settings items as a footer to your recyclerview. You can see this pattern in gmail. I am not sure why its not a good idea. If you have more items user still needs to scroll down.

While fixing the footer(settings & help) at the bottom with shadow at the top is what you see in inbox app.

ContentLicense: CC BY-SA 3.0

Body:
I have created a navigation view inside which a dynamic list is created at run time from the data retrieved from server. It works fine, and shows the list once a successful communication has been done with the server. The problem is that I am unable to add items like Settings and About Us to the bottom of the list. The following layout (activity_main.xml) results in menu items overshadowing the list view items:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:elevation="@dimen/padding"
        app:menu="@menu/navigation_items"

        >

        <android.support.v7.widget.ListViewCompat
            android:id="@+id/categories_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:layout_gravity="center"
            android:layout_marginStart="@dimen/margin_side"
            android:layout_marginLeft="@dimen/margin_side"
            android:layout_marginTop="@dimen/nav_header_height"
            android:layout_marginBottom="48dp"
            />

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

And this is the contents of navigation_items.xml (menu resource):

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/nav_bottom"
    android:orderInCategory="0">
    <item
        android:id="@+id/settings"
        android:icon="@drawable/settings"
        android:title="@string/settings" />
    <item
        android:id="@+id/about_us"
        android:icon="@drawable/info"
        android:title="@string/about_us" />

</group>
</menu>

The result on emulator is as follows:

Body:
The simplest way to achieve what you want is

<com.example.raghu.drawersample.ScrimInsetsRelativeLayout
    android:layout_width="320dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"
    android:fitsSystemWindows="true">

    <android.support.design.widget.NavigationView
        android:layout_alignParentBottom="true"
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/activity_main_drawer" />

    <android.support.v7.widget.RecyclerView
       android:layout_above="@+id/nav_view"
        android:id="@+id/item_list"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:scrollbars="vertical" />

</com.example.raghu.drawersample.ScrimInsetsRelativeLayout>

ViewGroup does not have setNavigationItemSelectedListener, then how
  can it be used instead of NavigationView? Also, how do I embed a menu
  inside a ViewGroup?

You are just wrapping your NavigationView and ListView/RecyclerView in  a RelativeLayout

Its upto you whether you use RecyclerView or ListView. You can use  navigationView.setNavigationItemSelectedListener(this) normally.

Picked ScrimInsetsRelativeLayout code from https://github.com/mikepenz/Materialize/blob/develop/library/src/main/java/com/mikepenz/materialize/view/ScrimInsetsRelativeLayout.java

I used that cause i added a header to recylerview and i wanted the status bar to look exactly like in the pic below.

You end up with

I am not sure if appending "settings" to my list view is a good idea

The other way is to add your settings items as a footer to your recyclerview. You can see this pattern in gmail. I am not sure why its not a good idea. If you have more items user still needs to scroll down.

While fixing the footer(settings & help) at the bottom with shadow at the top is what you see in inbox app.


问:
http POST in angular 2 client not working while http GET is working
I am trying to do an http POST request on angular 2 client (asp.net core 2.0 api server).

At first there was an 415 error (Unsupported Media).

When I add an header there is a response to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resource error.

Http GET in the same service is working perfectly(without headers).

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

export class MyService {

  constructor(private http: Http) {}

    // This is working
    getStudents(): Observable <string[]>{
      return this.http.get('https://localhost:44753/api/students', {withCredentials:true})
        .map((res:Response)=> res.Json());
    }

    // Return 415
    getStudent(name): Observable <string[]>{
    let data = {
      "name": name
    }
      return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          {withCredentials:true})
        .map((res:Response)=> res.Json());
    }

    // Return 401
     getStudent2(name): Observable <string[]>{
      let data = {
        "name": name
      }

      let headers = new Header();
      headers.append('Content-Type', 'application/json);
      headers.append('Access-Control-Allow-Origin', '*');

      let options = new RequestOptions({ headers:headers , withCredentials:true });

        return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          options)
          .map((res:Response)=> res.Json());
     }

 }```

Can someone help me solve this?

答: It seems like you need to configure server for CORS requests.</p>

Body:
I am trying to do an http POST request on angular 2 client (asp.net core 2.0 api server).

At first there was an 415 error (Unsupported Media).

When I add an header there is a response to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resource error.

Http GET in the same service is working perfectly(without headers).

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

export class MyService {

  constructor(private http: Http) {}

    // This is working
    getStudents(): Observable <string[]>{
      return this.http.get('https://localhost:44753/api/students', {withCredentials:true})
        .map((res:Response)=> res.Json());
    }

    // Return 415
    getStudent(name): Observable <string[]>{
    let data = {
      "name": name
    }
      return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          {withCredentials:true})
        .map((res:Response)=> res.Json());
    }

    // Return 401
     getStudent2(name): Observable <string[]>{
      let data = {
        "name": name
      }

      let headers = new Header();
      headers.append('Content-Type', 'application/json);
      headers.append('Access-Control-Allow-Origin', '*');

      let options = new RequestOptions({ headers:headers , withCredentials:true });

        return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          options)
          .map((res:Response)=> res.Json());
     }

 }

Can someone help me solve this?


问:
remove index.php from laravel route
I've a laravel 5.4 over apache centos server.

the folder structure are like:
/var/www/html <- public folder
/var/www/project <- laravel project folder
/var/www/html contains the "public's laravel folder" content like css/ js/ and index.php etc.

index.php contains references to the project main folder.
the project works but just with ip like:

```<code>myip/index.php/login
</code>```

and not

```<code>myip/login
</code>```

as I would like
I try many way to remove it but without luck, this is my .htaccess file inside /var/www/html:

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ index.php/$1 [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</code>```

答:
Instead of changing the .htaccess file, you should change the server configuration to serve files from Laravel public folder.

Before editing the config file and to be safe, copy the default config file to have a backup: cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.original

Edit the file /etc/httpd/conf/httpd.conf as the follwoing:

change this line:

```<code>DocumentRoot "/var/www/html"
</code>```

to

```<code>DocumentRoot "/var/www/project/public"
</code>```

Add the follwing lines to allow serving files from Laravel public folder:

```<code><Directory "/var/www/project/public">
    AllowOverride All
    Require all granted
</Directory>
</code>```

Run sudo apachectl configtest to make sure you did not make any mistake. You should get Syntax OK.

Restart the apache server to apply the new configuration. sudo systemctl restart httpd

Finally, restore the .htaccess file to the default version that comes with laravel at this link.

It's better to create a virtual host instead of changing the default configuration. However, this will be ok if you have only on website on the server.

Title: remove index.php from laravel route

Body:
I've a laravel 5.4 over apache centos server.

the folder structure are like:
/var/www/html <- public folder
/var/www/project <- laravel project folder
/var/www/html contains the "public's laravel folder" content like css/ js/ and index.php etc.

index.php contains references to the project main folder.
the project works but just with ip like:

myip/index.php/login

and not

myip/login

as I would like
I try many way to remove it but without luck, this is my .htaccess file inside /var/www/html:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ index.php/$1 [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Body:
Instead of changing the .htaccess file, you should change the server configuration to serve files from Laravel public folder.

Before editing the config file and to be safe, copy the default config file to have a backup: cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.original

Edit the file /etc/httpd/conf/httpd.conf as the follwoing:

change this line:

DocumentRoot "/var/www/html"

to

DocumentRoot "/var/www/project/public"

Add the follwing lines to allow serving files from Laravel public folder:

<Directory "/var/www/project/public">
    AllowOverride All
    Require all granted
</Directory>

Run sudo apachectl configtest to make sure you did not make any mistake. You should get Syntax OK.

Restart the apache server to apply the new configuration. sudo systemctl restart httpd

Finally, restore the .htaccess file to the default version that comes with laravel at this link.

It's better to create a virtual host instead of changing the default configuration. However, this will be ok if you have only on website on the server.


问:
Mutable and Immutable Strings in python
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

```<code>str1='Rohit'
str1.replace('R','M')
</code>```

This gives the output:

```<code>'Mohit'
</code>```

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

```<code>'Rohit'.replace('R','M')
</code>```

This also gives me the output:

```<code>'Mohit'
</code>```

Then what is meant by 'Strings are immutable'?

答:
Strings don't have any methods on them that allow a change to the value of the string. In other words: strings are immutable.

When you call str.replace a new string is built and returned.

```<code>>>> s1 = 'Rohit'
>>> s2 = s1.replace('R', 'M')
>>>
>>> s1
'Rohit'
>>> s2
'Mohit'
</code>```

As you can see s1 still has its original value.

Title: Mutable and Immutable Strings in python

Body:
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

str1='Rohit'
str1.replace('R','M')

This gives the output:

'Mohit'

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

'Rohit'.replace('R','M')

This also gives me the output:

'Mohit'

Then what is meant by 'Strings are immutable'?

Body:
Strings don't have any methods on them that allow a change to the value of the string. In other words: strings are immutable.

When you call str.replace a new string is built and returned.

>>> s1 = 'Rohit'
>>> s2 = s1.replace('R', 'M')
>>>
>>> s1
'Rohit'
>>> s2
'Mohit'

As you can see s1 still has its original value.


问:
How to set enabled/disabled dataset in a NVD3 line chart?
I see in the legend on the top right here http://nvd3.org/examples/line.html radio buttons which I can click to turn on/off some datasets on the chart.

Is there an option to set this value for each dataset individually when I load data into chart?

答:
You can set a disabled flag on the data to hide it on load. If you go to this example and add a disabled flag to the Data (JSON) tab you can see this.</p>

```<code>function() {
  var sin = [],
      cos = [];

  for (var i = 0; i < 100; i++) {
    sin.push({x: i, y: Math.sin(i/10)});
    cos.push({x: i, y: .5 * Math.cos(i/10)});
  }

  return [
    {
      values: sin,
      key: 'Sine Wave',
      color: '#ff7f0e',
      disabled: true
    },
    {
      values: cos,
      key: 'Cosine Wave',
      color: '#2ca02c'
    }
  ];
}
</code>```

Body:
You can set a disabled flag on the data to hide it on load. If you go to this example and add a disabled flag to the Data (JSON) tab you can see this.

function() {
  var sin = [],
      cos = [];

  for (var i = 0; i < 100; i++) {
    sin.push({x: i, y: Math.sin(i/10)});
    cos.push({x: i, y: .5 * Math.cos(i/10)});
  }

  return [
    {
      values: sin,
      key: 'Sine Wave',
      color: '#ff7f0e',
      disabled: true
    },
    {
      values: cos,
      key: 'Cosine Wave',
      color: '#2ca02c'
    }
  ];
}


问:
How to capture hidden

From below HTML:

      <input type="submit" value="Add To Cart" name="Buy" class="wpsc_buy_button">

Please select product options before adding to cart

```

<p>When clicked on Add To Cart button following alert error will show and will be hidden. <strong>How to capture the <code><div></code> alert addtocart as this is hidden by default?</strong></p>

<pre class="lang-html prettyprint-override"><code><div>
  <br>
 <div class="alert addtocart" style="display: none;">
  <br>
   <p>Item has been added to your cart!</p>
  <br>
   <span> </span>
  <br>
 </div>
  <!--close input-button-buy-->
 <div class="wpsc_loading_animation" style="visibility: hidden;">
  <br>
   <img title="Loading" alt="Loading" src="http://store.demoqa.com/wp-content/themes/mio/images/ajax-loader.gif">
 </div>
  <!--close wpsc_loading_animation-->
  <br>
</div>
</code>```

答:
Try  using JavascriptExecutor

use this code:

```<code>WebElement element_hide= driver.findElement(By.xpath("wpsc_loading_animation");
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element_hide);
</code>```

Title: How to capture hidden <div>

Body:
From below HTML:

      <input type="submit" value="Add To Cart" name="Buy" class="wpsc_buy_button">

Please select product options before adding to cart

When clicked on Add To Cart button following alert error will show and will be hidden. How to capture the
 alert addtocart as this is hidden by default?

Item has been added to your cart!

Body:
Try  using JavascriptExecutor

use this code:

WebElement element_hide= driver.findElement(By.xpath("wpsc_loading_animation");
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element_hide);


问:
DynamoDB fast search on complex data types
I need to create a new table on AWS DynamoDB that will have a structure like the following:

```<code>{
    "email" : String (key),
    ... : ...,
    "someStuff" : SomeType,
    ... : ...,

    "listOfIDs" : Array<String>
}
</code>```

This table contains users' data and a list of strings that I'll often query (see listOfIDs).

Since I don't want to scan the table every time in order to get the user linked to that specific ID due to its slowness, and I cannot create an index since it's an Array and not a "simple" type, how could I improve the structure of my table? Should I use a different table where I have all my IDs and the users linked to them in a "flat" structure? Is there any other way?

Thank you all!

答:
Should I use a different table where I have all my IDs and the users linked to them in a "flat" structure?

I think this is going to be your best bet if you want to leverage DynamoDB's parallelism for query performance.

Another option might be using a CONTAINS expression in a query if your listOfIDs is stored as a set, but I can't imagine that will scale performance-wise as your table grows.

Body:
I need to create a new table on AWS DynamoDB that will have a structure like the following:

{
    "email" : String (key),
    ... : ...,
    "someStuff" : SomeType,
    ... : ...,

    "listOfIDs" : Array<String>
}

This table contains users' data and a list of strings that I'll often query (see listOfIDs).

Since I don't want to scan the table every time in order to get the user linked to that specific ID due to its slowness, and I cannot create an index since it's an Array and not a "simple" type, how could I improve the structure of my table? Should I use a different table where I have all my IDs and the users linked to them in a "flat" structure? Is there any other way?

Thank you all!


问:
Codesign error in Xcode 9
I have the strange error. When my app is compiling, Xcode 9 asks for password in keychain. But when I enter the password, this window appears a lot and so on ad infinitum. If I do not enter the password, then the application will not be compiled.

Text: Code sign want to sign using key LG in your keychain.
Button : always allow, deny, allow

答: Enter your password and selecting the "Always allow" button should help.</p>

Title: Codesign error in Xcode 9


问:
" No NVENC capable devices found" with ffmpeg for screen capture and RTP stream
I´m trying to stream my Desktop with RTP using ffmpeg.

libx264 seems to work fine. But I would like to test the performance of a hardware accelerated codec.

```<code>ffmpeg -re -f dshow -i video="screen-capture-recorder" -vcodec libx264 -tune zerolatency -preset ultrafast -an -f rtp rtp://192.168.0.1
</code>```

The NVENC codec works fine in other situations like this

```<code>ffmpeg -y -rtbufsize 2000M -f gdigrab -framerate 60 -offset_x 0 -offset_y 0 -video_size 1280x1080 -i desktop -c:v nvenc -preset:v fast -pix_fmt nv12 out.mp4
</code>```

The Codec also apears in the list of available codecs.

However this command doesn´t work

```<code>ffmpeg -re -f dshow -i video="screen-capture-recorder" -vcodec nvenc -preset llhq -an -f rtp rtp://192.168.0.1
</code>```

My machine is a Windows 10 with GTX 760

答:
I found out what was wrong a few weeks ago.

Ffmpeg was expecting a GPU with CUDA 8, unfortunately GPUs with Kepler archtecture, like my 760,  have limited CUDA 8 features.

So NVENC could not properly work. The "solution" is to find a Ffmpeg release with CUDA 7 or 7.5 support.

Body:
I´m trying to stream my Desktop with RTP using ffmpeg.

libx264 seems to work fine. But I would like to test the performance of a hardware accelerated codec.

ffmpeg -re -f dshow -i video="screen-capture-recorder" -vcodec libx264 -tune zerolatency -preset ultrafast -an -f rtp rtp://192.168.0.1

The NVENC codec works fine in other situations like this

ffmpeg -y -rtbufsize 2000M -f gdigrab -framerate 60 -offset_x 0 -offset_y 0 -video_size 1280x1080 -i desktop -c:v nvenc -preset:v fast -pix_fmt nv12 out.mp4

The Codec also apears in the list of available codecs.

However this command doesn´t work

ffmpeg -re -f dshow -i video="screen-capture-recorder" -vcodec nvenc -preset llhq -an -f rtp rtp://192.168.0.1

My machine is a Windows 10 with GTX 760


问:
why run both of confirmation of if()else in javascript?whats solution?
I write code to check a form and if user enter all of information run confirm that show " are you sure to submit?".i use this for two form in onclick attribute.
My code is same this:

```<code>Var strurl=window.location.search();
 If(strurl.search("click=edit")>0)
  {
 If(document.forms["frm"]["fname"].value="")
 { alert("please enter all information required");
  Return false;
}

Return Confirm("are you sure to submit?");

}
Else
{

If(document.forms["frm"]["tel_num"].value="")
  { alert("please enter all information required");
 Return false;
  }

Return Confirm("are you sure to submit?");

}
</code>```

This code is for two form that one of these form show in one condition and dont show both form by php programming.

But my problem is run both confirm in both form and i couldnt block one of them in another form.

I know that can seperate to two page but for a reason i should use these codes in one page.

What should i do to solve this?

答: I found the problem.:-) I call twice this function.I found that between 1000 line of codes after 5 hours search.</p>

Body:
I write code to check a form and if user enter all of information run confirm that show " are you sure to submit?".i use this for two form in onclick attribute.
My code is same this:

Var strurl=window.location.search();
 If(strurl.search("click=edit")>0)
  {
 If(document.forms["frm"]["fname"].value="")
 { alert("please enter all information required");
  Return false;
}

Return Confirm("are you sure to submit?");

}
Else
{

If(document.forms["frm"]["tel_num"].value="")
  { alert("please enter all information required");
 Return false;
  }

Return Confirm("are you sure to submit?");

}

This code is for two form that one of these form show in one condition and dont show both form by php programming.

But my problem is run both confirm in both form and i couldnt block one of them in another form.

I know that can seperate to two page but for a reason i should use these codes in one page.

What should i do to solve this?


问:
Is it possible to deploy multiple war files under the same deployment path?
Let's say I have:

foo.war

bar.war

Is it possible that I deploy them both somehow to the same deployment path? E.g., to access it at:

http://localhost/baz

Are the content of the war files merged somehow? How are file conflicts handled (e.g., let's say both of them has an index.jsp file)?

Thx in advnace!

答:
Yes & no.

I don't think it's possible to somehow merge them into the same file system path within a servlet container like Tomcat (unless you were to write some kind of complicated, intelligent script to do so).  For starters, each .war will have a WEB-INF/web.xml file, and each will rely on the contents of its own file to function -- which would win?

But you conceivably could...

Deploy to 2 different contexts (or containers, or hosts), and employ some kind of load balancer (hardware or software) to route some requests to one, other requests to the other.

Use an "overlay" strategy (such as Maven Overlays) to make a second (and final) .war that is a derivative and extension of another .war file


问:
How to correctly do Pattern matching by type in this case?
I have a use-case where I'd like to serialize a Saddle Frame to a Scala-Play Json. I had it working for simple element types e.g. Double i.e. Frame[DateTime, String, Double] but now it becomes a bit more hairy trying to serialize Frame types whose elements are complex types e.g. Seq[(DateTime, Double)]

So I have the basic frameWrites implementation that works for primitive element types:

```<code>import play.api.libs.json._
import org.saddle._
import org.joda.time._

object JsonUtils {
implicit def frameWrites[RX, CX, E] = new Writes[Frame[RX, CX, E]] {
  override def writes(frame: Frame[RX, CX, E]): JsValue = {
    val json: JsArray = Json.arr(
      (0 until frame.numRows).map { i =>
        Json.obj(
          frame.rowIx.at(i).toString ->
            (0 until frame.numCols).map { j =>
              Json.obj(
                frame.colIx.at(j).toString -> cellWrites(frame.at(i, j))
              )
            }
        )
      })
    json
  }
}}
</code>```

So I created a cellWrites to be able to handle complex element types like so:

```<code>object JsonUtils {
implicit def cellWrites[E](elem: E)(implicit tag: ClassTag[E]): JsValue = {
  elem match {
    case seq: Seq[(DateTime, Double)] => {
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this should but doesn't happen
      Json.arr(
        seq.map { case (dt: DateTime, value: Double) =>
          Json.obj(dt.toString -> JsNumber(value))
        }
      )
    }
    case doubleValue: Double => JsNumber(doubleValue)
    case _ => JsString(elem.toString)
  }
}}
</code>```

The problem is that my Frame or type Frame[String, String, Seq[(DateTime, Double)]] is never matching the appropriate first case in cellWrites. I also tried using the implicit tag type information but could not find the way to use it for Pattern matching. This is a test-case sample Frame I use:

```<code>val today = DateTime.parse("2017-11-14T13:00:00.000+01:00")
val colIx = Index("x", "y")
val data = Seq(
  Series(
    "a" -> Seq(
        today.minusHours(2) -> 2.0,
        today.minusHours(1) -> 1.0,
        today.minusHours(0) -> 0.0
    ),
    "b" -> Seq(
      today.minusHours(1) -> 1.0,
      today.minusHours(0) -> 0.0
    )
  ),
  Series(
    "a" -> Seq(
      today.minusHours(5) -> 5.0,
      today.minusHours(4) -> 4.0,
      today.minusHours(3) -> 3.0
    ),
    "b" -> Seq(
      today.minusHours(4) -> 4.0,
      today.minusHours(3) -> 3.0
    )
  )
)
val frame: Frame[String, String, Seq[(DateTime, Double)]] = Frame(data, colIx)
println(frame)
</code>```

Note that all the code above compiles fine. However, the Pattern matching by cell element type is not working.

答:
OK found it, elem was actually of type org.saddle.scalar.Scalar[E] therefore this works:

```<code>implicit def cellWrites[E](scalar: Scalar[E]): JsValue = {
  val elem = scalar.get
  elem match {
    case seq: Seq[(DateTime, Double)] => {
      Json.arr(
        seq.map { case (dt: DateTime, value: Double) =>
          Json.obj(dt.toString -> JsNumber(value))
        }
      )
    }
    case doubleValue: Double => JsNumber(doubleValue)
    case _ => JsString(elem.toString)
  }
}
</code>```

Body:
I have a use-case where I'd like to serialize a Saddle Frame to a Scala-Play Json. I had it working for simple element types e.g. Double i.e. Frame[DateTime, String, Double] but now it becomes a bit more hairy trying to serialize Frame types whose elements are complex types e.g. Seq[(DateTime, Double)]

So I have the basic frameWrites implementation that works for primitive element types:

import play.api.libs.json._
import org.saddle._
import org.joda.time._

object JsonUtils {
implicit def frameWrites[RX, CX, E] = new Writes[Frame[RX, CX, E]] {
  override def writes(frame: Frame[RX, CX, E]): JsValue = {
    val json: JsArray = Json.arr(
      (0 until frame.numRows).map { i =>
        Json.obj(
          frame.rowIx.at(i).toString ->
            (0 until frame.numCols).map { j =>
              Json.obj(
                frame.colIx.at(j).toString -> cellWrites(frame.at(i, j))
              )
            }
        )
      })
    json
  }
}}

So I created a cellWrites to be able to handle complex element types like so:

object JsonUtils {
implicit def cellWrites[E](elem: E)(implicit tag: ClassTag[E]): JsValue = {
  elem match {
    case seq: Seq[(DateTime, Double)] => {
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this should but doesn't happen
      Json.arr(
        seq.map { case (dt: DateTime, value: Double) =>
          Json.obj(dt.toString -> JsNumber(value))
        }
      )
    }
    case doubleValue: Double => JsNumber(doubleValue)
    case _ => JsString(elem.toString)
  }
}}

The problem is that my Frame or type Frame[String, String, Seq[(DateTime, Double)]] is never matching the appropriate first case in cellWrites. I also tried using the implicit tag type information but could not find the way to use it for Pattern matching. This is a test-case sample Frame I use:

val today = DateTime.parse("2017-11-14T13:00:00.000+01:00")
val colIx = Index("x", "y")
val data = Seq(
  Series(
    "a" -> Seq(
        today.minusHours(2) -> 2.0,
        today.minusHours(1) -> 1.0,
        today.minusHours(0) -> 0.0
    ),
    "b" -> Seq(
      today.minusHours(1) -> 1.0,
      today.minusHours(0) -> 0.0
    )
  ),
  Series(
    "a" -> Seq(
      today.minusHours(5) -> 5.0,
      today.minusHours(4) -> 4.0,
      today.minusHours(3) -> 3.0
    ),
    "b" -> Seq(
      today.minusHours(4) -> 4.0,
      today.minusHours(3) -> 3.0
    )
  )
)
val frame: Frame[String, String, Seq[(DateTime, Double)]] = Frame(data, colIx)
println(frame)

Note that all the code above compiles fine. However, the Pattern matching by cell element type is not working.

Body:
OK found it, elem was actually of type org.saddle.scalar.Scalar[E] therefore this works:

implicit def cellWrites[E](scalar: Scalar[E]): JsValue = {
  val elem = scalar.get
  elem match {
    case seq: Seq[(DateTime, Double)] => {
      Json.arr(
        seq.map { case (dt: DateTime, value: Double) =>
          Json.obj(dt.toString -> JsNumber(value))
        }
      )
    }
    case doubleValue: Double => JsNumber(doubleValue)
    case _ => JsString(elem.toString)
  }
}


问:
Play/Pause button for my automatic jquery slider
So I have an automatic jquery slider which I want to control via a play/pause button. Currently the slider starts on page load but I want to be able to start/pause it with a play button, class=heart.

I want the image with play class to be the play/pause button.

I currently have no idea how to do this, here is my code:

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides1");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    setTimeout(showSlides, 7000); // Change image every 2 seconds
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.polaroid1{
 box-shadow: 10px 10px 7px -7px rgba(0, 0, 0, 0.5);
 -webkit-backface-visibility: hidden;
 transform: rotate(-8deg);
 margin-bottom:30px;
 width:380px;
 height:320px;
 background-color:rgba(255, 255, 255, 1.0);
 text-align:right;
 padding-top:10px;
 padding-right:10px;
 padding-left:10px;
 padding-bottom:15px;
 top:15px;
 left:25px;
 position:relative;
}

.photo1{
 width:100%;
 height:85%;
 position:relative;
 padding:5px;
}

.date1{
 margin:0;
 padding-right:10px;
 font-family: 'Covered By Your Grace', cursive;
 transform: rotate(-5deg);
 font-size:28px;
}

.mySlides1{
 display:none;
 width:380px;
 height:320px;
 position:absolute;
 top:0px;
 left:0px;
}

.play{
 position:absolute;
 left:5px;
 bottom:5px;
 cursor:pointer;
 z-index:10000;
}</code>```

22-05-2017

12-08-2017

22-05-2017

```

答:
I edited your example. Call startSlides() to start the slider, and stopSlides() to stop it. The main idea is to clear the timeout when stopping and set it again when starting.

var slideIndex = 0;
var stop = false;
var sliderTimeout;
showSlides();

function click() {
   if (stop) {
       startSlides();
   } else {
       stopSlides();
   }
}

function stopSlides() {
    clearTimeout(sliderTimeout);
    stop = true;
}

function startSlides() {
    stop = false;
    showSlides();
}

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides1");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    if (!stop) {
        sliderTimeout = setTimeout(showSlides, 7000); // Change image every 2 seconds
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.polaroid1{
 box-shadow: 10px 10px 7px -7px rgba(0, 0, 0, 0.5);
 -webkit-backface-visibility: hidden;
 transform: rotate(-8deg);
 margin-bottom:30px;
 width:380px;
 height:320px;
 background-color:rgba(255, 255, 255, 1.0);
 text-align:right;
 padding-top:10px;
 padding-right:10px;
 padding-left:10px;
 padding-bottom:15px;
 top:15px;
 left:25px;
 position:relative;
}

.photo1{
 width:100%;
 height:85%;
 position:relative;
 padding:5px;
}

.date1{
 margin:0;
 padding-right:10px;
 font-family: 'Covered By Your Grace', cursive;
 transform: rotate(-5deg);
 font-size:28px;
}

.mySlides1{
 display:none;
 width:380px;
 height:320px;
 position:absolute;
 top:0px;
 left:0px;
}

.play{
 position:absolute;
 left:5px;
 bottom:5px;
 cursor:pointer;
 z-index:10000;
}</code>```

22-05-2017

12-08-2017

22-05-2017

```

Body:
So I have an automatic jquery slider which I want to control via a play/pause button. Currently the slider starts on page load but I want to be able to start/pause it with a play button, class=heart.

I want the image with play class to be the play/pause button.

I currently have no idea how to do this, here is my code:

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides1");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    setTimeout(showSlides, 7000); // Change image every 2 seconds
}

.polaroid1{
 box-shadow: 10px 10px 7px -7px rgba(0, 0, 0, 0.5);
 -webkit-backface-visibility: hidden;
 transform: rotate(-8deg);
 margin-bottom:30px;
 width:380px;
 height:320px;
 background-color:rgba(255, 255, 255, 1.0);
 text-align:right;
 padding-top:10px;
 padding-right:10px;
 padding-left:10px;
 padding-bottom:15px;
 top:15px;
 left:25px;
 position:relative;
}

.photo1{
 width:100%;
 height:85%;
 position:relative;
 padding:5px;
}

.date1{
 margin:0;
 padding-right:10px;
 font-family: 'Covered By Your Grace', cursive;
 transform: rotate(-5deg);
 font-size:28px;
}

.mySlides1{
 display:none;
 width:380px;
 height:320px;
 position:absolute;
 top:0px;
 left:0px;
}

.play{
 position:absolute;
 left:5px;
 bottom:5px;
 cursor:pointer;
 z-index:10000;
}

22-05-2017

12-08-2017

22-05-2017

Body:
I edited your example. Call startSlides() to start the slider, and stopSlides() to stop it. The main idea is to clear the timeout when stopping and set it again when starting.

var slideIndex = 0;
var stop = false;
var sliderTimeout;
showSlides();

function click() {
   if (stop) {
       startSlides();
   } else {
       stopSlides();
   }
}

function stopSlides() {
    clearTimeout(sliderTimeout);
    stop = true;
}

function startSlides() {
    stop = false;
    showSlides();
}

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides1");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    if (!stop) {
        sliderTimeout = setTimeout(showSlides, 7000); // Change image every 2 seconds
    }
}

.polaroid1{
 box-shadow: 10px 10px 7px -7px rgba(0, 0, 0, 0.5);
 -webkit-backface-visibility: hidden;
 transform: rotate(-8deg);
 margin-bottom:30px;
 width:380px;
 height:320px;
 background-color:rgba(255, 255, 255, 1.0);
 text-align:right;
 padding-top:10px;
 padding-right:10px;
 padding-left:10px;
 padding-bottom:15px;
 top:15px;
 left:25px;
 position:relative;
}

.photo1{
 width:100%;
 height:85%;
 position:relative;
 padding:5px;
}

.date1{
 margin:0;
 padding-right:10px;
 font-family: 'Covered By Your Grace', cursive;
 transform: rotate(-5deg);
 font-size:28px;
}

.mySlides1{
 display:none;
 width:380px;
 height:320px;
 position:absolute;
 top:0px;
 left:0px;
}

.play{
 position:absolute;
 left:5px;
 bottom:5px;
 cursor:pointer;
 z-index:10000;
}

<div class="polaroid1">
  <img class="play" src="images/heart.png">
  <div class="mySlides1 fade">
    <img class="photo1" src="images/IMG-20170610-WA0028.jpg">
    <h3 class="date1">22-05-2017</h3>
  </div>
  <div class="mySlides1 fade">
    <img class="photo1" src="images/20170812_181516.jpg">
    <h3 class="date1">12-08-2017</h3>
  </div>
  <div class="mySlides1 fade">
    <img class="photo1" src="images/20170522_112958.jpg">
    <h3 class="date1">22-05-2017</h3>
  </div>
</div>


问:
SQL Query conversion from 6.5 to >= SQL Server 2008
Currently i am working on the migration project. Found the below query in a procedure. I am able to get the size of database from sys.master_files table. In WHERE condition segmap is used. I am not able to find the simillar column in sys.master_files. Please help me on this</p>

```<code>SELECT sum(size) * 2
FROM master..sysusages U
WHERE U.segmap = 3
  AND U.dbid = db_id(@db_name)
</code>```

答:
SYBASE and SQLSERVER used to share same code base.So as from SYBASE docs..below is definition of segmap

The values of master..sysusages.segmap mean the following:

3: Data stored on this segment

4: Log stored on this segment

7: Since 7=4+3, both log and data stored on this segment

So the equivalent would be type='0' which means get only data space

Body:
Currently i am working on the migration project. Found the below query in a procedure. I am able to get the size of database from sys.master_files table. In WHERE condition segmap is used. I am not able to find the simillar column in sys.master_files. Please help me on this

SELECT sum(size) * 2
FROM master..sysusages U
WHERE U.segmap = 3
  AND U.dbid = db_id(@db_name)


问:
Numerically sorting the String Arrays
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

```<code>14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289
</code>```

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

Title: Numerically sorting the String Arrays

Body:
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

Body:
You can also create a custom comparator:

List<String> list = Arrays.asList("14829435897932384626433832795", "4159265358979323846264338327", "1937286535897932384626433832795296523", "23746289", "4159265358979323846264338326");

// comparing by String if the length is equal
Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(String::compareTo));

System.out.println(list);

Output:

[23746289, 4159265358979323846264338326, 4159265358979323846264338327,
  14829435897932384626433832795, 1937286535897932384626433832795296523]


答:
Perhaps another table that looks like:

```<code>ID    string / hash key,
Email string / range key,
Any other attributes you may want to access
</code>```

The unique combination of ID and email will allow you to search on the "List of IDs". You may want to include other attributes within this table to save you from needing to perform another query.

Title: DynamoDB fast search on complex data types

Body:
Perhaps another table that looks like:

ID    string / hash key,
Email string / range key,
Any other attributes you may want to access

The unique combination of ID and email will allow you to search on the "List of IDs". You may want to include other attributes within this table to save you from needing to perform another query.


问:
Fluent movement with NetworkTransform & NetworkAnimator
My player character moves around the world using the Animator with root motion activated. Basically, the AI system sets the velocities on Animator, which in turn controls the Animation clips that control character motion. As this is a standard feature that ensures very realistic animation without noticable sliding, I thought this was a good idea ...until I added Network synchronization.

Synching the characters over the Network using NetworkTransform and NetworkAnimation causes those two components to conflict:

NetworkTransform moves the character to whichever position the host commands.

NetworkAnimator syncs the animation vars and plays the Animation clips as host instructs it to, while those Animation clips also apply root motion.

The result is precise (meaning the character reaches the exact target destination), but very stuttering movement (noticable jumps).

Removing NetworkTransform, the host and client instances of the characters desynchronize very quickly, meaning they will end up at different positions in the world when solely controlled by the timing-dependant Animator.

Removing NetworkAnimator, client instances won't play the same animations as the host, if any animations at all.

I tried keeping both Components while disabling root motion for the Animator (on client only). In that case however, NetworkTransform does not seem to interpolate at all. The character just jumps from synched position to synched position in steps of about 0.02 units. Same with rotation.

NetworkTransform is configured to "Sync Transform", as the character neither has a RigidBody nor a CharacterController. All other values are the defaults: sync rate of 9 (also tried higher values there), movement threshold of 0.001, snap threshold of 5, interpolate movement = 1.

How do I get fluent root motion based movement on the Network? I expected that to be a standard scenario...

答:
What you need is to disasble the Root Motion flag on non local instances but also to interpolate the rotation, not just the movement.

Moreover, an interpolation of 1 seems high, same as the thereshold of 5: those seem not realistic unless you are not using Unity standard where 1 unit = 1 meter. I would have a 25cm (0.25) interpolation for the movementand a 3 degrees for the rotation. The sync rate of 9 could be enough but in my experience it has to be recomputed based on the packet loss.


问:
What is the difference between ProtoBuf.Serializer and ProtoBuf.Meta.TypeModel in protobuf-net?
As I recently discovered we can serialize/deserialize in protobuf-net using two classes ProtoBuf.Serializer and ProtoBuf.Meta.TypeModel.
For example, let's say we have a custom class that we want to serialize/deserialize:

```<code>[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public string Name { get; set; }
    [ProtoMember(2)]
    public int Age { get; set; }
}
</code>```

We can do it in two ways:

1) Using TypeModel

```<code>TypeModel typeModel = RuntimeTypeModel.Default;
var person1 = new Person
{
    Name = "John",
    Age = 23
};

using (var stream = new MemoryStream())
{
    typeModel.Serialize(stream, person1);
    stream.Position = 0;
    var pesrson2 = typeModel.Deserialize(stream, null, typeof(Person));
}
</code>```

2) Using Serializer (which is the chosen way in most of the tutorials I've seen)

```<code>var person1 = new Person
{
    Name = "John",
    Age = 23
};
using (var stream = new MemoryStream())
{
    Serializer.Serialize(stream, person1);
    stream.Position = 0;
    var pesrson2 = Serializer.Deserialize<Person>(stream);
}
</code>```

What is the difference between these two approaches. How to choose between these two? And what is TypeModel and RuntimeTypeModel in the first place?

答:
All of the Serializer.* methods are generally just  convenience proxies to RuntimeTypeModel.Default.*. There are probably a few minor exceptions - those that don't touch a model at all (processing a "varint", for example)

Essentially, in the 1.* API, there was only one model. v2 added the ability to have concurrent/parallel models describing the same types, and a much richer runtime configuration system - all of this is encapsulated into TypeModel - with the usual implementation being RuntimeTypeModel. Note that you can also load assemblies that contain pre-baked TypeModel implementations, so not every TypeModel is a RuntimeTypeModel.

So; if you're using simple types with attributes : you're fine using Serializer.*. If you've had to do more advanced things with runtime configuration and multiple models - you'll need to keep track of your various TypeModel instances so you know which one to use.

Body:
As I recently discovered we can serialize/deserialize in protobuf-net using two classes ProtoBuf.Serializer and ProtoBuf.Meta.TypeModel.
For example, let's say we have a custom class that we want to serialize/deserialize:

[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public string Name { get; set; }
    [ProtoMember(2)]
    public int Age { get; set; }
}

We can do it in two ways:

1) Using TypeModel

TypeModel typeModel = RuntimeTypeModel.Default;
var person1 = new Person
{
    Name = "John",
    Age = 23
};

using (var stream = new MemoryStream())
{
    typeModel.Serialize(stream, person1);
    stream.Position = 0;
    var pesrson2 = typeModel.Deserialize(stream, null, typeof(Person));
}

2) Using Serializer (which is the chosen way in most of the tutorials I've seen)

var person1 = new Person
{
    Name = "John",
    Age = 23
};
using (var stream = new MemoryStream())
{
    Serializer.Serialize(stream, person1);
    stream.Position = 0;
    var pesrson2 = Serializer.Deserialize<Person>(stream);
}

What is the difference between these two approaches. How to choose between these two? And what is TypeModel and RuntimeTypeModel in the first place?


问:
AWS EC2 Cloudwatch monitoring
Firstly, Appreciate your patience in reading and thinking through this problem I have mentioned here.

I had unique problem on one of my AWS EC2 instances(Ubuntu 14.04), where the instance just goes unreachable through either http or ping. It also locked me out of ssh access. I had to log in to aws console everytime, and reboot the instance manually. As a solution, I have configured cloudwatch monitoring to reboot the instance automatically and send a notification email to me, on any occasion where the system check has failed.

So far, so good.

Now, what I really want is the root cause / reason for instance going unreachable. I assuming that to be a memory issue. I have gone through the get-system-logs, which helped a bit. But, is there anyway, I can configure cloudwatch to send me the fail logs or something similar when it sends me the alert email. Or is there any way, I can alert myself with sufficient log info like - example : memory usage being 80%, network not responding etc- when I instance goes unreachable. I have heard of swap tool, but I am looking for something more generic, just not limited to memory monitoring.

Anything? Anyone has any idea?

答:
I would go old skool and use a script on the server to log to a file

Presumably ( you don't mention this detail in the above ) there is a particular program running on the system that is giving you this problem

Usually system programs store their PID in a file.  Let's assume the file is /var/run/nginx.pid.  You can work this out for your particular system

Write a script to read the PID and record the memory use, for example add this file as "/usr/local/bin/mymemory"

```<code>PID=`cat /var/run/crond.pid`
# the 3 fields are %mem, VSZ and RSS
DATA=`ps uhp $PID| awk '{print $4, $5, $6}'`
NOW=`date --rfc-3339=sec`
echo "$NOW $DATA" >> /var/log/memory.log
</code>```

Add a line to crontab as root

```<code>* * * * * /usr/local/bin/mymemory.log
</code>```

This will make an ever growing file for memory per minute.  I suggest you login once a day and check it, download it if interesting and delete it.
(In a real production context log rotation could be used)

Every time there is a crash the file should contain memory use data

Title: AWS EC2 Cloudwatch monitoring

Body:
I would go old skool and use a script on the server to log to a file

Presumably ( you don't mention this detail in the above ) there is a particular program running on the system that is giving you this problem

Usually system programs store their PID in a file.  Let's assume the file is /var/run/nginx.pid.  You can work this out for your particular system

Write a script to read the PID and record the memory use, for example add this file as "/usr/local/bin/mymemory"

PID=`cat /var/run/crond.pid`
# the 3 fields are %mem, VSZ and RSS
DATA=`ps uhp $PID| awk '{print $4, $5, $6}'`
NOW=`date --rfc-3339=sec`
echo "$NOW $DATA" >> /var/log/memory.log

Add a line to crontab as root

* * * * * /usr/local/bin/mymemory.log

This will make an ever growing file for memory per minute.  I suggest you login once a day and check it, download it if interesting and delete it.
(In a real production context log rotation could be used)

Every time there is a crash the file should contain memory use data


问:
Calling `defineClass` on ClassLoader results in "No matching method found"
I generated a class using ASM and now I'm trying to load this class using the ContextClassLoader:

```<code>(.defineClass classloader (str pkg "." classname) controllerclass 0 (count controllerclass))
</code>```

controllerclass is the Byte-array containing the class. The exception I get is:

```<code>java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader, compiling:(fxml_test.clj:29:1)
Exception in thread "main" java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader, compiling:(fxml_test.clj:29:1)
        at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3700)
        at clojure.lang.Compiler.compile1(Compiler.java:7609)
        at clojure.lang.Compiler.compile(Compiler.java:7676)
        at clojure.lang.RT.compile(RT.java:413)
        at clojure.lang.RT.load(RT.java:458)
        at clojure.lang.RT.load(RT.java:426)
        at clojure.core$load$fn__6548.invoke(core.clj:6046)
        at clojure.core$load.invokeStatic(core.clj:6045)
        at clojure.core$load.doInvoke(core.clj:6029)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invokeStatic(core.clj:5848)
        at clojure.core$compile$fn__6553.invoke(core.clj:6056)
        at clojure.core$compile.invokeStatic(core.clj:6056)
        at clojure.core$compile.invoke(core.clj:6048)
        at user$eval246$fn__255.invoke(form-init5690492012618124781.clj:1)
        at user$eval246.invokeStatic(form-init5690492012618124781.clj:1)
        at user$eval246.invoke(form-init5690492012618124781.clj:1)
        at clojure.lang.Compiler.eval(Compiler.java:7062)
        at clojure.lang.Compiler.eval(Compiler.java:7052)
        at clojure.lang.Compiler.eval(Compiler.java:7052)
        at clojure.lang.Compiler.load(Compiler.java:7514)
        at clojure.lang.Compiler.loadFile(Compiler.java:7452)
        at clojure.main$load_script.invokeStatic(main.clj:278)
        at clojure.main$init_opt.invokeStatic(main.clj:280)
        at clojure.main$init_opt.invoke(main.clj:280)
        at clojure.main$initialize.invokeStatic(main.clj:311)
        at clojure.main$null_opt.invokeStatic(main.clj:345)
        at clojure.main$null_opt.invoke(main.clj:342)
        at clojure.main$main.invokeStatic(main.clj:424)
        at clojure.main$main.doInvoke(main.clj:387)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.lang.Var.applyTo(Var.java:702)
        at clojure.main.main(main.java:37)
Caused by: java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader
        at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:53)
        at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28)
        at clojurefx.controllergen$gen_fx_controller_class.invokeStatic(controllergen.clj:198)
        at clojurefx.controllergen$gen_fx_controller_class.invoke(controllergen.clj:185)
        at clojurefx.fxml$load_fxml_with_controller.invokeStatic(fxml.clj:13)
        at clojurefx.fxml$load_fxml_with_controller.invoke(fxml.clj:12)
        at clojure.lang.AFn.applyToHelper(AFn.java:156)
        at clojure.lang.AFn.applyTo(AFn.java:144)
        at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3695)
        ... 32 more
</code>```

I tried adding type hints, but that had no effect. How do I tell Clojure which method exactly to use? The types definitely match the ones shown in the javadoc of Java 8.

答:
The defineClass method is not even accessible in AppClassLoader since it inherits from URLClassLoader and defineClass is private in that class.

Generally, what you want to do is you want to register the class you compiled as a classloader resource so that it can find it natively using findClass.

Body:
I generated a class using ASM and now I'm trying to load this class using the ContextClassLoader:

(.defineClass classloader (str pkg "." classname) controllerclass 0 (count controllerclass))

controllerclass is the Byte-array containing the class. The exception I get is:

java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader, compiling:(fxml_test.clj:29:1)
Exception in thread "main" java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader, compiling:(fxml_test.clj:29:1)
        at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3700)
        at clojure.lang.Compiler.compile1(Compiler.java:7609)
        at clojure.lang.Compiler.compile(Compiler.java:7676)
        at clojure.lang.RT.compile(RT.java:413)
        at clojure.lang.RT.load(RT.java:458)
        at clojure.lang.RT.load(RT.java:426)
        at clojure.core$load$fn__6548.invoke(core.clj:6046)
        at clojure.core$load.invokeStatic(core.clj:6045)
        at clojure.core$load.doInvoke(core.clj:6029)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invokeStatic(core.clj:5848)
        at clojure.core$compile$fn__6553.invoke(core.clj:6056)
        at clojure.core$compile.invokeStatic(core.clj:6056)
        at clojure.core$compile.invoke(core.clj:6048)
        at user$eval246$fn__255.invoke(form-init5690492012618124781.clj:1)
        at user$eval246.invokeStatic(form-init5690492012618124781.clj:1)
        at user$eval246.invoke(form-init5690492012618124781.clj:1)
        at clojure.lang.Compiler.eval(Compiler.java:7062)
        at clojure.lang.Compiler.eval(Compiler.java:7052)
        at clojure.lang.Compiler.eval(Compiler.java:7052)
        at clojure.lang.Compiler.load(Compiler.java:7514)
        at clojure.lang.Compiler.loadFile(Compiler.java:7452)
        at clojure.main$load_script.invokeStatic(main.clj:278)
        at clojure.main$init_opt.invokeStatic(main.clj:280)
        at clojure.main$init_opt.invoke(main.clj:280)
        at clojure.main$initialize.invokeStatic(main.clj:311)
        at clojure.main$null_opt.invokeStatic(main.clj:345)
        at clojure.main$null_opt.invoke(main.clj:342)
        at clojure.main$main.invokeStatic(main.clj:424)
        at clojure.main$main.doInvoke(main.clj:387)
        at clojure.lang.RestFn.applyTo(RestFn.java:137)
        at clojure.lang.Var.applyTo(Var.java:702)
        at clojure.main.main(main.java:37)
Caused by: java.lang.IllegalArgumentException: No matching method found: defineClass for class sun.misc.Launcher$AppClassLoader
        at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:53)
        at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28)
        at clojurefx.controllergen$gen_fx_controller_class.invokeStatic(controllergen.clj:198)
        at clojurefx.controllergen$gen_fx_controller_class.invoke(controllergen.clj:185)
        at clojurefx.fxml$load_fxml_with_controller.invokeStatic(fxml.clj:13)
        at clojurefx.fxml$load_fxml_with_controller.invoke(fxml.clj:12)
        at clojure.lang.AFn.applyToHelper(AFn.java:156)
        at clojure.lang.AFn.applyTo(AFn.java:144)
        at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3695)
        ... 32 more

I tried adding type hints, but that had no effect. How do I tell Clojure which method exactly to use? The types definitely match the ones shown in the javadoc of Java 8.


问:
Can this be optimized even further using object methods or other way in javascript?
Hello I am trying to remove a user from an array in react javascript the text is given to the function that needs to be deleted and runs through the function below, this.state.users contain objects with properties like:

0: {user_id: "001"  , first_name: "john", last_name: "doe", email:
  "john@doe.com"}

1: {user_id: "002"  , first_name: "mike", last_name: "ty", email:
  "mike@ty.com"}

I'm wondering if this can be optimized even further for large sets of data? or is it already optimized thanks!

```<code>removeUser(text){
  var updatedUsers = this.state.users;
  var i = 0;
  for (i = 0; i< updatedUsers.length;i++)
  {
    if(updatedUsers[i].user_id == text)
      break;
    }
    updatedUsers.splice(i,1);
    this.setState({users: updatedUsers});
  }
}
</code>```

答:
You could use one of redux's approach. </p>

```<code>removeUser(text) {
  const { users } = this.state
  const index = users.findIndex(user => user.user_id === text)

  this.setState({
    users: [
      ...users.slice(0, index), // every user before index
      ...users.slice(index + 1), // every user after index
    ]
  })
}
</code>```

Body:
Hello I am trying to remove a user from an array in react javascript the text is given to the function that needs to be deleted and runs through the function below, this.state.users contain objects with properties like:

0: {user_id: "001"  , first_name: "john", last_name: "doe", email:
  "john@doe.com"}

1: {user_id: "002"  , first_name: "mike", last_name: "ty", email:
  "mike@ty.com"}

I'm wondering if this can be optimized even further for large sets of data? or is it already optimized thanks!

removeUser(text){
  var updatedUsers = this.state.users;
  var i = 0;
  for (i = 0; i< updatedUsers.length;i++)
  {
    if(updatedUsers[i].user_id == text)
      break;
    }
    updatedUsers.splice(i,1);
    this.setState({users: updatedUsers});
  }
}

Body:
You could use one of redux's approach.

removeUser(text) {
  const { users } = this.state
  const index = users.findIndex(user => user.user_id === text)

  this.setState({
    users: [
      ...users.slice(0, index), // every user before index
      ...users.slice(index + 1), // every user after index
    ]
  })
}


问:
scp a bunch of files via bash script: there must be a better way
I currently have the following bash script:

```<code>for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;
</code>```

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).

答:
Does this work with bash?</p>

```<code>scp doneill@server:/mnt/device/folder/numbered_file{16..75}.txt ./
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I currently have the following bash script:

for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).

Body:
Does this work with bash?

scp doneill@server:/mnt/device/folder/numbered_file{16..75}.txt ./


问:
Mutable and Immutable Strings in python
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

```<code>str1='Rohit'
str1.replace('R','M')
</code>```

This gives the output:

```<code>'Mohit'
</code>```

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

```<code>'Rohit'.replace('R','M')
</code>```

This also gives me the output:

```<code>'Mohit'
</code>```

Then what is meant by 'Strings are immutable'?

答:
Strings are known as Immutable in Python (and other languages) because once the initial string is created, none of the function/methods that act on it change it directly, they simply return new strings.

So, in your example

```<code>str1='Rohit'
str1.replace('R','M')
</code>```

After the .replace call, you should try evaluating str1 in your REPL.  It might surprise you to see that str1 still holds the value 'Rohit'.  The .replace returns a new string in which all instances of the given character are replaced with the specified character.  Your REPL will print that returned string, but after that it is lost since you didn't assign it to anything.

Your second example is much the same, but with a string constant instead of a variable like str1.

Title: Mutable and Immutable Strings in python

Body:
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

str1='Rohit'
str1.replace('R','M')

This gives the output:

'Mohit'

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

'Rohit'.replace('R','M')

This also gives me the output:

'Mohit'

Then what is meant by 'Strings are immutable'?

Body:
Strings are known as Immutable in Python (and other languages) because once the initial string is created, none of the function/methods that act on it change it directly, they simply return new strings.

So, in your example

str1='Rohit'
str1.replace('R','M')

After the .replace call, you should try evaluating str1 in your REPL.  It might surprise you to see that str1 still holds the value 'Rohit'.  The .replace returns a new string in which all instances of the given character are replaced with the specified character.  Your REPL will print that returned string, but after that it is lost since you didn't assign it to anything.

Your second example is much the same, but with a string constant instead of a variable like str1.


问:
Pandas data reader update, getting FRED currency exchange rates
So, I was attempting to grab USD/CNY rates from FRED using Pandas with the following code I found on another stack exchange post:

```<code>import pandas.io.data as web
cny = wb.get_data_fred('DEXCHUS')
</code>```

However I got an error-

```<code>ImportError: The pandas.io.data module is moved to a separate package (pandas-datareader). After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import ``from pandas.io import data, wb`` to ``from pandas_datareader import data, wb``.
</code>```

I followed the GitHub instructions to install pandas-datareader and then changed to from pandas.io import data, wb then when I try to run my code I get an error that the module has no get_data_fred.

How can I use the updated package to get the FRED data?

答:
There are a few different ways to get the FRED data. For the generic DataReader call, try (using version 0.5.0):

```<code>import pandas_datareader as pdr
cny = pdr.DataReader("DEXCHUS", "fred")
</code>```

Or, more similar to the syntax you had previously:

```<code>from pandas_datareader import data
cny = data.get_data_fred("DEXCHUS")
</code>```

The data.get_data_fred method just returns the following, which provides a third way to get your data:

```<code># Connect to FRED report and read from connection
cny = data.FredReader("DEXCHUS").read()
</code>```

All results should be identical, however I prefer the more general first call myself.

Body:
So, I was attempting to grab USD/CNY rates from FRED using Pandas with the following code I found on another stack exchange post:

import pandas.io.data as web
cny = wb.get_data_fred('DEXCHUS')

However I got an error-

ImportError: The pandas.io.data module is moved to a separate package (pandas-datareader). After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import ``from pandas.io import data, wb`` to ``from pandas_datareader import data, wb``.

I followed the GitHub instructions to install pandas-datareader and then changed to from pandas.io import data, wb then when I try to run my code I get an error that the module has no get_data_fred.

How can I use the updated package to get the FRED data?

Body:
There are a few different ways to get the FRED data. For the generic DataReader call, try (using version 0.5.0):

import pandas_datareader as pdr
cny = pdr.DataReader("DEXCHUS", "fred")

Or, more similar to the syntax you had previously:

from pandas_datareader import data
cny = data.get_data_fred("DEXCHUS")

The data.get_data_fred method just returns the following, which provides a third way to get your data:

# Connect to FRED report and read from connection
cny = data.FredReader("DEXCHUS").read()

All results should be identical, however I prefer the more general first call myself.


问:
Symfony2 Form Anchors
I have a number of forms on the one page under different tabs

After the form is processed, I would like to return to the same tab as the form was sent from.

Basically, I would like to modify the target_route to go to the current page with an Anchor at the end of the URL. (EG company/view/6#editdetails)

Could someone provide or link to an example that I can put in my controller or into twig?

答:
You may also set this in the template itself as an attribute. See example:</p>

```<code>{{ form_start(form, {attr: { novalidate: "novalidate", class: 'requiredStar', action: '#form' }}) }}
</code>```

Title: Symfony2 Form Anchors

Body:
You may also set this in the template itself as an attribute. See example:

{{ form_start(form, {attr: { novalidate: "novalidate", class: 'requiredStar', action: '#form' }}) }}


问:
Can I write a select function run on different db tables in lambda or Entityframework
I am new to EntityFramework and want to know If it is possible to write a Select statement works on different table. As following.

```<code>public IList<ent_customer> getCustomer()
{
    return db.Customers.Select(a=>new ent_Customers{
         first_name=a.first_name,
         last_name=a.last_Name
    }).ToList();
}
public IList<ent_vendors> getVendors()
{
    return db.Vendors.Select(a=>new ent_vendors{
         first_name=a.first_name,
         last_name=a.last_Name,
         mobile=a.mobile,
         email=a.email
    }).ToList();
}
</code>```

Before I was using one Select,Insert,Update,Delete function for all tables and avoided rewriting of same code in normal 3 tier project.

I tried a lot and google, unfortunately not found any suggestion

Update

Before in general 3tier One SQLEngine Class maintain SQL Queries and Dynamically generates Select,Delete,Edit etc.
If I have a class dal_Product and I need to get product list then Only I was calling

```<code>objProduct.Select();// All Productions
objCustomer.Select();//All Customer No need to write two different queries
obj

on above examle .. SQLEngine were automatically generate two queries
 1- "select *from Product"
 2- "Select *from Customer"

So I was avoiding rewriting for similar queries and functions.
</code>```

Hop know you people understand that I want SQLEngine type of central queries generator based on condition.

Thanks and Advance

答:
To solve your problem you can use a Generic Repository (pattern)
That will take care of the CRUD actions.

Be aware that some people say that having a generic repository pattern is bad practice because it's not what they are meant for.

Body:
I am new to EntityFramework and want to know If it is possible to write a Select statement works on different table. As following.

public IList<ent_customer> getCustomer()
{
    return db.Customers.Select(a=>new ent_Customers{
         first_name=a.first_name,
         last_name=a.last_Name
    }).ToList();
}
public IList<ent_vendors> getVendors()
{
    return db.Vendors.Select(a=>new ent_vendors{
         first_name=a.first_name,
         last_name=a.last_Name,
         mobile=a.mobile,
         email=a.email
    }).ToList();
}

Before I was using one Select,Insert,Update,Delete function for all tables and avoided rewriting of same code in normal 3 tier project.

I tried a lot and google, unfortunately not found any suggestion

Update

Before in general 3tier One SQLEngine Class maintain SQL Queries and Dynamically generates Select,Delete,Edit etc.
If I have a class dal_Product and I need to get product list then Only I was calling

objProduct.Select();// All Productions
objCustomer.Select();//All Customer No need to write two different queries
obj

on above examle .. SQLEngine were automatically generate two queries
 1- "select *from Product"
 2- "Select *from Customer"

So I was avoiding rewriting for similar queries and functions.

Hop know you people understand that I want SQLEngine type of central queries generator based on condition.

Thanks and Advance


问:
mix-blend-mode is broken by 3D transformations on page
I was fiddling with the mix-blend-mode property. Everything works fine until I add something like transform: perspective(100px) or any other 3d transformation anywhere on the page, then it breaks completely. The transformation is applied but the blend mode is gone.

I tested on chrome and firefox and on linux and windows and it's the same everywhere, however on a different computer it worked fine (I don't remember what version of chrome it had and was running ubuntu).

Is that something that can be fixed with CSS or is it possibly just a hardware / GPU drivers issue?

I put background-blend-mode in tags because the mix-blend-mode tag doesn't exist yet, however this property strangely works completely fine and isn't broken by transformations.

Here is a codepen of what I am trying to achieve:
http://codepen.io/vnenkpet/pen/avWvRg

The lightning shouldn't have it's black background flashing with it but should be blended smoothly with the page background.

EDIT:

I have just found out that it actually DOES work in Firefox. Is this therefore a chrome bug? 3D Transforms shouldn't break blend mode as far as I know...

答:
I was having a similar issue, except that applying a mix-blend-mode (multiply) higher on the page broke my transforms lower on the page (using Chrome on Mac). I was able to fix this by applying a z-index rule to the mix-blend-mode div (don't forget to set a position, too).

I'm not entirely sure if this is a bug or if it is expected behavior due to the properties of stacking contexts, though.


问:
d3 zoom and pan with hover functions
I have a graph that has zoom and pan from this example code: (https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172). My graph is almost exactly like that one, except with different data points, and circles noting each data point.

Now I'm trying to allow for a mouseover function that will display the data for each data point when hovering. However, the zoom behavior is taking precedence, and I'm not sure how to switch the behaviors so that the zoom is listening and the mouseover/hover happens (first, maybe?).

I'm trying to use this code sample since it has both the hover and zoom behaviors: (https://bl.ocks.org/lorenzopub/013c0c41f9ffab4d27f860127f79c5f5)

答:
Adding

```<code>d3.select("#rect").style("pointer-events", "all")
</code>```

Have solved my problem.
I think the mouse events where not propagated properly.

Title: d3 zoom and pan with hover functions

Body:
Adding

d3.select("#rect").style("pointer-events", "all")

Have solved my problem.
I think the mouse events where not propagated properly.