问:
How to generate Custom Id in JPA
i want generate Custom Id in JPA it must be primary key of table.
there are many examples to create Custom Id using hibernate like this
i want same implementation but in JPA.The id must be alphanumeric like STAND0001

Thanks.

答:
You can do it using GenericGenerator like this :

```<code> @Entity
public class Client {

    @Id
    @GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
    @GeneratedValue(generator = "client_id")
    @Column(name="client_id")
    private String clientId;
}
</code>```

and the custom generator class (will add prefix to the ID, you can make it do what you like):

```<code>public class ClientIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {

    String prefix = "cli";
    Connection connection = session.connection();

    try {
        Statement statement=connection.createStatement();

        ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");

        if(rs.next())
        {
            int id=rs.getInt(1)+101;
            String generatedId = prefix + new Integer(id).toString();
            return generatedId;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}
</code>```

Title: How to generate Custom Id in JPA

Body:
You can do it using GenericGenerator like this :

 @Entity
public class Client {

    @Id
    @GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
    @GeneratedValue(generator = "client_id")
    @Column(name="client_id")
    private String clientId;
}

and the custom generator class (will add prefix to the ID, you can make it do what you like):

public class ClientIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {

    String prefix = "cli";
    Connection connection = session.connection();

    try {
        Statement statement=connection.createStatement();

        ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");

        if(rs.next())
        {
            int id=rs.getInt(1)+101;
            String generatedId = prefix + new Integer(id).toString();
            return generatedId;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}


来源: stackexchange

问:
Getting all connected nodes in neo4j, using neo4j-driver
I have been developing a javascript wrapper library over neo4j-driver. Though I was facing a little difficulty to obtain all the nodes using the api.

The query does work in neo4j browser, but returns only a single node using neo4j-driver.

```<code>MATCH (n) MATCH (n)-[r]-(p) RETURN p
</code>```

For instance:

Whereas using neo4j-driver:

My question:
Is there another way(another query) that could return me all the connected nodes?

答:
You have an issue with the response you get from neo4j-driver library as the Cypher Query returns all nodes, as per the relation, i.e, MATCH (n) MATCH (n)-[r]-(p) RETURN p, returns all nodes connected to (n).

Check the way you are parsing the result from the neo4j-driver.

ContentLicense: CC BY-SA 3.0

Body:
I have been developing a javascript wrapper library over neo4j-driver. Though I was facing a little difficulty to obtain all the nodes using the api.

The query does work in neo4j browser, but returns only a single node using neo4j-driver.

MATCH (n) MATCH (n)-[r]-(p) RETURN p

For instance:

Whereas using neo4j-driver:

My question:
Is there another way(another query) that could return me all the connected nodes?


问:
Preferred jQuery toolTip?
There are a bunch of jquery tooltip plugins out there.

Which one should I use? and why?

答: I would highly recommend http://craigsworks.com/projects/qtip2/ vs qtip v1.  qtip v1 is no longer maintained, and qtip2 has some great new features.</p>

ContentLicense: CC BY-SA 2.5

Title: Preferred jQuery toolTip?


问:
onBackPressed with fragments and saving fragment state
I want to save fragment state so I use fragment .add() and fragment .show() methods.
the part I use to add fragments in my mainActivity is

```<code>android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content, fragment, CURRENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
</code>```

On back pressed in the fragment and getting back to it the get fragment by tag returns null

```<code>       if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawerLayout.closeDrawers();
            Runnable mPendingRunnable = new Runnable() {
                @Override
                public void run() {
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
                    hideTransactions(CURRENT_TAG);
                    fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG)).commit();
                }
            };
</code>```

although onBackPressed the state of the fragment is right(TAG_PREV returns not null) in the on back pressed method

```<code>@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawers();
        return;
    }
    if (CURRENT_TAG == TAG_HOME) {
        return;
    }
    navItemIndex = 0;
    TAG_PREV = CURRENT_TAG;
    CURRENT_TAG = TAG_HOME;
    loadHomeFragment();
    super.onBackPressed();
}
</code>```

答: addToBackStack saves the transaction, in this case: fragmentTransaction.add(R.id.main_content, fragment, CURRENT_TAG); and when you press back(onBackPressed) you are reversing that transaction.  So that will imply you are removing the previously added fragment.

Body:
I want to save fragment state so I use fragment .add() and fragment .show() methods.
the part I use to add fragments in my mainActivity is

android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content, fragment, CURRENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

On back pressed in the fragment and getting back to it the get fragment by tag returns null

       if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawerLayout.closeDrawers();
            Runnable mPendingRunnable = new Runnable() {
                @Override
                public void run() {
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
                    hideTransactions(CURRENT_TAG);
                    fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG)).commit();
                }
            };

although onBackPressed the state of the fragment is right(TAG_PREV returns not null) in the on back pressed method

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawers();
        return;
    }
    if (CURRENT_TAG == TAG_HOME) {
        return;
    }
    navItemIndex = 0;
    TAG_PREV = CURRENT_TAG;
    CURRENT_TAG = TAG_HOME;
    loadHomeFragment();
    super.onBackPressed();
}


问:
Pattern matching HTTPoison.Response
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end
```

<p>The error I return is:</p>

<pre class="lang-rb prettyprint-override"><code>CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}
</code>```

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

答:
What about a nice and classy pattern matching suggested by HTTPoison docs? Just get rid of exclamation mark and try something like this: </p>

```<code>case HTTPoison.post(stuff) do
  {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
    decoded_stuff = Poison.decode(body) # use another nice case statement here
  {:ok, %HTTPoison.Response{status_code: 404}} ->
    IO.puts "Not found :("
  {:error, %HTTPoison.Error{reason: reason}} ->
    IO.inspect reason
end
</code>```

Title: Pattern matching HTTPoison.Response

Body:
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end

The error I return is:

CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

Body:
What about a nice and classy pattern matching suggested by HTTPoison docs? Just get rid of exclamation mark and try something like this:

case HTTPoison.post(stuff) do
  {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
    decoded_stuff = Poison.decode(body) # use another nice case statement here
  {:ok, %HTTPoison.Response{status_code: 404}} ->
    IO.puts "Not found :("
  {:error, %HTTPoison.Error{reason: reason}} ->
    IO.inspect reason
end


问:
How to add password fields to a default WordPress registration?
I woulrd like to enable users to choose their own passord, but keep a verification email(without reseting password link)?

I am adding an input field for the password in wp-login:

```<code><input type="password" name="user_password" value="" placeholder="Password" id="user_password" class="input" />
</code>```

Than, I have a custom plugin thats sets user's password:

```<code>function myplugin_registration_change_pass( $user_id )

{if ( isset( $_POST['user_password'] ) )
    wp_set_password( $_POST['user_password'], $user_id );}
</code>```

For some reason I keep getting verification email asking the user to set a password.
ANy ideas how I can solve this?

答:
```<code><form name="registerform" id="registerform" action="<?php echo esc_url( site_url( 'wp-login.php?action=register', 'login_post' ) ); ?>" method="post" novalidate="novalidate">
<p>
    <label for="user_login"><?php _e('*First Name') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_login"><?php _e('*Last Name') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>

<p>

    <label for="user_login"><?php _e('*Username') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_email"><?php _e('*Email address') ?><br />
    <input type="email" name="user_email" id="user_email" class="input" value="<?php echo esc_attr( wp_unslash( $user_email ) ); ?>" size="25" /></label>
</p>

<p>
    <label for="user_login"><?php _e('*Choose a password') ?><br />
    <input type="text" name="user_password" id="user_password" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_login"><?php _e('*Confirm password') ?><br />
    <input type="text" name="user_password" id="user_password" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <input type="checkbox" name="vehicle" value="Bike" onclick="return false" checked >I agree to the terms and conditions<br>
</p>
</code>```

When you go to wp-login.php at some point you have these fields for user registration. I added first, last name and password.I also created a small plugin that sets the password from the input field:

```<code>function myplugin_set_pass( $user_id )
{if ( isset( $_POST['user_password'] ) )
wp_set_password( $_POST['user_password'], $user_id );}
add_action('user_register','myplugin_set_pass')
</code>```

With the line line I am saying that on user registration the function from the plugin should be performed. In other words the password should be set. I am not really sure if that is the right track.

Body:
I woulrd like to enable users to choose their own passord, but keep a verification email(without reseting password link)?

I am adding an input field for the password in wp-login:

<input type="password" name="user_password" value="" placeholder="Password" id="user_password" class="input" />

Than, I have a custom plugin thats sets user's password:

function myplugin_registration_change_pass( $user_id )

{if ( isset( $_POST['user_password'] ) )
    wp_set_password( $_POST['user_password'], $user_id );}

For some reason I keep getting verification email asking the user to set a password.
ANy ideas how I can solve this?

Body:
<form name="registerform" id="registerform" action="<?php echo esc_url( site_url( 'wp-login.php?action=register', 'login_post' ) ); ?>" method="post" novalidate="novalidate">
<p>
    <label for="user_login"><?php _e('*First Name') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_login"><?php _e('*Last Name') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>

<p>

    <label for="user_login"><?php _e('*Username') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_email"><?php _e('*Email address') ?><br />
    <input type="email" name="user_email" id="user_email" class="input" value="<?php echo esc_attr( wp_unslash( $user_email ) ); ?>" size="25" /></label>
</p>

<p>
    <label for="user_login"><?php _e('*Choose a password') ?><br />
    <input type="text" name="user_password" id="user_password" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <label for="user_login"><?php _e('*Confirm password') ?><br />
    <input type="text" name="user_password" id="user_password" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="25" /></label>
</p>
<p>
    <input type="checkbox" name="vehicle" value="Bike" onclick="return false" checked >I agree to the terms and conditions<br>
</p>

When you go to wp-login.php at some point you have these fields for user registration. I added first, last name and password.I also created a small plugin that sets the password from the input field:

function myplugin_set_pass( $user_id )
{if ( isset( $_POST['user_password'] ) )
wp_set_password( $_POST['user_password'], $user_id );}
add_action('user_register','myplugin_set_pass')

With the line line I am saying that on user registration the function from the plugin should be performed. In other words the password should be set. I am not really sure if that is the right track.


问:
Search text in particular column and retrieve data from another column in excel using C#
I have an Excel file of 20 columns and there are about 150 records. I need to search for a particular string in a particular column with header "DESCRIPTION"(usually column b). The search string and column header values come from an INI File. After the search is found, I need to copy the value in column J (again from INI file) to the output file.

I am new to C#. Can somebody help me here. I tried Range.Find but I got confused.

答:
You can use free version of GemBox.Spreadsheet to search for a text in both XLS and XLSX file formats. Also regarding the INI file, you can use MadMilkman.Ini.

Here is an example that you could try:

```<code>// Load INI file.
IniFile ini = new IniFile();
ini.Load("Sample.ini");

// Get INI values.
string header = ini.Sections["SampleSection"].Keys["ColumnHeaderValue"].Value;
string search = ini.Sections["SampleSection"].Keys["SearchTextValue"].Value;
string j = ini.Sections["SampleSection"].Keys["JColumnValue"].Value;

// Load XLSX file.
ExcelFile excel = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet sheet = excel.Worksheets[0];

// Find column header value in first row.
ExcelColumn searchColumn = sheet.Rows[0].Cells
    .First(cell => cell.ValueType == CellValueType.String && cell.StringValue == header)
    .Column;

// Find search value in column.
int r, c;
searchColumn.Cells.FindText(search, false, false, out r, out c);
ExcelCell searchCell = sheet.Cells[r, c];

// Get cell from column "J" that is in the same row as cell that has search text.
ExcelCell jCell = sheet.Cells[r, ExcelColumnCollection.ColumnNameToIndex("J")];
// Set cell value.
jCell.Value = j;

// Save XLSX file.
excel.Save("Sample.xlsx");
</code>```

Body:
You can use free version of GemBox.Spreadsheet to search for a text in both XLS and XLSX file formats. Also regarding the INI file, you can use MadMilkman.Ini.

Here is an example that you could try:

// Load INI file.
IniFile ini = new IniFile();
ini.Load("Sample.ini");

// Get INI values.
string header = ini.Sections["SampleSection"].Keys["ColumnHeaderValue"].Value;
string search = ini.Sections["SampleSection"].Keys["SearchTextValue"].Value;
string j = ini.Sections["SampleSection"].Keys["JColumnValue"].Value;

// Load XLSX file.
ExcelFile excel = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet sheet = excel.Worksheets[0];

// Find column header value in first row.
ExcelColumn searchColumn = sheet.Rows[0].Cells
    .First(cell => cell.ValueType == CellValueType.String && cell.StringValue == header)
    .Column;

// Find search value in column.
int r, c;
searchColumn.Cells.FindText(search, false, false, out r, out c);
ExcelCell searchCell = sheet.Cells[r, c];

// Get cell from column "J" that is in the same row as cell that has search text.
ExcelCell jCell = sheet.Cells[r, ExcelColumnCollection.ColumnNameToIndex("J")];
// Set cell value.
jCell.Value = j;

// Save XLSX file.
excel.Save("Sample.xlsx");


问:
support unknown number of levels of hierarchy in jqGrid
I'm using jqGrid and I need to display a tree grid with unknown number of levels(subgrids).

There is an example of hierarchical grid in jqGrid demonstrations but it's good only if you know the number of levels in advance, in this case it's supporting 2 levels only.

Here is the code:jqGrid subgrid example

Any idea how to support unknown number of tree nodes ahead? i.e., sometimes it's may be 2 levels, sometimes 1(only root) level, sometimes 4 levels and so on...

Thank you

答:
I am doing this.</p>

```<code>$("#TopLevelGrid").jqGrid({
    ...
    subGrid: true,
    subGridRowExpanded: expandScript,
    ...
});
// Append information about the level to the TopLevelGrid html-table element
$("#TopLevelGrid").data("currentLevelId", 1);
$("#TopLevelGrid").addClass("MyGrid");      // Ensure that html-table has class MyGrid

function expandScript(parentDivId, parentRowId)
{
        ...
        var parentTable = $("#" + parentDivId").closest("table.MyGrid");
        var parentLevelId = $(parentTable).data("currentLevelId");

        var currentLevelId = parentLevelId + 1;                     // calculate the ID of the current level
        var currentLevelHasChildLevel = true;                       // calculate if the current level has a childLevel
        // Append a table-element which will hold the new grid;     // the same as the jqGrid-subgrid example
        $('#' + parentDivId).append('<table class=\"MyGrid\" id=\"ChildGrid_' + currentLevelId + '\"></table><div id=\"Pager_ChildGrid_' + currentLevelId + '\"></div><br />');
        $('#ChildGrid_' + currentLevelId ').jqGrid({
            ...
            subGrid: currentLevelHasChildLevel,
            subGridRowExpanded: expandScript,                       // recursive call to expandScript function
            ...
        });
        // Save the currentLevelId as custom-data element bound to the html-table element which will also hold the child-grid
        $("#ChildGrid_" + currentLevelId).data("currentlevelid", currentLevelId);
        ...
}
</code>```

Body:
I am doing this.

$("#TopLevelGrid").jqGrid({
    ...
    subGrid: true,
    subGridRowExpanded: expandScript,
    ...
});
// Append information about the level to the TopLevelGrid html-table element
$("#TopLevelGrid").data("currentLevelId", 1);
$("#TopLevelGrid").addClass("MyGrid");      // Ensure that html-table has class MyGrid

function expandScript(parentDivId, parentRowId)
{
        ...
        var parentTable = $("#" + parentDivId").closest("table.MyGrid");
        var parentLevelId = $(parentTable).data("currentLevelId");

        var currentLevelId = parentLevelId + 1;                     // calculate the ID of the current level
        var currentLevelHasChildLevel = true;                       // calculate if the current level has a childLevel
        // Append a table-element which will hold the new grid;     // the same as the jqGrid-subgrid example
        $('#' + parentDivId).append('<table class=\"MyGrid\" id=\"ChildGrid_' + currentLevelId + '\"></table><div id=\"Pager_ChildGrid_' + currentLevelId + '\"></div><br />');
        $('#ChildGrid_' + currentLevelId ').jqGrid({
            ...
            subGrid: currentLevelHasChildLevel,
            subGridRowExpanded: expandScript,                       // recursive call to expandScript function
            ...
        });
        // Save the currentLevelId as custom-data element bound to the html-table element which will also hold the child-grid
        $("#ChildGrid_" + currentLevelId).data("currentlevelid", currentLevelId);
        ...
}


问:
android - Activity still leaks even instance is set to null in onDestroy() method
I am stuck with memory leak in my main Activity (NavigationActivity)

```<code>public static NavigationActivity navigationActivity;

public static NavigationActivity getNavigationActivity() {
    return navigationActivity;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation);

    navigationActivity = NavigationActivity.this;

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (navigationActivity != null) {
        navigationActivity = null;
    }
}
</code>```

Where does it leak? and how do I fix it? Any help would be appreciated. Thank you very much.

I'm using leak canary and this is the leak

答:
You cleared up the reference inside your activity. But class ContactsCompletionView still has strong reference to your activity. The best way to avoid this leak is not to expose link to your activity.

But if you really need this you can use WeakReference to your Activity. So your method getNavigationActivity() might looks like this:

```<code>public static WeakReference<NavigationActivity> navigationActivityRef;
{
    public static WeakReference<NavigationActivity> getNavigationActivity() {
      if(navigationActivityRef == null) {
          navigationActivityRef = new WeakReference<>(this);
      }
      return navigationActivityRef;
}
</code>```

Body:
I am stuck with memory leak in my main Activity (NavigationActivity)

public static NavigationActivity navigationActivity;

public static NavigationActivity getNavigationActivity() {
    return navigationActivity;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation);

    navigationActivity = NavigationActivity.this;

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (navigationActivity != null) {
        navigationActivity = null;
    }
}

Where does it leak? and how do I fix it? Any help would be appreciated. Thank you very much.

I'm using leak canary and this is the leak

Body:
You cleared up the reference inside your activity. But class ContactsCompletionView still has strong reference to your activity. The best way to avoid this leak is not to expose link to your activity.

But if you really need this you can use WeakReference to your Activity. So your method getNavigationActivity() might looks like this:

public static WeakReference<NavigationActivity> navigationActivityRef;
{
    public static WeakReference<NavigationActivity> getNavigationActivity() {
      if(navigationActivityRef == null) {
          navigationActivityRef = new WeakReference<>(this);
      }
      return navigationActivityRef;
}


问:
Using IObservable (Rx) as a INotifyCollectionChanged Replacement for MVVM?
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

```<code>using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}
</code>```

答: To my mind that is not a suitable usage of Rx. An Rx Observable is a stream of 'events' that you can subscribe to. You can react to these events in your View Model, for example adding them to an ObservableCollection which is bound to your view. However, an Observable cannot be used to represent a fixed set of items which you add / remove items from.</p>

Body:
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}


问:
Python- writing json file as list of dictionaries
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

```<code>dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))
</code>```

For example, it currently prints like this:

```<code>[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
</code>```

I would like it to print like this:

```<code>[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]
</code>```

答:
Update Actually what you have is a list of dictionaries. When you want to add more elements you need to remove the [] around the dictionary.

To slve your specific problem you want to use indent=0. Also consider using json.dump directly.

```<code>import json

l=[]

dct={"name": 'name',
    "cuisine": 'cuisine',
    "price-range": 'price',
    "address": 'address',
    "rating": 'rating',
    "reviews": 'score',
    "district": 'district',
    "url": 'link'
    }

l.append(dct)

with open('openrice_data.json', 'w') as file:
    json.dump(l,file,indent=0)
</code>```

Output:

```<code>[
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
}
]
</code>```

Continuing

To add more elements you need to do this:

```<code># Load json to list
with open('openrice_data.json') as f:
    l = json.load(f)

# A new dict
dct2={"name": 'name',
    "cuisine": 'cuisine',
    "price-range": 'price',
    "address": 'address',
    "rating": 'rating',
    "reviews": 'score',
    "district": 'district',
    "url": 'link'
    }

# Append new dict
l.append(dct2)

with open('openrice_data.json', 'w') as file:
    json.dump(l,file,indent=0)
</code>```

Output now contains a list with 2 dicts.

```<code>[
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
},
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
}
]
</code>```

Body:
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))

For example, it currently prints like this:

[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]

I would like it to print like this:

[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]

Body:
Update Actually what you have is a list of dictionaries. When you want to add more elements you need to remove the [] around the dictionary.

To slve your specific problem you want to use indent=0. Also consider using json.dump directly.

import json

l=[]

dct={"name": 'name',
    "cuisine": 'cuisine',
    "price-range": 'price',
    "address": 'address',
    "rating": 'rating',
    "reviews": 'score',
    "district": 'district',
    "url": 'link'
    }

l.append(dct)

with open('openrice_data.json', 'w') as file:
    json.dump(l,file,indent=0)

Output:

[
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
}
]

Continuing

To add more elements you need to do this:

# Load json to list
with open('openrice_data.json') as f:
    l = json.load(f)

# A new dict
dct2={"name": 'name',
    "cuisine": 'cuisine',
    "price-range": 'price',
    "address": 'address',
    "rating": 'rating',
    "reviews": 'score',
    "district": 'district',
    "url": 'link'
    }

# Append new dict
l.append(dct2)

with open('openrice_data.json', 'w') as file:
    json.dump(l,file,indent=0)

Output now contains a list with 2 dicts.

[
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
},
{
"name": "name",
"cuisine": "cuisine",
"price-range": "price",
"address": "address",
"rating": "rating",
"reviews": "score",
"district": "district",
"url": "link"
}
]


问:
Checking a file for matching string
I'm writing a program that allows multiple users to create, save, and load data to files. I'm running into an issue where I can't find seem to figure out a logic that doesn't allow users to create duplicate file names.

Here is the important working part of my code thus far, but where my issues are. The variable user is assigned at the launch of my program where the user must enter their username and password.

```<code>else if (selection == 6)
{
    int i;
    int d;
    printf("Please enter a file name: ");
    scanf("%s", filename);
    newFile = fopen(filename, "a+");
    Record = fopen("records.txt", "a+");
    fprintf(Record, "%s %s\n", user, filename);
    for (i = 0; i < icount; i++)
    {

        fprintf(newFile, "%d ", ints[i]);
    }
    for (d = 0; d < dcount; d++)
    {

        fprintf(newFile, "%lf ", doubles[d]);
    }
    fclose(Record);
    fclose(newFile);

}
else if (selection == 7)
{
    printf("Please enter a file name: ");
    scanf("%s", filename);
    Record = fopen("records.txt", "a+");
    while (fscanf(Record, "%s %s", curuser, curfile) != EOF)
    {
        if (strcmp(user, curuser) == 0 && strcmp(filename, curfile) == 0)
        {
            int c;
            //fopen(newFile, "a+");
            newFile = fopen(filename, "a+");
            if (newFile) {
                while ((c = getc(newFile)) != EOF)
                {
                    putchar(c);

                }
                fclose(newFile);
                break;
            }

        }
        else
        {
            printf("You don't have access to this file.\n");
            break;
        }
    }
}
</code>```

Somewhere in selection 6, I'm trying to say in code, "Okay user, enter a file, unless the name already exists." What I tried was

```<code>while (fscanf(Record, "%s %s", curuser, curfile) != EOF)
{
    if  (strcmp(curfile, filename) == 0)
    {
        break;
    }
    else
    {
        fprintf(Record, "%s %s\n", user, filename);
        fclose(Record);
    }
}
</code>```

and I'm unable to figure out why this won't work. I tried placing this code right below Record file declaration.

I think the issue may be that when the record file is empty, the != EOF line is causing it to break, but I also can't figure out a way to initially get one user and filename in the record before probing the rest of the users for their filenames. Any guidance in the right direction would be appreciated!

答:
I think you can solve your problem by cutting the while loop in several parts:

do the fscanf

check for end of file

check for "user found"

And finally,

write user if not previously in file.

I would have written something like:

```<code>int record_found = 0;
int scanf_res;

while (1)
{
    /* do the fscanf */
    scanf_res = fscanf(Record, "%s %s", curuser, curfile);

    /* test for end of file */
    if (EOF == scanf_res)
    {
        /* end of file reached */
        break;
    }

    /* if fscanf has mado 2 conversion AND
       filename is curfile */
    if ((2 == scanf_res) && (strcmp(curfile, filename) == 0))
    {
        record_found = 1;
        break;
    }
}

if (!record_found)
{
    /* add user if needed */
    fprintf(Record, "%s %s\n", user, filename);
}

/* and close file in all cases */
fclose(Record);
</code>```

Title: Checking a file for matching string

Body:
I'm writing a program that allows multiple users to create, save, and load data to files. I'm running into an issue where I can't find seem to figure out a logic that doesn't allow users to create duplicate file names.

Here is the important working part of my code thus far, but where my issues are. The variable user is assigned at the launch of my program where the user must enter their username and password.

else if (selection == 6)
{
    int i;
    int d;
    printf("Please enter a file name: ");
    scanf("%s", filename);
    newFile = fopen(filename, "a+");
    Record = fopen("records.txt", "a+");
    fprintf(Record, "%s %s\n", user, filename);
    for (i = 0; i < icount; i++)
    {

        fprintf(newFile, "%d ", ints[i]);
    }
    for (d = 0; d < dcount; d++)
    {

        fprintf(newFile, "%lf ", doubles[d]);
    }
    fclose(Record);
    fclose(newFile);

}
else if (selection == 7)
{
    printf("Please enter a file name: ");
    scanf("%s", filename);
    Record = fopen("records.txt", "a+");
    while (fscanf(Record, "%s %s", curuser, curfile) != EOF)
    {
        if (strcmp(user, curuser) == 0 && strcmp(filename, curfile) == 0)
        {
            int c;
            //fopen(newFile, "a+");
            newFile = fopen(filename, "a+");
            if (newFile) {
                while ((c = getc(newFile)) != EOF)
                {
                    putchar(c);

                }
                fclose(newFile);
                break;
            }

        }
        else
        {
            printf("You don't have access to this file.\n");
            break;
        }
    }
}

Somewhere in selection 6, I'm trying to say in code, "Okay user, enter a file, unless the name already exists." What I tried was

while (fscanf(Record, "%s %s", curuser, curfile) != EOF)
{
    if  (strcmp(curfile, filename) == 0)
    {
        break;
    }
    else
    {
        fprintf(Record, "%s %s\n", user, filename);
        fclose(Record);
    }
}

and I'm unable to figure out why this won't work. I tried placing this code right below Record file declaration.

I think the issue may be that when the record file is empty, the != EOF line is causing it to break, but I also can't figure out a way to initially get one user and filename in the record before probing the rest of the users for their filenames. Any guidance in the right direction would be appreciated!

Body:
I think you can solve your problem by cutting the while loop in several parts:

do the fscanf

check for end of file

check for "user found"

And finally,

write user if not previously in file.

I would have written something like:

int record_found = 0;
int scanf_res;

while (1)
{
    /* do the fscanf */
    scanf_res = fscanf(Record, "%s %s", curuser, curfile);

    /* test for end of file */
    if (EOF == scanf_res)
    {
        /* end of file reached */
        break;
    }

    /* if fscanf has mado 2 conversion AND
       filename is curfile */
    if ((2 == scanf_res) && (strcmp(curfile, filename) == 0))
    {
        record_found = 1;
        break;
    }
}

if (!record_found)
{
    /* add user if needed */
    fprintf(Record, "%s %s\n", user, filename);
}

/* and close file in all cases */
fclose(Record);


问:
What does Bad EIP value error means?
I've been writing some kernel module recently. For some modules everytime i insert them or remove them a huge kernel trace is shown on screen. The errors are somewhat like

```<code> ERROR: Bad EIP value.
</code>```

or

```<code>ModuleName is tainted.
</code>```

What does this imply. Any help is appreciated.

答:
The Extended Instruction Pointer exists in x86 processors, but is somehow related to a missing WiFi driver, it seems:

Yesterday I could not reach this site and read your reactions, so I
  experimented with several Linux versions: Xubuntu, Slacko-Puppy 5,4
  Firefox ,Puppy Akita Beta and LinuxMintMaya. And with all the same
  result, i.e. no result,

But in the last install - LinuxMintMaya - I discovered the problem,
  which is be found here: http://www.linuxmint.com/rel_maya.php  It
  tells:

Boot hangs on systems using b43 wireless cards

So after entering this command

Code: sudo apt-get install firmware-b43-installer

LinuxMintMaya works.

To boot, the Mint page says:

An upstream issue in the kernel prevents Linux Mint 13 from booting on
  computers with b43 wireless cards. If you're in this situation, try
  the following:

To boot the live DVD, choose the "Compatibility mode" or add the
  following kernel argument to the boot options: b43.blacklist=yes
  Install Linux Mint on the hard drive If not present already, in Grub,
  modify the boot options to add: b43.blacklist=yes Install the b43
  firmware on the system

Title: What does Bad EIP value error means?

Body:
I've been writing some kernel module recently. For some modules everytime i insert them or remove them a huge kernel trace is shown on screen. The errors are somewhat like

 ERROR: Bad EIP value.

or

ModuleName is tainted.

What does this imply. Any help is appreciated.


问:
Associativity, Precedence and F# Pipe-forward
The F# pipe-forward can be expressed as:

```<code>let (|>) x f = f x
</code>```

For example:

```<code>let SimpleFunction (a : typeA) (b : typeB) (c : typeC)=
    printf "OK."

// No problem here.
SimpleFunction a b c

// Using pipe-forward
c |> SimpleFunction a b
// No problem here. Interpreted as the same as above.
</code>```

However, according to the documentation, the pipe-forward operator is left-associative.

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/

So, I expected the pipe-forward statement:

```<code>// Original Expression
c |> SimpleFunction a b

// to be equivalent to:
(c |> SimpleFunction) a b

// Which is equivalent to:
SimpleFunction c a b
// Error!! SimpleFunction takes typeA, then typeB, then typeC.
</code>```

Why does the compiler not "interpret" the pipe-forward expression as the error expression? Do I have any confusion about the operator precedence/associativity?

Additional Sources:

http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/

What is associativity of operators and why is it important?

https://en.wikipedia.org/wiki/Operator_associativity

答:
Functions are curried by default, you original expression is actually like this:

c |> (SimpleFunction a b) which then becomes (SimpleFunction a b) c. For this to work function application will have to have precedence.

Body:
The F# pipe-forward can be expressed as:

let (|>) x f = f x

For example:

let SimpleFunction (a : typeA) (b : typeB) (c : typeC)=
    printf "OK."

// No problem here.
SimpleFunction a b c

// Using pipe-forward
c |> SimpleFunction a b
// No problem here. Interpreted as the same as above.

However, according to the documentation, the pipe-forward operator is left-associative.

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/

So, I expected the pipe-forward statement:

// Original Expression
c |> SimpleFunction a b

// to be equivalent to:
(c |> SimpleFunction) a b

// Which is equivalent to:
SimpleFunction c a b
// Error!! SimpleFunction takes typeA, then typeB, then typeC.

Why does the compiler not "interpret" the pipe-forward expression as the error expression? Do I have any confusion about the operator precedence/associativity?

Additional Sources:

http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/

What is associativity of operators and why is it important?

https://en.wikipedia.org/wiki/Operator_associativity


问:
A 'pythonic' way to generate a seasonal dataframe from a pandas timeseries dataframe
I have a pandas dataframe that captures values over a timespan (maybe monthly over years,  or daily over years, or daily over months). There is no guarantee that the time series is continuous (some months might be missing in a year)

```<code>""" no guarantee that this index will have an entry for every month of the time range!"""
dates = pd.date_range('1/1/2015', periods=36, freq='M')
df = pd.DataFrame(index = dates)
df['value'] = df.index.year * 0.1 + df.index.month * 0.05
df.plot()
</code>```

It can give me a simple time series plot

But what I want to make is a 'seasonal' plot.  This would display each year's data as a different line on the same index of months.   As a simple display:

```<code>import numpy as np
index = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
df = pd.DataFrame(index = index)
df[2015] = np.arange(12)*0.4+1
df[2016] = np.arange(12)*0.35+1.4
df[2017] = np.arange(12)*0.5+1.2

df.plot()
</code>```

I'm looking for a 'pythonic' or elegant way to do this operation.  My attempts to transform have been incredibly gross, spaghetti, garbage code.  I am sure there must be some tidy approach using pandas/python to display this transformation efficiently and cleanly  In particular, I want to find an abstracted way to do this, so that I can generalize it to making charts showing "seasonality" of days across a month, etc.

To start with, I'm not even sure what is a good index to build and base this chart off of.

答:
You can use DatetimeIndex.strftime and DatetimeIndex.year and for correct ordering use sorted CategoricalIndex, last reshape by pivot:

```<code>c = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df = pd.pivot(index=pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c),
              columns=df.index.year,
              values=df['value'])
print (df)

       2015    2016    2017
Jan  201.55  201.65  201.75
Feb  201.60  201.70  201.80
Mar  201.65  201.75  201.85
Apr  201.70  201.80  201.90
May  201.75  201.85  201.95
Jun  201.80  201.90  202.00
Jul  201.85  201.95  202.05
Aug  201.90  202.00  202.10
Sep  201.95  202.05  202.15
Oct  202.00  202.10  202.20
Nov  202.05  202.15  202.25
Dec  202.10  202.20  202.30

df.plot()
</code>```

Another solution is create new columns:

```<code>df['months'] = pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c)
df['years'] = df.index.year
df = df.pivot(index='months', columns='years',values='value')
</code>```

Body:
I have a pandas dataframe that captures values over a timespan (maybe monthly over years,  or daily over years, or daily over months). There is no guarantee that the time series is continuous (some months might be missing in a year)

""" no guarantee that this index will have an entry for every month of the time range!"""
dates = pd.date_range('1/1/2015', periods=36, freq='M')
df = pd.DataFrame(index = dates)
df['value'] = df.index.year * 0.1 + df.index.month * 0.05
df.plot()

It can give me a simple time series plot

But what I want to make is a 'seasonal' plot.  This would display each year's data as a different line on the same index of months.   As a simple display:

import numpy as np
index = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
df = pd.DataFrame(index = index)
df[2015] = np.arange(12)*0.4+1
df[2016] = np.arange(12)*0.35+1.4
df[2017] = np.arange(12)*0.5+1.2

df.plot()

I'm looking for a 'pythonic' or elegant way to do this operation.  My attempts to transform have been incredibly gross, spaghetti, garbage code.  I am sure there must be some tidy approach using pandas/python to display this transformation efficiently and cleanly  In particular, I want to find an abstracted way to do this, so that I can generalize it to making charts showing "seasonality" of days across a month, etc.

To start with, I'm not even sure what is a good index to build and base this chart off of.

Body:
You can use DatetimeIndex.strftime and DatetimeIndex.year and for correct ordering use sorted CategoricalIndex, last reshape by pivot:

c = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df = pd.pivot(index=pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c),
              columns=df.index.year,
              values=df['value'])
print (df)

       2015    2016    2017
Jan  201.55  201.65  201.75
Feb  201.60  201.70  201.80
Mar  201.65  201.75  201.85
Apr  201.70  201.80  201.90
May  201.75  201.85  201.95
Jun  201.80  201.90  202.00
Jul  201.85  201.95  202.05
Aug  201.90  202.00  202.10
Sep  201.95  202.05  202.15
Oct  202.00  202.10  202.20
Nov  202.05  202.15  202.25
Dec  202.10  202.20  202.30

df.plot()

Another solution is create new columns:

df['months'] = pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c)
df['years'] = df.index.year
df = df.pivot(index='months', columns='years',values='value')

ContentLicense: CC BY-SA 4.0


问:
Java.Lang.IllegalException At Setdestinationfolder path while downloading image

IllegalException at destination folder path

Here is my code am downloading gif images from url

```<code>@Override
    protected Void doInBackground(String... strings) {
        String uRl = strings[0];
        DownloadManager mgr = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setTitle("Downloading giphy file")
                .setDestinationInExternalPublicDir("/IslamicGif", "fileName.gif");
        mgr.enqueue(request);
        return null;
    }
</code>```

答:
Actually i have not manage the directory path perfectly so the error comes its
 working with this path now. </p>

```<code> File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");
    if (!mydownload.exists()){
        mydownload.mkdir();
    }
    String url = sUrl[0];
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
</code>```

Body:
IllegalException at destination folder path

Here is my code am downloading gif images from url

@Override
    protected Void doInBackground(String... strings) {
        String uRl = strings[0];
        DownloadManager mgr = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setTitle("Downloading giphy file")
                .setDestinationInExternalPublicDir("/IslamicGif", "fileName.gif");
        mgr.enqueue(request);
        return null;
    }

Body:
Actually i have not manage the directory path perfectly so the error comes its
 working with this path now.

 File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");
    if (!mydownload.exists()){
        mydownload.mkdir();
    }
    String url = sUrl[0];
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);


问:
Find unused variables and functions in a MATLAB-Simulink project
I have a complex MATLAB-Simulink project involving many m-files and mdl-files. Some m-files define variables that are used in other m-files (bad design, I know, but it is legacy code). There are also functions that aren't used anymore.

I need an automatic way to find unused variables and functions so that I can delete them and make the whole thing a little less complex. Ideally I should have a script/tool which takes as input the name of root directory of the project, scans all the files in subdirectories, and outputs all the variables and functions that are not used in any m-file or mdl-file.

I know that I can find variables that are not used in mdl-files (see Tips and Tricks - Tracking Variables in a Simulink Model). I would like to apply that method to all the files in the project.

My idea to detect variables not used in m-files is to temporarily combine all the m-files into a single file and run mlint on it. Any better ideas?

答:
Instead of going through the tedious (and potentially error-prone) task of pasting all of your m-files into one to run MLINT, you have a few other options...

If you have all your files in one folder, the simplest approach is to go to the Current Folder browser, click the Actions button , and then select Reports > Code Analyzer Report.

This will open a new window displaying the MLINT results for each m-file in the current directory:

If you would rather automate the process using a script instead of having to click through menu options, there are a couple of submissions on the MathWorks File Exchange (here and here) that appear to work recursively on a directory structure as opposed to just a single directory.

In additional, here is some sample code that will do what you want for a single directory:

```<code>dirData = dir;                 %# Get data on the current directory contents
fileIndex = ~[dirData.isdir];                 %# Get an index for the files
fileNames = {dirData(fileIndex).name};        %# Get the file names
[~,~,ext] = cellfun(@fileparts,fileNames,...  %# Get the file extensions
                    'UniformOutput',false);
mFileIndex = strcmp(ext,'.m');                %# Get an index for the m-files
cellfun(@mlint,fileNames(mFileIndex));        %# Run MLINT on each m-file
</code>```

You could extend the collection of file names (and paths) in this way to operate recursively on a directory tree, then run MLINT on the resulting set of files you collect.

Body:
Instead of going through the tedious (and potentially error-prone) task of pasting all of your m-files into one to run MLINT, you have a few other options...

If you have all your files in one folder, the simplest approach is to go to the Current Folder browser, click the Actions button , and then select Reports > Code Analyzer Report.

This will open a new window displaying the MLINT results for each m-file in the current directory:

If you would rather automate the process using a script instead of having to click through menu options, there are a couple of submissions on the MathWorks File Exchange (here and here) that appear to work recursively on a directory structure as opposed to just a single directory.

In additional, here is some sample code that will do what you want for a single directory:

dirData = dir;                 %# Get data on the current directory contents
fileIndex = ~[dirData.isdir];                 %# Get an index for the files
fileNames = {dirData(fileIndex).name};        %# Get the file names
[~,~,ext] = cellfun(@fileparts,fileNames,...  %# Get the file extensions
                    'UniformOutput',false);
mFileIndex = strcmp(ext,'.m');                %# Get an index for the m-files
cellfun(@mlint,fileNames(mFileIndex));        %# Run MLINT on each m-file

You could extend the collection of file names (and paths) in this way to operate recursively on a directory tree, then run MLINT on the resulting set of files you collect.


问:
Is it possible to create a 3D photo from a normal photo?
If I have understand well, 3D 360 photos are created from a panorama photo, so I guess it should be possible to create a 3D photo (non 360) from a normal photo. But how? I did not find anything in Google! Any idea of what should I search??

So far, if nothing available (I don't think so), I'll try to duplicate the same photo in each eye. One of the pictures a little bit moved to the right, and the other one moved a little bit to the left. But I think the distortion algorithm is much more complicated.

Note: I'm also receiving answers here: https://plus.google.com/u/0/115463690952639951338/posts/4KdqFcqUTT9

答: 3d photos can't be taken by normal but you can take 360 photos with normal camera ..... There are many apps via which you can do this ..... Also there are many algorithms to do it programmatically</p>


问:
onProgressUpdate is not being called android
I have this GetAllUsers(); in onCreate and I have this

```<code>private void GetAllUsers() {
  (new LoadingUsers(this)).execute();
}
</code>```

Then I have this

private class LoadingUsers extends AsyncTask < Void, Integer, String > {
  String TAG = getClass().getSimpleName();
  AlertDialog.Builder builderSingle;
  ArrayAdapter < String > arrayAdapter;@
  SuppressWarnings("unused")
  Context mContext;

  public LoadingUsers(Context context) {
    super();

    mContext = context;

  }

  protected void onPreExecute() {
    //            prgDialog.show();
    //            builderSingle = new
    Log.d(TAG + " PreExceute", "On pre Exceute......");
  }

  protected String doInBackground(Void...arg0) {

    Log.d(TAG + " DoINBackGround", "On doInBackground...");
    return null;
  }

  protected void onProgressUpdate(Integer...a) {
    super.onProgressUpdate(a);
    Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);

  }

  protected void onPostExecute(String result) {
    //            prgDialog.hide();
    Log.d(TAG + " onPostExecute", "" + result);

    MainActivity.this.pd.dismiss();
  }
}```
</div>
</div>
</p>

<p>I wanted to put a <code>builderSingle = new AlertDialog.Builder(MainActivity.this);</code> inside the <code>protected void onProgressUpdate(Integer... a) {</code> which has a <code>AsyncHttpClient client = new AsyncHttpClient();</code> but unfortunately the onProgressUpdate does not get called at all. I know this because the log does not show. All other <code>log</code> are showing except the <code>onProgressUpdate</code> I have also have </p>

```@
Override
protected void onDestroy() {
  super.onDestroy();
  Log.i(TAG, "On Destroy .....");
}

@
Override
protected void onPause() {
  super.onPause();
  Log.i(TAG, "On Pause .....");
}

@
Override
protected void onRestart() {
  super.onRestart();
  Log.i(TAG, "On Restart .....");
}

@
Override
protected void onResume() {
  super.onResume();
  Log.i(TAG, "On Resume .....");
}

@
Override
protected void onStart() {
  super.onStart();
  Log.i(TAG, "On Start .....");
}

@
Override
protected void onStop() {
  super.onStop();
  Log.i(TAG, "On Stop .....");
}
```

OnStart and OnResume are being log as well.

Why is onProgressUpdate not being called?
How to call the onProgressUpdated correctly?

Update

onPostExecute is being called as well on the onProgressUpdate is not

答:
Override the function instead of just copy past,
use keyword @Override  </p>

Body:
I have this GetAllUsers(); in onCreate and I have this

private void GetAllUsers() {
  (new LoadingUsers(this)).execute();
}

Then I have this

private class LoadingUsers extends AsyncTask < Void, Integer, String > {
  String TAG = getClass().getSimpleName();
  AlertDialog.Builder builderSingle;
  ArrayAdapter < String > arrayAdapter;@
  SuppressWarnings("unused")
  Context mContext;

  public LoadingUsers(Context context) {
    super();

    mContext = context;

  }

  protected void onPreExecute() {
    //            prgDialog.show();
    //            builderSingle = new
    Log.d(TAG + " PreExceute", "On pre Exceute......");
  }

  protected String doInBackground(Void...arg0) {

    Log.d(TAG + " DoINBackGround", "On doInBackground...");
    return null;
  }

  protected void onProgressUpdate(Integer...a) {
    super.onProgressUpdate(a);
    Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);

  }

  protected void onPostExecute(String result) {
    //            prgDialog.hide();
    Log.d(TAG + " onPostExecute", "" + result);

    MainActivity.this.pd.dismiss();
  }
}

I wanted to put a builderSingle = new AlertDialog.Builder(MainActivity.this); inside the protected void onProgressUpdate(Integer... a) { which has a AsyncHttpClient client = new AsyncHttpClient(); but unfortunately the onProgressUpdate does not get called at all. I know this because the log does not show. All other log are showing except the onProgressUpdate I have also have

@
Override
protected void onDestroy() {
  super.onDestroy();
  Log.i(TAG, "On Destroy .....");
}

@
Override
protected void onPause() {
  super.onPause();
  Log.i(TAG, "On Pause .....");
}

@
Override
protected void onRestart() {
  super.onRestart();
  Log.i(TAG, "On Restart .....");
}

@
Override
protected void onResume() {
  super.onResume();
  Log.i(TAG, "On Resume .....");
}

@
Override
protected void onStart() {
  super.onStart();
  Log.i(TAG, "On Start .....");
}

@
Override
protected void onStop() {
  super.onStop();
  Log.i(TAG, "On Stop .....");
}

OnStart and OnResume are being log as well.

Why is onProgressUpdate not being called?
How to call the onProgressUpdated correctly?

Update

onPostExecute is being called as well on the onProgressUpdate is not


问:
group day of the year data by month
I have a data frame called "fish" which contains variables such as mass, length and day of the year. I need to make a boxplot of fish length by month but there is no month variable, only day of the year (i.e 1:365). How can I group days by 30 to represent month and then name them so I can make a boxplot? I have attached a screenshot of the data.

答:
You can use this solution:

```<code>#load package
require(tidyverse)
#make dataframe
n <- 100
tmp <- tibble(year  = rep(c(1994,1994),n/2),day = c(1:n),lenght_mm = rnorm(n),mass_g = rnorm(n,5))
#add month column
tmp <- tmp %>%
  mutate(month = as.factor(ifelse(day%%30/30 != 0,day%/%30 +1,day%/%30)))

#make plot
    tmp %>%
      ggplot(aes(month,lenght_mm,col = month)) +
      geom_boxplot() +
      theme_bw()
</code>```

Title: group day of the year data by month

Body:
You can use this solution:

#load package
require(tidyverse)
#make dataframe
n <- 100
tmp <- tibble(year  = rep(c(1994,1994),n/2),day = c(1:n),lenght_mm = rnorm(n),mass_g = rnorm(n,5))
#add month column
tmp <- tmp %>%
  mutate(month = as.factor(ifelse(day%%30/30 != 0,day%/%30 +1,day%/%30)))

#make plot
    tmp %>%
      ggplot(aes(month,lenght_mm,col = month)) +
      geom_boxplot() +
      theme_bw()


问:
ContentFlow (coverflow) - Need to make it work + Tabs and panes
Im using this plugin:

http://www.jacksasylum.eu/ContentFlow/

Here is my test site:

http://flexbeltsite.info/TestPages/

This is the main index file, which is loading

http://flexbeltsite.info/TestPages/_Page3.html

1) The page that contains the contentFlow. As you can see when you go to the index, the contentFlow dosent work.  It only works when you view _Page3.html all by itself. This dosent help me much, as I need it to work on the index page when that page is loaded.

////////////////////////////////////////////////

2) I also would like to make it that when I click on one of the images, It expands (grow animation) to the full width and height of the containing div, the black area.  Then, if you click it again, it shrinks back to its original shape, and goes back in with the rest of the carousel, and the carousel works as normal.

////////////////////////////////////////////////

3) As for the 2nd page, away, id like to make the two sets of tabs and panes work totally independent of each other.  As you can see now if you try to use them, the tabs will control the content of the of the other panes instead of only their own...i dont want that. I need 1 top set of tabs and panes, and 1 bottom set of tabs and panes.  This is what i used to make the tabs and panes if you're curious.

http://flowplayer.org/tools/tabs/index.html

If i can get the cure to these 3 issues, id most greatly appreciate it. Thanks in advance.

EDIT:

This is the latest batch of code I am trying, yet i still cannot get it to work. Nothing different is happening. Why? What am i doing wrong?

```<code><!--Page Loading Mechanism-->
<script type="text/javascript">
    $( document ).ready( function() {
        $( 'a.dynamicLoad' ).click( function( e ) {
            e.preventDefault();   // prevent the browser from following the link
            e.stopPropagation();  // prevent the browser from following the link

            $( '#MainWrapper' ).load( $( this ).attr( 'href' ) , function() {
            /* Content is now loaded */
            ThumbnailScroller("tsv_container","vertical",10,800,"easeOutCirc",0.4,500);

    /*Newest Recommended Code from curlackhacker*/
        $.ajax({ url: $( this ).attr( 'href' ),
        success: function() {
                var contentFlow = new ContentFlow('.ContentFlow');
                contentFlow._init();
       }});
        });
      });

   });

</script>
</code>```

答:
1) A few remarks.
When you are loading the page3 as you are doing through  $( '#MainWrapper' ).load( $( this ).attr( 'href' ) ); you are loading the url's content into the mainwrapper. Which is fine to do, but your page3 is actually an entire HTML page including the     tags.
So what you end up with is your mainpage being similar to (a bit shortened):

```<code><html>
<body>
<div id="MainWrapper">
    <html>
        <head>
            <script language="JavaScript" type="text/javascript" src="ContentFlow/contentflow.js"></script>
        </head>
        <body>
             Your page3 content...
        </body>
    </html>
</div>

<div align="center"></div>
</body>
</html>
</code>```

Which you can see is not proper HTML, having a html and a body tag inside another body tag. So if you are planning on loading the content on the flow using JQuery, I advise you to drop the  and  tags from the included file (_Page3.html).

2) Then, the reason your contentflow is not working is because that library is autom. initiated using the body load function. So when your homepage HTML has been loaded, that function is being called. But it's only after that that you trigger the JQuery load function to load _Page3.html and its scripts into your main page, so the function inside the contentflow library that is configuring your flow is never being called.

A way to fix this is to make use of the 'success' function of your ajax call. That function is being triggered when your page has finished loading the external page. That means that your _Page3.html has been included into your main page and it's THEN that the contentflow should be configured.

```<code>$.ajax({ url: $( this ).attr( 'href' ),
        success: function() {
                //Not sure about this method name, you should look it up in contentflow.js
                onloadInit();
       }});
</code>```

3) Lastly, you can fit the image into your black part of the header by making use of the onclickActiveItem := function(obj item)  method of the contentflow library. And just add your own function there, that does this by selecting the selected image and modifying your header's content, using JQuery, to display the selected image. As described here: http://www.jacksasylum.eu/ContentFlow/docu.php

Body:
1) A few remarks.
When you are loading the page3 as you are doing through  $( '#MainWrapper' ).load( $( this ).attr( 'href' ) ); you are loading the url's content into the mainwrapper. Which is fine to do, but your page3 is actually an entire HTML page including the     tags.
So what you end up with is your mainpage being similar to (a bit shortened):

<html>
<body>
<div id="MainWrapper">
    <html>
        <head>
            <script language="JavaScript" type="text/javascript" src="ContentFlow/contentflow.js"></script>
        </head>
        <body>
             Your page3 content...
        </body>
    </html>
</div>

<div align="center"></div>
</body>
</html>

Which you can see is not proper HTML, having a html and a body tag inside another body tag. So if you are planning on loading the content on the flow using JQuery, I advise you to drop the <html> and <body> tags from the included file (_Page3.html).

2) Then, the reason your contentflow is not working is because that library is autom. initiated using the body load function. So when your homepage HTML has been loaded, that function is being called. But it's only after that that you trigger the JQuery load function to load _Page3.html and its scripts into your main page, so the function inside the contentflow library that is configuring your flow is never being called.

A way to fix this is to make use of the 'success' function of your ajax call. That function is being triggered when your page has finished loading the external page. That means that your _Page3.html has been included into your main page and it's THEN that the contentflow should be configured.

$.ajax({ url: $( this ).attr( 'href' ),
        success: function() {
                //Not sure about this method name, you should look it up in contentflow.js
                onloadInit();
       }});

3) Lastly, you can fit the image into your black part of the header by making use of the onclickActiveItem := function(obj item)  method of the contentflow library. And just add your own function there, that does this by selecting the selected image and modifying your header's content, using JQuery, to display the selected image. As described here: http://www.jacksasylum.eu/ContentFlow/docu.php


问:
Vertically center parent div on page
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

```<code><body>
 <div>
 My Logo goes here
 <div>
 <div>
  <section id="loginForm"></section>
  <section id="SocialLoginForm"></section>
 </div>
</body>
</code>```

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

答:
You can try flex like this :

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  text-align:center;
}

.logo {
  border: 1px solid red;
  min-height: 30px;
}

.login {
  flex: 1;
  border: 1px solid red;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
}

#loginForm,
#SocialLoginForm {
  min-height: 45px;
  border: 1px solid green;
  flex: 0 0 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="logo">
    My Logo goes here
  </div>
  <div class="login">
    <section id="loginForm">Login content</section>
    <section id="SocialLoginForm"> social login content</section>
  </div>
</div></code>```

Title: Vertically center parent div on page

Body:
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

 My Logo goes here

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

Body:
You can try flex like this :

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  text-align:center;
}

.logo {
  border: 1px solid red;
  min-height: 30px;
}

.login {
  flex: 1;
  border: 1px solid red;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
}

#loginForm,
#SocialLoginForm {
  min-height: 45px;
  border: 1px solid green;
  flex: 0 0 100%;
}

<div class="container">
  <div class="logo">
    My Logo goes here
  </div>
  <div class="login">
    <section id="loginForm">Login content</section>
    <section id="SocialLoginForm"> social login content</section>
  </div>
</div>


问:
how to run gulp tasks in order?
I am trying to concat all the css files into one released css file by running task:

```<code>gulp.task('task one', () => {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));
});
</code>```

After that, because the font path in the output css file is not correct, so I need to modify the path.

```<code>gulp.task('task two', () => {
    var urlAdjuster = require('gulp-css-url-adjuster');

    //change font path for released css files
    gulp.src([releasePath + "/*.css"])
        .pipe(urlAdjuster({
            replace: ['../../fonts', '../fonts'],
        }))
        .pipe(gulp.dest(releasePath + "/"));
);
</code>```

In order to make it happen, I need to run these two tasks separately one by one.
How can I run these two tasks in order and put them into one task.

I have tried:
series = require('gulp-series'); ----not working

```<code>gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});
</code>```

-----not working

---update--------------------------------------------------------
I used return but it is now working. The actual codes are:

```<code>function procHTMLForRelease(stream, file) {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));

}

function processRelease() {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

}

gulp.task('task one', () => { return processRelease();
});
</code>```

答:
You could modify your updated code like this to make it return.

```<code>gulp.task('taks one', function () {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    var one = gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    var two = gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    var three = gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

   // Return
   return [ one, two, three];

});
</code>```

The tasks inside the function will run asynchronously, but you can make another function to depend on those all being done.

```<code>gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});
</code>```

Title: how to run gulp tasks in order?

Body:
I am trying to concat all the css files into one released css file by running task:

gulp.task('task one', () => {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));
});

After that, because the font path in the output css file is not correct, so I need to modify the path.

gulp.task('task two', () => {
    var urlAdjuster = require('gulp-css-url-adjuster');

    //change font path for released css files
    gulp.src([releasePath + "/*.css"])
        .pipe(urlAdjuster({
            replace: ['../../fonts', '../fonts'],
        }))
        .pipe(gulp.dest(releasePath + "/"));
);

In order to make it happen, I need to run these two tasks separately one by one.
How can I run these two tasks in order and put them into one task.

I have tried:
series = require('gulp-series'); ----not working

gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});

-----not working

---update--------------------------------------------------------
I used return but it is now working. The actual codes are:

function procHTMLForRelease(stream, file) {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));

}

function processRelease() {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

}

gulp.task('task one', () => { return processRelease();
});

Body:
You could modify your updated code like this to make it return.

gulp.task('taks one', function () {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    var one = gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    var two = gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    var three = gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

   // Return
   return [ one, two, three];

});

The tasks inside the function will run asynchronously, but you can make another function to depend on those all being done.

gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});


问:
How to use x:Object and when?
When passing arguments by the markup extension x:Arguments to non default constructors as specified by the docs, I can see the use of concrete data types such as x:Int32 or x:String, but what's the use case of x:Object? And what's more, to use it, what should be put between the tag? <x:Object> ??? </x:Object>

In the case of integer or string, it is natural to think them as an variable assignment and the variables then get passed to the constructors. But in the case of Object, such an variable normally is constructed by another user defined class, so how to specify what class you want to create?

答:
Technically you can pass x:Object as constructor argument. x:Object corresponds to System.Object which does have default constructor. So if you have

```<code> public class MyClass {
     public MyClass(object arg) {

     }
 }
</code>```

You can construct it like this:

```<code><my:MyClass>
  <x:Arguments>
    <x:Object />
  </x:Arguments>
</my:MyClass>
</code>```

But this is not quite useful, because it will correspond to

```<code>new MyClass(new object());
</code>```

Since Object does not have any other constructors - you cannot construct it in any other meaningful way. So when constructor expects argument of type object - you don't want to use x:Object but instead actual type:

```<code><my:MyClass>
  <x:Arguments>
    <x:String>string</x:String>
  </x:Arguments>
</my:MyClass>
</code>```

which corresponds to

```<code>new MyClass("string");
</code>```

Title: How to use x:Object and when?

Body:
Technically you can pass x:Object as constructor argument. x:Object corresponds to System.Object which does have default constructor. So if you have

 public class MyClass {
     public MyClass(object arg) {

     }
 }

You can construct it like this:

<my:MyClass>
  <x:Arguments>
    <x:Object />
  </x:Arguments>
</my:MyClass>

But this is not quite useful, because it will correspond to

new MyClass(new object());

Since Object does not have any other constructors - you cannot construct it in any other meaningful way. So when constructor expects argument of type object - you don't want to use x:Object but instead actual type:

<my:MyClass>
  <x:Arguments>
    <x:String>string</x:String>
  </x:Arguments>
</my:MyClass>

which corresponds to

new MyClass("string");


问:
Having trouble reformatting date
I have a dict that has a bunch of dates in European format (%d/%m/%Y).
I am trying to reformat the dates so that they are in US format (%m/%d/%Y).
Whenever I run it, the following error is identified:

```<code>ValueError: time data '2' does not match format '%m/%d/%Y'
</code>```

Anyone know what I need to correct?
Thanks for your help!

```<code>from datetime import datetime
import time
from time import mktime

Transaction_Date=[
"23/08/2017",
"23/08/2017",
"21/08/2017",
"01/10/2017",
"19/08/2017",
"19/08/2017",
"18/08/2017",
"03/09/2017",
"27/09/2017",
"26/08/2017",
"03/10/2017",
"27/09/2017",
"27/03/2017",
"02/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017"]

for row in Transaction_Date:
    Transaction_Date = row[0]
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)
</code>```

Gives the following error:

```<code>ValueError: time data '2' does not match format '%m/%d/%Y'
</code>```

From what I can tell, the dates format is correct, why is the system saying different?

Title: Having trouble reformatting date

Body:
I have a dict that has a bunch of dates in European format (%d/%m/%Y).
I am trying to reformat the dates so that they are in US format (%m/%d/%Y).
Whenever I run it, the following error is identified:

ValueError: time data '2' does not match format '%m/%d/%Y'

Anyone know what I need to correct?
Thanks for your help!

from datetime import datetime
import time
from time import mktime

Transaction_Date=[
"23/08/2017",
"23/08/2017",
"21/08/2017",
"01/10/2017",
"19/08/2017",
"19/08/2017",
"18/08/2017",
"03/09/2017",
"27/09/2017",
"26/08/2017",
"03/10/2017",
"27/09/2017",
"27/03/2017",
"02/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017"]

for row in Transaction_Date:
    Transaction_Date = row[0]
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)

Gives the following error:

ValueError: time data '2' does not match format '%m/%d/%Y'

From what I can tell, the dates format is correct, why is the system saying different?

Body:
You just need to use row inside your loop as follows:

from datetime import datetime

Transaction_Dates = [
    "23/08/2017", "23/08/2017", "21/08/2017", "01/10/2017",
    "19/08/2017", "19/08/2017", "18/08/2017", "03/09/2017",
    "27/09/2017", "26/08/2017", "03/10/2017", "27/09/2017",
    "27/03/2017", "02/08/2017", "20/08/2017", "20/08/2017",
    "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017"]

for row in Transaction_Dates:
    print(datetime.strptime(row, '%d/%m/%Y').strftime('%m/%d/%Y'))

Which displays:

08/23/2017
08/23/2017
08/21/2017
10/01/2017
08/19/2017
08/19/2017
08/18/2017
09/03/2017
09/27/2017
08/26/2017
10/03/2017
09/27/2017
03/27/2017
08/02/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017


问:
Return errors as json django rest api
Beginner alert. I am using ListCreateAPIView for listing and creating purposes. Whenever I create through an api it returns responses in json format.

```<code>{"id":16,"title":"yyyyyyyy","destination_place":[1]}
</code>```

But if there are errors like duplicate slug or title it returns errors like this

```<code>IntegrityError at /api/holidays/
duplicate key value violates unique constraint "holidays_holiday_slug_key"
DETAIL:  Key (slug)=(yyyyyyyy) already exists.
</code>```

Is there any way to return these errors in json format.
My views

```<code>class HolidayList(ListCreateAPIView):
    queryset = Holiday.objects.all()
    serializer_class = HolidaySerializer
    permission_classes = [IsAdminUser, IsAuthenticated]
</code>```

Model

```<code>class Holiday(models.Model):
   title = models.CharField(verbose_name=_("Title"), max_length=255)
   slug = models.SlugField(unique=True)
   destination_place = models.ManyToManyField(to='places.Place',related_name='destination_place',null=True,blank=True)
</code>```

答:
In HolidaySerializer, add UniqueValidator on slug field.

Example:

```<code>from rest_framework.validators import UniqueValidator

class HolidaySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(
             max_length=255,
             validators=[UniqueValidator(queryset=Holiday.objects.all())])

    class Meta:
        model = Holiday
        fields = ('id', 'title', 'slug', 'destination_place', )
</code>```

This will return back the unique constraint error in the JSON format.

You can customize the message. Look at the docs.

Title: Return errors as json django rest api

Body:
Beginner alert. I am using ListCreateAPIView for listing and creating purposes. Whenever I create through an api it returns responses in json format.

{"id":16,"title":"yyyyyyyy","destination_place":[1]}

But if there are errors like duplicate slug or title it returns errors like this

IntegrityError at /api/holidays/
duplicate key value violates unique constraint "holidays_holiday_slug_key"
DETAIL:  Key (slug)=(yyyyyyyy) already exists.

Is there any way to return these errors in json format.
My views

class HolidayList(ListCreateAPIView):
    queryset = Holiday.objects.all()
    serializer_class = HolidaySerializer
    permission_classes = [IsAdminUser, IsAuthenticated]

Model

class Holiday(models.Model):
   title = models.CharField(verbose_name=_("Title"), max_length=255)
   slug = models.SlugField(unique=True)
   destination_place = models.ManyToManyField(to='places.Place',related_name='destination_place',null=True,blank=True)

Body:
In HolidaySerializer, add UniqueValidator on slug field.

Example:

from rest_framework.validators import UniqueValidator

class HolidaySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(
             max_length=255,
             validators=[UniqueValidator(queryset=Holiday.objects.all())])

    class Meta:
        model = Holiday
        fields = ('id', 'title', 'slug', 'destination_place', )

This will return back the unique constraint error in the JSON format.

You can customize the message. Look at the docs.


问:
py.test how to run a method before every test
I used unittest and nose for unit-testing in Python but now I'm using py.test.

unittest and nose always call class.setUp before executing every method in the TestCase.

How can I do this with py.test?

EDIT: If I add this:

```<code>def setup_class(cls):
    cls.a = pypol.polynomial('x^3 - 2x^2 + x -5')
    cls.b = pypol.polynomial('a^3 - 2x^2 - b + 3')
    cls.c = pypol.polynomial('-x + 1')
    cls.d = pypol.polynomial('a')
</code>```

I get all errors:

```<code>_____________________________ TestPolynomial.testSetitem ______________________________

self = <test_pypol.TestPolynomial object at 0x97355ec>

    def testSetitem(self):
>       TestPolynomial.a[2] = (3, {'x': 3, 'y': 4})
E       AttributeError: type object 'TestPolynomial' has no attribute 'a'

test_pypol.py:162: AttributeError
_____________________________ TestPolynomial.testDelitem ______________________________

self = <test_pypol.TestPolynomial object at 0x9735eac>

    def testDelitem(self):
>       del TestPolynomial.a[1:3]
E       AttributeError: type object 'TestPolynomial' has no attribute 'a'
</code>```

EDIT2: Ok, I'm stupid. I had to put inside the TestCase and not outside. Thank you.

答:
Sounds like you need to define setup_method on the test class:

https://codespeak.net/py/0.9.2/test.html#managing-test-state-across-test-modules-classes-and-methods

Body:
I used unittest and nose for unit-testing in Python but now I'm using py.test.

unittest and nose always call class.setUp before executing every method in the TestCase.

How can I do this with py.test?

EDIT: If I add this:

def setup_class(cls):
    cls.a = pypol.polynomial('x^3 - 2x^2 + x -5')
    cls.b = pypol.polynomial('a^3 - 2x^2 - b + 3')
    cls.c = pypol.polynomial('-x + 1')
    cls.d = pypol.polynomial('a')

I get all errors:

_____________________________ TestPolynomial.testSetitem ______________________________

self = <test_pypol.TestPolynomial object at 0x97355ec>

    def testSetitem(self):
>       TestPolynomial.a[2] = (3, {'x': 3, 'y': 4})
E       AttributeError: type object 'TestPolynomial' has no attribute 'a'

test_pypol.py:162: AttributeError
_____________________________ TestPolynomial.testDelitem ______________________________

self = <test_pypol.TestPolynomial object at 0x9735eac>

    def testDelitem(self):
>       del TestPolynomial.a[1:3]
E       AttributeError: type object 'TestPolynomial' has no attribute 'a'

EDIT2: Ok, I'm stupid. I had to put inside the TestCase and not outside. Thank you.