问:
Attaching a JSON array to list view
I am new to Java so please excuse any silly or obvious mistake.  I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view.  I am getting the dreaded red squiggly lines and what is to me a cryptic error message.    Here is my code.  I appreciate any assistance.</p>

```<code>package --Hidden--;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class tracklist extends Activity implements OnItemClickListener {
    private static final String URL = "http://rickthompson.com/json/fetchtracks.php";

    ListView lv;

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

        lv = (ListView) findViewById(R.id.displayTrackList);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            R.layout.rowlayout, R.id.label, profileUserOptions);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);

        Bundle bundle = getIntent().getExtras();
        final String selectedSubGenre = bundle.getString("option");

        /////////////  login script
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.names().get(0).equals("tracks")) {
                        Toast.makeText(getApplicationContext(), "tracks " +    jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();

                        ///  save user id in prefs
                        JSONArray contacts =   jsonObject.getJSONArray("tracks");
                        HashMap<String, String> trackview = null;
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            String isrc = c.getString("isrc");

                            trackview = new HashMap<>();
                            trackview.put("isrc", isrc);
                        }

                        trackview.toString();

                        lv = (ListView)  findViewById(R.id.displayTrackList);
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
                        lv.setAdapter(adapter);
                        lv.setOnItemClickListener(this);
                    } else {
                        Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<>();
                SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                String userid = userPrefs.getString("memberid", "");

                hashMap.put("u", userid);
                Bundle bundle = getIntent().getExtras();
                final String selectedSubGenre = bundle.getString("option");
                hashMap.put("sg", selectedSubGenre);
                return hashMap;
            }
       };

       requestQueue.add(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
    }
}
</code>```

答:
```<code>JSONObject jsonObject = new JSONObject(response);
 if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}
</code>```

In the above code I hope you are trying to get "name" array which should be

```<code>    JSONArray jso3 = new JSONArray (jsonObject.getString("names"));
</code>```

Please provide the error details so that i can give you a detailed description.

Title: Attaching a JSON array to list view

Body:
I am new to Java so please excuse any silly or obvious mistake.  I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view.  I am getting the dreaded red squiggly lines and what is to me a cryptic error message.    Here is my code.  I appreciate any assistance.

package --Hidden--;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class tracklist extends Activity implements OnItemClickListener {
    private static final String URL = "http://rickthompson.com/json/fetchtracks.php";

    ListView lv;

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

        lv = (ListView) findViewById(R.id.displayTrackList);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            R.layout.rowlayout, R.id.label, profileUserOptions);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);

        Bundle bundle = getIntent().getExtras();
        final String selectedSubGenre = bundle.getString("option");

        /////////////  login script
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.names().get(0).equals("tracks")) {
                        Toast.makeText(getApplicationContext(), "tracks " +    jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();

                        ///  save user id in prefs
                        JSONArray contacts =   jsonObject.getJSONArray("tracks");
                        HashMap<String, String> trackview = null;
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            String isrc = c.getString("isrc");

                            trackview = new HashMap<>();
                            trackview.put("isrc", isrc);
                        }

                        trackview.toString();

                        lv = (ListView)  findViewById(R.id.displayTrackList);
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
                        lv.setAdapter(adapter);
                        lv.setOnItemClickListener(this);
                    } else {
                        Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<>();
                SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                String userid = userPrefs.getString("memberid", "");

                hashMap.put("u", userid);
                Bundle bundle = getIntent().getExtras();
                final String selectedSubGenre = bundle.getString("option");
                hashMap.put("sg", selectedSubGenre);
                return hashMap;
            }
       };

       requestQueue.add(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
    }
}

Body:
JSONObject jsonObject = new JSONObject(response);
 if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}

In the above code I hope you are trying to get "name" array which should be

    JSONArray jso3 = new JSONArray (jsonObject.getString("names"));

Please provide the error details so that i can give you a detailed description.


来源: stackexchange

问:
How can I change CSS styles as a user reaches a specific point on a page?
I am trying to underline each specific title inside of a fixed navigation bar as a person reaches specific points on a page.

Ex: As a person reaches the Contact Info section of the page, the title "CONTACT INFO" inside of the fixed navigation bar will be the only title with a red underline.

答:
Bootstrap Solution

If you're using Bootstrap there is a build in Javascript Component called "Scrollspy" that already exists.

See the documentation.

This expects you to use a  for your navigation, and that all your links that you want to highlight points to valid DOM identifiers such as:

```<code><a href="#my-title">Link</a>
</code>```

Other ways

There are already a couple of existing Javascript plugins that do this. You can see them here:

https://github.com/r3plica/Scrollspy

https://github.com/sxalexander/jquery-scrollspy

ContentLicense: CC BY-SA 3.0

Body:
Bootstrap Solution

If you're using Bootstrap there is a build in Javascript Component called "Scrollspy" that already exists.

See the documentation.

This expects you to use a <nav> for your navigation, and that all your links that you want to highlight points to valid DOM identifiers such as:

<a href="#my-title">Link</a>

Other ways

There are already a couple of existing Javascript plugins that do this. You can see them here:

https://github.com/r3plica/Scrollspy

https://github.com/sxalexander/jquery-scrollspy


问:
Xamarin.Forms ListView Load More
The Problem

What I want to achieve can you basically see here

so when the user scrolls to the end I want to load more, because my List is very large and I want to Maximize Performance.

I'm trying to achieve this as follows, in splitting the Main Collection with the Data so that i can set the ItemSource new when the User reaches the end.

What ive Implemented so far

```<code> public class ViewModel : BaseViewModel {

        public ViewModel() {
            Initialize();
        }

        public List<List<Usermodel>> SplitedUserLists { get; set; }

        //Main List that im Binding to
        public List<Usermodel> ItemSourceCollection { get; set; }

        public int ChunkSize { get; set; }
        #endregion

        private async void Initialize() {

            ItemSourceCollection = await LoadList();

            // Splites the list (in this case the chunk Size is 5)
            SplitedScoreLists = ItemSourceCollection.Split(GetChunkSize()));
            ItemSourceCollection = SplitedScoreLists[0];
        }

        //Gets called from CodeBehind
        public void ListViewItemAppearing(ItemVisibilityEventArgs e) {

            //Bottom Hit!
            if (e.Item == ItemSourceCollection[ItemSourceCollection.Count - 1]) {

                if (ChunkSize >= SplitedScoreLists.Count) {
                    return;
                }

                foreach (var usermodel in SplitedScoreLists[ChunkSize].ToList()) {
                    ItemSourceCollection.Add(usermodel);
                }

                if (ChunkSize < SplitedScoreLists.Count) {
                    ChunkSize++;
                }
            }
        }
 }
</code>```

Questions

The problem with my Implementation is that the List is actually longer than the Count of the original List due to duplicates.

Is this the right way to achieve something like this?

Am I actually increasing Performance with this? I need to cause the List is 1000+ entries.

答:
There are nice tutorials on how to achieve this:

http://motzcod.es/post/107620279512/load-more-items-at-end-of-listview-in

https://github.com/jguibault/Xamarin-Forms-Infinite-Scroll

http://www.codenutz.com/lac09-xamarin-forms-infinite-scrolling-listview/

The key point is when to raise the "load more" command:

```<code>public class InfiniteListView : ListView
{
    public static readonly BindableProperty LoadMoreCommandProperty = BindableProperty.Create<InfiniteListView, ICommand>(bp => bp.LoadMoreCommand, default(ICommand));

    public ICommand LoadMoreCommand
    {
        get { return (ICommand) GetValue(LoadMoreCommandProperty); }
        set { SetValue(LoadMoreCommandProperty, value); }
    }

    public InfiniteListView()
    {
        ItemAppearing += InfiniteListView_ItemAppearing;
    }

    void InfiniteListView_ItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        var items = ItemsSource as IList;

        if (items != null && e.Item == items[items.Count - 1])
        {
            if(LoadMoreCommand != null && LoadMoreCommand.CanExecute(null))
                LoadMoreCommand.Execute(null);
        }
    }
}
</code>```

Title: Xamarin.Forms ListView Load More

Body:
The Problem

What I want to achieve can you basically see here

so when the user scrolls to the end I want to load more, because my List is very large and I want to Maximize Performance.

I'm trying to achieve this as follows, in splitting the Main Collection with the Data so that i can set the ItemSource new when the User reaches the end.

What ive Implemented so far

 public class ViewModel : BaseViewModel {

        public ViewModel() {
            Initialize();
        }

        public List<List<Usermodel>> SplitedUserLists { get; set; }

        //Main List that im Binding to
        public List<Usermodel> ItemSourceCollection { get; set; }

        public int ChunkSize { get; set; }
        #endregion

        private async void Initialize() {

            ItemSourceCollection = await LoadList();

            // Splites the list (in this case the chunk Size is 5)
            SplitedScoreLists = ItemSourceCollection.Split(GetChunkSize()));
            ItemSourceCollection = SplitedScoreLists[0];
        }

        //Gets called from CodeBehind
        public void ListViewItemAppearing(ItemVisibilityEventArgs e) {

            //Bottom Hit!
            if (e.Item == ItemSourceCollection[ItemSourceCollection.Count - 1]) {

                if (ChunkSize >= SplitedScoreLists.Count) {
                    return;
                }

                foreach (var usermodel in SplitedScoreLists[ChunkSize].ToList()) {
                    ItemSourceCollection.Add(usermodel);
                }

                if (ChunkSize < SplitedScoreLists.Count) {
                    ChunkSize++;
                }
            }
        }
 }

Questions

The problem with my Implementation is that the List is actually longer than the Count of the original List due to duplicates.

Is this the right way to achieve something like this?

Am I actually increasing Performance with this? I need to cause the List is 1000+ entries.

Body:
There are nice tutorials on how to achieve this:

http://motzcod.es/post/107620279512/load-more-items-at-end-of-listview-in

https://github.com/jguibault/Xamarin-Forms-Infinite-Scroll

http://www.codenutz.com/lac09-xamarin-forms-infinite-scrolling-listview/

The key point is when to raise the "load more" command:

public class InfiniteListView : ListView
{
    public static readonly BindableProperty LoadMoreCommandProperty = BindableProperty.Create<InfiniteListView, ICommand>(bp => bp.LoadMoreCommand, default(ICommand));

    public ICommand LoadMoreCommand
    {
        get { return (ICommand) GetValue(LoadMoreCommandProperty); }
        set { SetValue(LoadMoreCommandProperty, value); }
    }

    public InfiniteListView()
    {
        ItemAppearing += InfiniteListView_ItemAppearing;
    }

    void InfiniteListView_ItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        var items = ItemsSource as IList;

        if (items != null && e.Item == items[items.Count - 1])
        {
            if(LoadMoreCommand != null && LoadMoreCommand.CanExecute(null))
                LoadMoreCommand.Execute(null);
        }
    }
}


问:
Formatted elapsed time in C
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

```<code>// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}
</code>```

And here is the output I get immediately after running the program

```<code>01:00:00
01:00:00
01:00:01
01:00:01
01:00:01
</code>```

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

答:
time_t typically (see edit) stores absolute timestamps (the number of seconds since midnight UTC, January 1, 1970). By calculating current - *_start, you're getting elapsed time in seconds (as desired), but by then passing that to localtime and strftime, you're telling the computer to take the time elapsed since the start of your program and treat it as the time elapsed since midnight UTC 1-1-1970.

I'm guessing that happens to be 01:00:00 in your system's local time zone.

I'm not aware of a C99 function to print elapsed time, but it's not hard to write one yourself.

```<code>void format_elapsed_time(char *time_str, int total_seconds_elapsed) {
    int hours_elapsed = total_seconds_elapsed / 3600;
    int minutes_elapsed = (total_seconds_elapsed % 3600) / 60;
    int seconds_elapsed = total_seconds_elapsed % 60;
    sprintf(time_str, "%02i:%02i:%02i", hours_elapsed, minutes_elapsed, seconds_elapsed);
}
</code>```

Edit: As @chux points out, time_t doesn't have to store timestamps as seconds since 1-1-1970. See this answer for details.

Title: Formatted elapsed time in C

Body:
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}

And here is the output I get immediately after running the program

01:00:00
01:00:00
01:00:01
01:00:01
01:00:01

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

Body:
time_t typically (see edit) stores absolute timestamps (the number of seconds since midnight UTC, January 1, 1970). By calculating current - *_start, you're getting elapsed time in seconds (as desired), but by then passing that to localtime and strftime, you're telling the computer to take the time elapsed since the start of your program and treat it as the time elapsed since midnight UTC 1-1-1970.

I'm guessing that happens to be 01:00:00 in your system's local time zone.

I'm not aware of a C99 function to print elapsed time, but it's not hard to write one yourself.

void format_elapsed_time(char *time_str, int total_seconds_elapsed) {
    int hours_elapsed = total_seconds_elapsed / 3600;
    int minutes_elapsed = (total_seconds_elapsed % 3600) / 60;
    int seconds_elapsed = total_seconds_elapsed % 60;
    sprintf(time_str, "%02i:%02i:%02i", hours_elapsed, minutes_elapsed, seconds_elapsed);
}

Edit: As @chux points out, time_t doesn't have to store timestamps as seconds since 1-1-1970. See this answer for details.


问:
How to create privileges buttons dynamically?
As I can create buttons automatically depending on the user who logs in, for example an administrator user is of type administrator and has all the privileges, then the admin user when login in the form should generate the privileges like buttons, how can it be done?

My login code:

```<code>  private void button1_Click(object sender, EventArgs e)
            {
    if (txtUser.Text == "" || txtContrasenna.Text == "")
                {
                    MessageBox.Show("Please provide UserName and Password");
                    return;
                }
                try
                {
                    //Create SqlConnection
                    SqlConnection con = new SqlConnection(cs);
                    SqlCommand cmd = new SqlCommand("Select * from Users where NameUser=@nameuser and Password=@password", con);
                    cmd.Parameters.AddWithValue("@nameuser", txtUser.Text);
                    cmd.Parameters.AddWithValue("@password", txtContrasenna.Text);
                    con.Open();
                    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                    DataTable ds = new DataTable();
                    adapt.Fill(ds);
                    con.Close();
                   // int count = ds.Tables[0].Rows.Count;

                    //If count is equal to 1, than show frmMain form
                    if (ds.Rows.Count == 1)
                    {
                        switch (ds.Rows[0]["UserTypeId"] as int?)
                        {
                            case 1:
                                {
                                    this.Hide();
                                   Menus.MenuSuperUser ss = new Menus.MenuSuperUser();
                                    ss.Show();
                                   // MessageBox.Show("MAMALON");

                                    break;
                                }
                            case 2:
                                {
                                    this.Hide();
                                    PantallasUsers.DashboardVendedor ss = new PantallasUsers.DashboardVendedor();
                                    ss.Show();

                                    break;
                                }
                            default:
                                {
                                    MessageBox.Show("NOTBABY");
                                    break;
                                }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Algo esta mal, revisa tus datos.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
</code>```

答:
```<code>// Create desired control
CTRL ctrl = new CTRL();

// Set properties
ctrl.SomeProperty = value;

// Where to put the control
ctrl.Location = new Point(X, Y);

Controls.Add(ctrl);
</code>```

Body:
As I can create buttons automatically depending on the user who logs in, for example an administrator user is of type administrator and has all the privileges, then the admin user when login in the form should generate the privileges like buttons, how can it be done?

My login code:

  private void button1_Click(object sender, EventArgs e)
            {
    if (txtUser.Text == "" || txtContrasenna.Text == "")
                {
                    MessageBox.Show("Please provide UserName and Password");
                    return;
                }
                try
                {
                    //Create SqlConnection
                    SqlConnection con = new SqlConnection(cs);
                    SqlCommand cmd = new SqlCommand("Select * from Users where NameUser=@nameuser and Password=@password", con);
                    cmd.Parameters.AddWithValue("@nameuser", txtUser.Text);
                    cmd.Parameters.AddWithValue("@password", txtContrasenna.Text);
                    con.Open();
                    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                    DataTable ds = new DataTable();
                    adapt.Fill(ds);
                    con.Close();
                   // int count = ds.Tables[0].Rows.Count;

                    //If count is equal to 1, than show frmMain form
                    if (ds.Rows.Count == 1)
                    {
                        switch (ds.Rows[0]["UserTypeId"] as int?)
                        {
                            case 1:
                                {
                                    this.Hide();
                                   Menus.MenuSuperUser ss = new Menus.MenuSuperUser();
                                    ss.Show();
                                   // MessageBox.Show("MAMALON");

                                    break;
                                }
                            case 2:
                                {
                                    this.Hide();
                                    PantallasUsers.DashboardVendedor ss = new PantallasUsers.DashboardVendedor();
                                    ss.Show();

                                    break;
                                }
                            default:
                                {
                                    MessageBox.Show("NOTBABY");
                                    break;
                                }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Algo esta mal, revisa tus datos.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }


问:
How to pull embedded 1:1 data on a CouchDb document
I am using CouchDb to store my documents and figuring out how to pull 1:1 related data on a document using CouchDb views.

For this given document structure,

```<code>{
  _id: 'some_id',
  doc_type: 'item',
  name: 'Steel Caliper'
  description: 'Steel Caliper description',
  classification: {
    _id: 'some_classification_id'
  }
}

classification: {
  _id: 'some_classification_id',
  doc_type: 'classification',
  name: 'Hand Tools'
}
</code>```

When I retrieve a list of item documents using a CouchDb view like below (called with include_docs=true)

```<code>function(doc) {
  if(doc_type==='item') {
     emit(doc.name, null);
  }
}
</code>```

I get the item document but without the classification data pulled in.

```<code>{
  "total_rows": 10,
  "offset": 0,
  "rows": [
    {
      "id": "some_id",
      "key": "Steel Caliper",
      "value": null,
      "doc": {
        "_id": "some_id",
        "_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
        "doc_type": "item"
        "name": "Steel Caliper"
        "classification": {
          "_id": "some_classification_id"
        }
      }
    },
    { ... }
}
</code>```

Is there a way to pull in the classification data using a view and get an output like below ?

```<code>...
    "doc": {
       "_id": "some_id",
       "_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
       "doc_type": "item"
       "name": "Steel Caliper"
       "classification": {
          "_id": "some_classification_id",
          "doc_type": "classification",
          "name": "Hand Tools"
       }
    }
...
</code>```

答:
yes, this is called view collation. You can emit multiple docs if you are joining by _ids.

in your case you can call

```<code>function(doc) {
   if(doc_type==='item') {
     emit(doc.name, null);
     if( doc.classification ){
         emit( doc.classification._id, {_id: doc.classification._id });
     }

   }
}
</code>```

you might still need play around with the returned result to get it into the form you want.

http://docs.couchdb.org/en/2.0.0/couchapp/views/joins.html

Body:
I am using CouchDb to store my documents and figuring out how to pull 1:1 related data on a document using CouchDb views.

For this given document structure,

{
  _id: 'some_id',
  doc_type: 'item',
  name: 'Steel Caliper'
  description: 'Steel Caliper description',
  classification: {
    _id: 'some_classification_id'
  }
}

classification: {
  _id: 'some_classification_id',
  doc_type: 'classification',
  name: 'Hand Tools'
}

When I retrieve a list of item documents using a CouchDb view like below (called with include_docs=true)

function(doc) {
  if(doc_type==='item') {
     emit(doc.name, null);
  }
}

I get the item document but without the classification data pulled in.

{
  "total_rows": 10,
  "offset": 0,
  "rows": [
    {
      "id": "some_id",
      "key": "Steel Caliper",
      "value": null,
      "doc": {
        "_id": "some_id",
        "_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
        "doc_type": "item"
        "name": "Steel Caliper"
        "classification": {
          "_id": "some_classification_id"
        }
      }
    },
    { ... }
}

Is there a way to pull in the classification data using a view and get an output like below ?

...
    "doc": {
       "_id": "some_id",
       "_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
       "doc_type": "item"
       "name": "Steel Caliper"
       "classification": {
          "_id": "some_classification_id",
          "doc_type": "classification",
          "name": "Hand Tools"
       }
    }
...

Body:
yes, this is called view collation. You can emit multiple docs if you are joining by _ids.

in your case you can call

function(doc) {
   if(doc_type==='item') {
     emit(doc.name, null);
     if( doc.classification ){
         emit( doc.classification._id, {_id: doc.classification._id });
     }

   }
}

you might still need play around with the returned result to get it into the form you want.

http://docs.couchdb.org/en/2.0.0/couchapp/views/joins.html


问:
Perl script to copy logs with timestamp for every hour and paste into different file
First of all, I'm very new to programming and so would need your help in writing a perl script to do the following on windows.

I have a big log file with timestamp (1gb) and its difficult to read the logs as it takes a lot of time to open. so my requirement is to copy the logs from the bigger log file for the last one hour and paste it to another file and then copy the next 1 hr of data to different file(so we will have 24 files for a day). The next day the data in these files needs to be over written or delete & create a new file.

Sample log :

```<code>09092016-00:02:00,..................
09092016-00:02:08,..................
09092016-00:02:15,..................
09092016-00:02:18,..................
</code>```

Please help me with this and thanks for your help in advance.

Thanks,

答:
for example:

```<code>logfile="./log"
while read -r d m y h; do
    grep "^$d$m$y-$h" "$logfile" > "partial-${y}${m}{$d}-${h}.log"
done < <(sed -n 's/\(..\)\(..\)\(....\)-\(..\)\(.*\)/\1 \2 \3 \4/p' "$logfile" | sort -u)
</code>```

easy, but not efficient. It reads the whole big logfile 25x for the split. (1x for gathering the existing ddmmyyyy-hh lines in the log, and again for every different found date-hour.)

Body:
First of all, I'm very new to programming and so would need your help in writing a perl script to do the following on windows.

I have a big log file with timestamp (1gb) and its difficult to read the logs as it takes a lot of time to open. so my requirement is to copy the logs from the bigger log file for the last one hour and paste it to another file and then copy the next 1 hr of data to different file(so we will have 24 files for a day). The next day the data in these files needs to be over written or delete & create a new file.

Sample log :

09092016-00:02:00,..................
09092016-00:02:08,..................
09092016-00:02:15,..................
09092016-00:02:18,..................

Please help me with this and thanks for your help in advance.

Thanks,

Body:
for example:

logfile="./log"
while read -r d m y h; do
    grep "^$d$m$y-$h" "$logfile" > "partial-${y}${m}{$d}-${h}.log"
done < <(sed -n 's/\(..\)\(..\)\(....\)-\(..\)\(.*\)/\1 \2 \3 \4/p' "$logfile" | sort -u)

easy, but not efficient. It reads the whole big logfile 25x for the split. (1x for gathering the existing ddmmyyyy-hh lines in the log, and again for every different found date-hour.)


问:
Taking a square root equation and representing it as a string in Java
I'm trying to represent a square root in a string in Java, however ...

The Unicode for a square root, which is \u221A, just prints the symbol for a square root - I want it to wrap around my equation like so:

An example of a normal square root equation

But it comes out like this, as expected:

The Unicode symbol for a square root

How can I format my string to represent the square roots as such?

Thanks in advance!

答:
If you mean you want to print this to the console then you cannot achieve what you are attempting to do - the closest you could achieve is an approximation of the overbar using underscores, eg:

```<code> ___
√ x
</code>```

If you aren't using the console and instead a rich rendering device (eg a Swing GUI, or a browser window) you may be able to achieve something richer in HTML using MathML (may require further JavaScript library support):

```<code><math xmlns="http://www.w3.org/1998/Math/MathML">
    <msqrt>
        <mrow>x</mrow>
    </msqrt>
</math>
</code>```

or by drawing it yourself into a suitable graphics context, eg a Graphics2D.

Body:
If you mean you want to print this to the console then you cannot achieve what you are attempting to do - the closest you could achieve is an approximation of the overbar using underscores, eg:

 ___
√ x

If you aren't using the console and instead a rich rendering device (eg a Swing GUI, or a browser window) you may be able to achieve something richer in HTML using MathML (may require further JavaScript library support):

<math xmlns="http://www.w3.org/1998/Math/MathML">
    <msqrt>
        <mrow>x</mrow>
    </msqrt>
</math>

or by drawing it yourself into a suitable graphics context, eg a Graphics2D.


问:
Facebook Messenger bot error: The parameter recipient is required
the bash command I used to connect the bot is: curl -ik -X POST 'https://graph.facebook.com/v2.6/me/messages?access_token=#AccessToken'

My error message is:

{"error":{"message":"(#100) The parameter recipient is
  required","type":"OAuthException","code":100,"fbtrace_id":"EFqWAGq2ABs"}}

Do anyone how to solve it ?

答:
Just in case anyone missed this, I encountered this issue when I accidentally use the wrong content type - I was using application/x-www-form-urlencoded instead of application/json

So my advise overall is,

Check if you are indeed passing the parameter

Double check the characters and encoding

Make sure to use the correct endpoint

and Make sure to use the correct content type when posting the JSON Request.

ContentLicense: CC BY-SA 4.0


问:
how to read the Excel sheet in JSF
How to read the Excel sheet data in jsf.pls can u give the sample application</p>

答: Reading Excel sheet data has nothing to do with JSF. Try Apache POI or JExcel to read Excel. Google and find there are lot of tutorial for these around the web.</p>

ContentLicense: CC BY-SA 2.5

Title: how to read the Excel sheet in JSF


问:
Why is my relative format looking awkward?
I'm trying to build a relative layout for my school project. The center element refuses to be the same height and distance from the top as the others. How do I fix this?

Edit: To clarify the icons are textViews using fontAwesome. Debugging a little I switched the icons of the left and center containers and the center was still higher so I believe it is an issue of formatting.

Layout:

```<code><RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDate"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_calender"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDate"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDuration"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_time"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDuration"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDistance"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_road"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDistance"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

    </RelativeLayout>
</code>```

with bg to highlight issue:

without bg

答:
Two ways to do this.

1、Use Paint to make sure your size of image is totally same.

2、adjust your image size in specific

```<code>            android:layout_width="30dp"
            android:layout_height="30dp"
</code>```

Body:
I'm trying to build a relative layout for my school project. The center element refuses to be the same height and distance from the top as the others. How do I fix this?

Edit: To clarify the icons are textViews using fontAwesome. Debugging a little I switched the icons of the left and center containers and the center was still higher so I believe it is an issue of formatting.

Layout:

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDate"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_calender"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDate"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDuration"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_time"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDuration"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDistance"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_road"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDistance"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

    </RelativeLayout>

with bg to highlight issue:

without bg

Body:
Two ways to do this.

1、Use Paint to make sure your size of image is totally same.

2、adjust your image size in specific

            android:layout_width="30dp"
            android:layout_height="30dp"


问:
How to check every 3rd element in a list and count the vowels in that string?
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

```<code>wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']
</code>```

答:
First off, this looks a lot like a homework problem or something. That said, this isn't the place to ask for homework help and instead you should ask questions about general algorithms or strategies. Maybe it's not, so here's a general suggestion.

I don't think it has a specific example, but this page may  help. For getting every nth index of a list (starting at 0) you can do list[0::n]. This returns a new list containing every nth entry of the original.

From there counting every vowel is pretty basic string manipulation and/or list comparison. Please show us what you've tried and we can give more specific feed back, but that's probably what you should be using.

Body:
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']


问:
most efficient method to extract key: value pairs from a pandas column and use the keys as columns
I have a large data set, 50000 or so csv's containing about 40000 lines, that I need to read into dataframes, extract the key: value pairs and use them as columns/values in the same dataframe. The excerpt below is a single column of my pandas dataframe:

```<code>column
'this is my string of data., you can:  parse me now, but:  you will never find me'
'this is some crazy data., where are:  you at today?, you can:  never find me, but:  this is fun.'
'this is more crazy than ever, where are:, you can:  not parse me, strange:  stuff'
</code>```

How can I extract just the key: value pairs that match the following criteria? I am trying to do this in the most efficient method due to the iteration over multiple files.

```<code>between two commas
must contain a colon
two spaces after the colon
any character to include spaces
</code>```

With an expected output of expanding the keys to columns and values in the columns:

```<code>you can          but                      where are      strange     <==columns
parse me now     you will never find me   NONE           NONE
never find me    this is fun              you at today?  NONE
not parse me     NONE                     NONE           stuff
</code>```

Updated visual of data.

```<code>                                 1
  0
0  subject                     NaN
  strange sub                AcDe1
  strange name               i001$
  stuff and things           86753
  newby id                      09
</code>```

答:
You can use extractall to get all the key value pairs in long format, and transform it so the keys goes as the column headers, assuming the original column name is col here:

```<code>(df.col.str.extractall("([^,]+?):(?:\s{2}([^,]+))?")
   .reset_index(level=1, drop=True)
   .set_index(0, append=True)[1]
   .unstack(level=1))
</code>```

Body:
I have a large data set, 50000 or so csv's containing about 40000 lines, that I need to read into dataframes, extract the key: value pairs and use them as columns/values in the same dataframe. The excerpt below is a single column of my pandas dataframe:

column
'this is my string of data., you can:  parse me now, but:  you will never find me'
'this is some crazy data., where are:  you at today?, you can:  never find me, but:  this is fun.'
'this is more crazy than ever, where are:, you can:  not parse me, strange:  stuff'

How can I extract just the key: value pairs that match the following criteria? I am trying to do this in the most efficient method due to the iteration over multiple files.

between two commas
must contain a colon
two spaces after the colon
any character to include spaces

With an expected output of expanding the keys to columns and values in the columns:

you can          but                      where are      strange     <==columns
parse me now     you will never find me   NONE           NONE
never find me    this is fun              you at today?  NONE
not parse me     NONE                     NONE           stuff

Updated visual of data.

                                 1
  0
0  subject                     NaN
  strange sub                AcDe1
  strange name               i001$
  stuff and things           86753
  newby id                      09

Body:
You can use extractall to get all the key value pairs in long format, and transform it so the keys goes as the column headers, assuming the original column name is col here:

(df.col.str.extractall("([^,]+?):(?:\s{2}([^,]+))?")
   .reset_index(level=1, drop=True)
   .set_index(0, append=True)[1]
   .unstack(level=1))


问:
Insert nested JSON to MySQL using Node
I am using Node to INSERT JSON to MySQL, using Node.js

This works fine, until I have nested values.

Example of my JSON is here:

```<code>var result2 = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}, {
"id": 89305,
"employeeDetails": {
    "id": 102522,
    "version": 99
}
}];
</code>```

Note: I am using the above for testing, as further on I want to call API requests in JSON and return them.

This is how I am sending it to MySQL using Node.js:

```<code>var query = connection.query('INSERT INTO employees SET ?', result2,
function(error, results, fields) {
    if (error) throw error;
});
</code>```

Without nesting, this is working fine, however the nested employeeDetails gives me the following error:

```<code>Error: ER_BAD_FIELD_ERROR: Unknown column 'employeeDetails' in 'field list'
</code>```

My current table format is:

Field: "userID", INT

Field: "id", INT

Field: "version", INT

答:
As stated in the doc https://www.npmjs.com/package/mysql#escaping-query-values :

Objects are turned into key = 'val' pairs for each enumerable property
  on the object. If the property's value is a function, it is skipped;
  if the property's value is an object, toString() is called on it and
  the returned value is used.

So you can't use nested objects because it's considered as a field.

You would instead do a loop through your array of objects :

```<code>var result2 = [{
  "id": 89304,
  "userId": 102524,
  "version": 9
}, {
  "id": 89305,
  "userId": 102522,
  "version": 99
}
}];
for(var i in result2) {
  var query = connection.query('INSERT INTO employees SET ?', result2[i],
  function(error, results, fields) {
    if (error) throw error;
  });
}
</code>```

Or more simply, if your goal is to accomplish a bulk INSERT, using nested arrays :

```<code>var result2 = [[89304, 102524, 9], [89305, 102522, 99]];
var query = connection.query('INSERT INTO employees(id, userId, version) VALUES ?', [result2],
function(error, results, fields) {
  if (error) throw error;
});
</code>```

There a method to convert from your original nested objects to Bulk INSERT :

```<code>var result2 = result2.map(function(el){
    return [el.id, el.employeeDetails.id, el.employeeDetails.version];
});
</code>```

Title: Insert nested JSON to MySQL using Node

Body:
I am using Node to INSERT JSON to MySQL, using Node.js

This works fine, until I have nested values.

Example of my JSON is here:

var result2 = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}, {
"id": 89305,
"employeeDetails": {
    "id": 102522,
    "version": 99
}
}];

Note: I am using the above for testing, as further on I want to call API requests in JSON and return them.

This is how I am sending it to MySQL using Node.js:

var query = connection.query('INSERT INTO employees SET ?', result2,
function(error, results, fields) {
    if (error) throw error;
});

Without nesting, this is working fine, however the nested employeeDetails gives me the following error:

Error: ER_BAD_FIELD_ERROR: Unknown column 'employeeDetails' in 'field list'

My current table format is:

Field: "userID", INT

Field: "id", INT

Field: "version", INT

Body:
As stated in the doc https://www.npmjs.com/package/mysql#escaping-query-values :

Objects are turned into key = 'val' pairs for each enumerable property
  on the object. If the property's value is a function, it is skipped;
  if the property's value is an object, toString() is called on it and
  the returned value is used.

So you can't use nested objects because it's considered as a field.

You would instead do a loop through your array of objects :

var result2 = [{
  "id": 89304,
  "userId": 102524,
  "version": 9
}, {
  "id": 89305,
  "userId": 102522,
  "version": 99
}
}];
for(var i in result2) {
  var query = connection.query('INSERT INTO employees SET ?', result2[i],
  function(error, results, fields) {
    if (error) throw error;
  });
}

Or more simply, if your goal is to accomplish a bulk INSERT, using nested arrays :

var result2 = [[89304, 102524, 9], [89305, 102522, 99]];
var query = connection.query('INSERT INTO employees(id, userId, version) VALUES ?', [result2],
function(error, results, fields) {
  if (error) throw error;
});

There a method to convert from your original nested objects to Bulk INSERT :

var result2 = result2.map(function(el){
    return [el.id, el.employeeDetails.id, el.employeeDetails.version];
});


问:
multithreading and strtok
I will be continually splitting strings in a multithreaded application, I've read that strtok is not suitable for this, but why?

Should I consider using a semaphore around the portion of my code that calls strtok?

答:
You'll need to use strtok_r.

In some non-standard implementations (most prominently Microsoft's), strtok stores its values in TLS (thread-local storage), so it should be fine to use in multiple threads at the same time. However, you cannot split your tokenization for one and the same string across multiple threads.

Title: multithreading and strtok


问:
Visual code multiple line selection
If I select some word and vscode see the same word in the code it highlights it. But is there any way to select all the lines that are highlighted?

答:
To select all the lines that are highlighted:

```<code>Ctrl+Shift+L  (and cmd+shift+L for mac)
</code>```

from vscode shortcuts reference

Title: Visual code multiple line selection

Body:
To select all the lines that are highlighted:

Ctrl+Shift+L  (and cmd+shift+L for mac)

from vscode shortcuts reference


问:
Arduino doesn't write to SD card?

Problem

I have an Arduino on an Adafruit feather mo. I am attempting to store data on an adalogger. The idea is simple. I have a potentiometer and I wish to write data from that potentiometer to an SD card. I can create, open, and close a CSV file, but I cannot write data from the potentiometer to the CSV file on the SD card.

Very rarely, I can get data from the sensor to write into the CSV file. However, I am not convinced this is a hardware issue, because I can see all the data in COM using Serial.println() just like I want from the potentiometer. It just won't write to the SD card. Can someone point out what I could be going wrong?

Code

This code works:

```<code>**Initalize Stuff**
//Project Dependencies
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include "RTClib.h"

// the setup function runs once when you press reset or power the board
//Global variables, usually associated with physical assets on the board
Sd2Card card;
SdVolume volume;
SdFile root;
char filename[13] = "";
File logfile;
int potPin = 2; //select the input pin for the potentiometer
const int chipSelect = 10;//chip select for SPID
File dataFile;
File sensorData;
bool fileOpen = false;

void setup() {
  //Step 1: Initialize Serial
  //================================================================
  Serial.begin(57600);
  //Step 1: Initialize the SD Card
  //================================================================
  //Step 1: Initialize the SD Card
  //================================================================
  Serial.println("Initializing SD card...");
  while (!SD.begin(chipSelect)) {
    // see if the card is present and can be initialized:
    Serial.println("...Card failed, or not present");
    delay(2000);
  }
  Serial.println("...Success.");
  if (card.init(SPI_HALF_SPEED, chipSelect))
    Serial.println("...Card initialized.");
  //// print the type of card
    Serial.print("\n...Card type: ");
    switch (card.type()) {
      case SD_CARD_TYPE_SD1:
        Serial.println("SD1");
        break;
      case SD_CARD_TYPE_SD2:
        Serial.println("SD2");
        break;
      case SD_CARD_TYPE_SDHC:
        Serial.println("SDHC");
        break;
      default:
        Serial.println("Unknown");
    }
    sprintf(filename, "%02d%02d%02d%02d.csv", now.month(), now.day(), now.hour(), now.minute());
    Serial.print("Initializing date file: ");
    Serial.println(filename);
    //Step 2: Create and open new logfile
    if (SD.exists(filename)) {
      Serial.print("...file ");
      Serial.print(filename);
      Serial.println(" already created before...Success.");
    } else {
      //File not found, so create it.
      dataFile = SD.open(filename, FILE_WRITE);
      if (!dataFile) {
        Serial.print("...Couldn't create ");
        Serial.println(filename);
      } else {
        Serial.print("...Success opening ");
        Serial.println(filename);
        Serial.print("...Starting size: ");
        Serial.print(dataFile.size());
        Serial.print(" bytes");
      }
      dataFile.close();
    }
  }
</code>```

Loop

This code doesn't work:

```<code>// the loop function runs over and over again until power down or reset
void loop() {
  int WriteEnabled = digitalRead(5); //This is when I turn a switch on to record, this works
  if (WriteEnabled) {
    sensorData = SD.open(filename, FILE_WRITE);
    if (sensorData) {
      uint32_t value = analogRead(potPin);
      //char line[27] = ""; //Define my input line
      //sprintf(line, "%04d/%02d/%02d, %02d:%02d:%02d, %04d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second(), value); //Doesn't work either, why?
      String dataString = String(value);
      sensorData.println(dataString);//This doesn't work
      Serial.println(dataString);
    }
  }
  if (!WriteEnabled && sensorData) {
    sensorData.close();
  }
}
</code>```

References

I have attempted to fix the problem by consulting several resources. Similar questions on Stack Overflow do not answer my problem.

Arduino SD Documentation

Arduino not writing to the SD card

SD Library API Documentation

Tried String and sprint. Should I try flush? But that doesn't match the documentation for SD library. Frustrating.

Update: Just tried using sensorData.flush() after println() command. Didn't work.

I have changed writing to the SD card by using String() and also sprint to help define the data. Nothing is working. I don't think it is a hardware problem because I can open and close a file, but just not write any data. Can someone please help me out? If someone suspects hardware, please let me know why. I really doubt it because why can I create a file on SD card and see potentiometer values in COM but not store them?

答:
Try changing the code so that the open call only happens when the WriteEnable flag changes from false to true. Do the opposite for the close call.

To more directly match the Arduino Reference move the close call to be just after the write.

Title: Arduino doesn't write to SD card?

Body:
Problem

I have an Arduino on an Adafruit feather mo. I am attempting to store data on an adalogger. The idea is simple. I have a potentiometer and I wish to write data from that potentiometer to an SD card. I can create, open, and close a CSV file, but I cannot write data from the potentiometer to the CSV file on the SD card.

Very rarely, I can get data from the sensor to write into the CSV file. However, I am not convinced this is a hardware issue, because I can see all the data in COM using Serial.println() just like I want from the potentiometer. It just won't write to the SD card. Can someone point out what I could be going wrong?

Code

This code works:

**Initalize Stuff**
//Project Dependencies
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include "RTClib.h"

// the setup function runs once when you press reset or power the board
//Global variables, usually associated with physical assets on the board
Sd2Card card;
SdVolume volume;
SdFile root;
char filename[13] = "";
File logfile;
int potPin = 2; //select the input pin for the potentiometer
const int chipSelect = 10;//chip select for SPID
File dataFile;
File sensorData;
bool fileOpen = false;

void setup() {
  //Step 1: Initialize Serial
  //================================================================
  Serial.begin(57600);
  //Step 1: Initialize the SD Card
  //================================================================
  //Step 1: Initialize the SD Card
  //================================================================
  Serial.println("Initializing SD card...");
  while (!SD.begin(chipSelect)) {
    // see if the card is present and can be initialized:
    Serial.println("...Card failed, or not present");
    delay(2000);
  }
  Serial.println("...Success.");
  if (card.init(SPI_HALF_SPEED, chipSelect))
    Serial.println("...Card initialized.");
  //// print the type of card
    Serial.print("\n...Card type: ");
    switch (card.type()) {
      case SD_CARD_TYPE_SD1:
        Serial.println("SD1");
        break;
      case SD_CARD_TYPE_SD2:
        Serial.println("SD2");
        break;
      case SD_CARD_TYPE_SDHC:
        Serial.println("SDHC");
        break;
      default:
        Serial.println("Unknown");
    }
    sprintf(filename, "%02d%02d%02d%02d.csv", now.month(), now.day(), now.hour(), now.minute());
    Serial.print("Initializing date file: ");
    Serial.println(filename);
    //Step 2: Create and open new logfile
    if (SD.exists(filename)) {
      Serial.print("...file ");
      Serial.print(filename);
      Serial.println(" already created before...Success.");
    } else {
      //File not found, so create it.
      dataFile = SD.open(filename, FILE_WRITE);
      if (!dataFile) {
        Serial.print("...Couldn't create ");
        Serial.println(filename);
      } else {
        Serial.print("...Success opening ");
        Serial.println(filename);
        Serial.print("...Starting size: ");
        Serial.print(dataFile.size());
        Serial.print(" bytes");
      }
      dataFile.close();
    }
  }

Loop

This code doesn't work:

// the loop function runs over and over again until power down or reset
void loop() {
  int WriteEnabled = digitalRead(5); //This is when I turn a switch on to record, this works
  if (WriteEnabled) {
    sensorData = SD.open(filename, FILE_WRITE);
    if (sensorData) {
      uint32_t value = analogRead(potPin);
      //char line[27] = ""; //Define my input line
      //sprintf(line, "%04d/%02d/%02d, %02d:%02d:%02d, %04d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second(), value); //Doesn't work either, why?
      String dataString = String(value);
      sensorData.println(dataString);//This doesn't work
      Serial.println(dataString);
    }
  }
  if (!WriteEnabled && sensorData) {
    sensorData.close();
  }
}

References

I have attempted to fix the problem by consulting several resources. Similar questions on Stack Overflow do not answer my problem.

Arduino SD Documentation

Arduino not writing to the SD card

SD Library API Documentation

Tried String and sprint. Should I try flush? But that doesn't match the documentation for SD library. Frustrating.

Update: Just tried using sensorData.flush() after println() command. Didn't work.

I have changed writing to the SD card by using String() and also sprint to help define the data. Nothing is working. I don't think it is a hardware problem because I can open and close a file, but just not write any data. Can someone please help me out? If someone suspects hardware, please let me know why. I really doubt it because why can I create a file on SD card and see potentiometer values in COM but not store them?


问:
Variadic functions addition in c++ with constrained types
My goal is to do a simple addition of any number of parameters as long as they are of the following types -

integer (e.g. 123)

string represented as integer (e.g. "123")

If they are of some other type, I ignore them.

Approach

I'm using a variadic function approach.

Within the function, I check for type. If the type is int, then I add recursively. Else, I ignore the argument, and recur on further arguments.

Here's what I think the code looks like --

```<code>// BASE
template <typename T>
int func(T t)
{
    string type= typeid(t).name();
    if (type==typeid(int).name())
        return stoi(t);
    else if (type==typeid(const char*).name())
        return atoi(t);
    else
        return 0;
}
// RECUR
template<typename T, typename... Args>
int func(T t, Args... args) // recursive variadic function
{
    string type = typeid(t).name();
    if (type==typeid(int).name()){
        int sum = t;
        return sum+func(args...);
    }
    else
        return func(args...);

}

// MAIN
int main()
{
    // All testing here in MAIN.

    // [2]
    int funcres = func('a',1, 2.5000,"123");
    cout << funcres << endl;

    return 0;
}
</code>```

This gives me the expected answer: 124.

However,
I made following observations which tell me that my code is not fail-safe.

Why is stoi required in this line of the base function?

if (type==typeid(int).name())
            return stoi(t);

If I do not do this and call just return t, I get an error when I call my function.

```<code>Cannot initialize return object of type 'int' with an lvalue of type 'const char *'
</code>```

This doesn't make sense to me when I've already specified that return the integer if the type is integer.

Even after I do return stoi(t) (which I don't understand why is required in the first place), and return atoi(t) if the type is const char* then inserting "japan" or "123" at the beginning or in the middle in the template arg list [for.e.g func(1,2,2.5000,"123",12);] causes the code to complain at this point.

int sum = t;

The error is same as above.

```<code>Cannot initialize return object of type 'int' with an lvalue of type 'const char *'
</code>```

Is using variadic function the best way or are there alternatives?

If it's the best way (it seems so to me since I need any number of parameters and any type of parameters to be considered for adding), what am I doing wrong?

答:
C++ templates are resolved statically, meaning that substituting the parameters has to work for all substitutions, even those which are unreachable at runtime. However by using overloads with a helper function instead of RTTI we can handle the conversion a lot more cleanly:

```<code>template<class T>
int forceInt(T arg) { return 0; }

int forceInt(int arg) { return arg; }

int forceInt(std::string arg) { return std::stoi(arg); }

int forceInt(const char * arg) { return std::stoi(arg); }
</code>```

With this helper function you can do a simple recursive sum:

```<code>int func() { return 0; }

template<typename T, typename... Args>
int func(T t, Args... args) // recursive variadic function
{

        return forceInt(t) + func(args...);
}
</code>```

This can also be expanded to handle any integer type. By using SFINAE on the general overload to restrict it to non-integer types, this causes the int overload to become prefered for integral types. However char is integral so we also need to add a char overload of 0 if you don't want that to be implicitly converted to an int:

```<code>template<class T, class U = typename std::enable_if<!std::is_integral<T>::value>::type>
int forceInt(T arg) { return 0; }

int forceInt(char arg) {return 0;}
</code>```

Body:
My goal is to do a simple addition of any number of parameters as long as they are of the following types -

integer (e.g. 123)

string represented as integer (e.g. "123")

If they are of some other type, I ignore them.

Approach

I'm using a variadic function approach.

Within the function, I check for type. If the type is int, then I add recursively. Else, I ignore the argument, and recur on further arguments.

Here's what I think the code looks like --

// BASE
template <typename T>
int func(T t)
{
    string type= typeid(t).name();
    if (type==typeid(int).name())
        return stoi(t);
    else if (type==typeid(const char*).name())
        return atoi(t);
    else
        return 0;
}
// RECUR
template<typename T, typename... Args>
int func(T t, Args... args) // recursive variadic function
{
    string type = typeid(t).name();
    if (type==typeid(int).name()){
        int sum = t;
        return sum+func(args...);
    }
    else
        return func(args...);

}

// MAIN
int main()
{
    // All testing here in MAIN.

    // [2]
    int funcres = func('a',1, 2.5000,"123");
    cout << funcres << endl;

    return 0;
}

This gives me the expected answer: 124.

However,
I made following observations which tell me that my code is not fail-safe.

Why is stoi required in this line of the base function?

if (type==typeid(int).name())
            return stoi(t);

If I do not do this and call just return t, I get an error when I call my function.

Cannot initialize return object of type 'int' with an lvalue of type 'const char *'

This doesn't make sense to me when I've already specified that return the integer if the type is integer.

Even after I do return stoi(t) (which I don't understand why is required in the first place), and return atoi(t) if the type is const char* then inserting "japan" or "123" at the beginning or in the middle in the template arg list [for.e.g func(1,2,2.5000,"123",12);] causes the code to complain at this point.

int sum = t;

The error is same as above.

Cannot initialize return object of type 'int' with an lvalue of type 'const char *'

Is using variadic function the best way or are there alternatives?

If it's the best way (it seems so to me since I need any number of parameters and any type of parameters to be considered for adding), what am I doing wrong?

Body:
C++ templates are resolved statically, meaning that substituting the parameters has to work for all substitutions, even those which are unreachable at runtime. However by using overloads with a helper function instead of RTTI we can handle the conversion a lot more cleanly:

template<class T>
int forceInt(T arg) { return 0; }

int forceInt(int arg) { return arg; }

int forceInt(std::string arg) { return std::stoi(arg); }

int forceInt(const char * arg) { return std::stoi(arg); }

With this helper function you can do a simple recursive sum:

int func() { return 0; }

template<typename T, typename... Args>
int func(T t, Args... args) // recursive variadic function
{

        return forceInt(t) + func(args...);
}

This can also be expanded to handle any integer type. By using SFINAE on the general overload to restrict it to non-integer types, this causes the int overload to become prefered for integral types. However char is integral so we also need to add a char overload of 0 if you don't want that to be implicitly converted to an int:

template<class T, class U = typename std::enable_if<!std::is_integral<T>::value>::type>
int forceInt(T arg) { return 0; }

int forceInt(char arg) {return 0;}


问:
Difference between numpy dot() and Python 3.5+ matrix multiplication @
I recently moved to Python 3.5 and noticed the new matrix multiplication operator (@) sometimes behaves differently from the numpy dot operator. In example, for 3d arrays:

```<code>import numpy as np

a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b  # Python 3.5+
d = np.dot(a, b)
</code>```

The @ operator returns an array of shape:

```<code>c.shape
(8, 13, 13)
</code>```

while the np.dot() function returns:

```<code>d.shape
(8, 13, 8, 13)
</code>```

How can I reproduce the same result with numpy dot? Are there any other significant differences?

答:
The answer by @ajcr explains how the dot and matmul (invoked by the @ symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.

To clarify the differences take a 4x4 array and return the dot product and matmul product with a 3x4x2 'stack of matricies' or tensor.

```<code>import numpy as np
fourbyfour = np.array([
                       [1,2,3,4],
                       [3,2,1,4],
                       [5,4,6,7],
                       [11,12,13,14]
                      ])

threebyfourbytwo = np.array([
                             [[2,3],[11,9],[32,21],[28,17]],
                             [[2,3],[1,9],[3,21],[28,7]],
                             [[2,3],[1,9],[3,21],[28,7]],
                            ])

print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))
</code>```

The products of each operation appear below. Notice how the dot product is,

...a sum product over the last axis of a and the second-to-last of b

and how the matrix product is formed by broadcasting the matrix together.

```<code>4x4*3x4x2 dot:
 [[[232 152]
  [125 112]
  [125 112]]

 [[172 116]
  [123  76]
  [123  76]]

 [[442 296]
  [228 226]
  [228 226]]

 [[962 652]
  [465 512]
  [465 512]]]

4x4*3x4x2 matmul:
 [[[232 152]
  [172 116]
  [442 296]
  [962 652]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]]
</code>```

Body:
I recently moved to Python 3.5 and noticed the new matrix multiplication operator (@) sometimes behaves differently from the numpy dot operator. In example, for 3d arrays:

import numpy as np

a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b  # Python 3.5+
d = np.dot(a, b)

The @ operator returns an array of shape:

c.shape
(8, 13, 13)

while the np.dot() function returns:

d.shape
(8, 13, 8, 13)

How can I reproduce the same result with numpy dot? Are there any other significant differences?

Body:
The answer by @ajcr explains how the dot and matmul (invoked by the @ symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.

To clarify the differences take a 4x4 array and return the dot product and matmul product with a 3x4x2 'stack of matricies' or tensor.

import numpy as np
fourbyfour = np.array([
                       [1,2,3,4],
                       [3,2,1,4],
                       [5,4,6,7],
                       [11,12,13,14]
                      ])

threebyfourbytwo = np.array([
                             [[2,3],[11,9],[32,21],[28,17]],
                             [[2,3],[1,9],[3,21],[28,7]],
                             [[2,3],[1,9],[3,21],[28,7]],
                            ])

print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))

The products of each operation appear below. Notice how the dot product is,

...a sum product over the last axis of a and the second-to-last of b

and how the matrix product is formed by broadcasting the matrix together.

4x4*3x4x2 dot:
 [[[232 152]
  [125 112]
  [125 112]]

 [[172 116]
  [123  76]
  [123  76]]

 [[442 296]
  [228 226]
  [228 226]]

 [[962 652]
  [465 512]
  [465 512]]]

4x4*3x4x2 matmul:
 [[[232 152]
  [172 116]
  [442 296]
  [962 652]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]]


问:
Learning PowerShell. Create usernames no longer than 8 characters and check for collision
I'm learning powershell right now.

I need to import a CSV like this:
lastname,firstname
lastname,firstname
lastname,firstname
etc

Then create a list of usernames no longer then 8 characters and check for collisions.

I have found bits and pieces of scripting around but not sure how to tie it all together.

I use Import-Csv to import my file.csv:

```<code>$variablename = import-csv C:\path\to\file.csv
</code>```

but then I am not sure if I just import it into an array or not. I am not familiar with how for loops work in powershell exactly.

Any direction? Thanks.

答:
There are a couple of concepts that are central to understanding PowerShell. Firstly, remember that you are always working with objects. So after importing your CSV file, your $variablename will refer to a collection of sub-objects.

Secondly, you can use the PowerShell pipeline to send the output of one cmdlet to the input of another. Some cmdlets will understand if you send them a collection, and automatically process each row.

If think what you're looking for though is the foreach-object cmdlet, which will allow you to run code against each item in the collection. Code inside the foreach-object block can refer to the $_ automatic variable which will contain the current object.

Assuming your CSV file is well formatted and has a header row with the column names, you can refer to each column by name e.g. $_.lastname & $_.firstname.

To put it all together:

```<code>import-csv C:\path\to\file.csv |
    foreach-object {
        write-host "Processing: $($_.lastname), $($_.firstname)"
        # logic here to calculate username and create AD account
    }
</code>```

PowerShell can have a bit of a learning curve if you are coming from a different scripting environment. Here are a couple of resources that I've found helpful:

PowerShell 'gotchas' http://www.rlmueller.net/PSGotchas.htm

Keith Hill's Effective PowerShell: https://rkeithhill.wordpress.com/2009/03/08/effective-windows-powershell-the-free-ebook/

Also, check out the Technet Script Center, where there are many hundreds of Active Directory scripts. https://technet.microsoft.com/en-us/scriptcenter/bb410849.aspx

Body:
I'm learning powershell right now.

I need to import a CSV like this:
lastname,firstname
lastname,firstname
lastname,firstname
etc

Then create a list of usernames no longer then 8 characters and check for collisions.

I have found bits and pieces of scripting around but not sure how to tie it all together.

I use Import-Csv to import my file.csv:

$variablename = import-csv C:\path\to\file.csv

but then I am not sure if I just import it into an array or not. I am not familiar with how for loops work in powershell exactly.

Any direction? Thanks.

Body:
There are a couple of concepts that are central to understanding PowerShell. Firstly, remember that you are always working with objects. So after importing your CSV file, your $variablename will refer to a collection of sub-objects.

Secondly, you can use the PowerShell pipeline to send the output of one cmdlet to the input of another. Some cmdlets will understand if you send them a collection, and automatically process each row.

If think what you're looking for though is the foreach-object cmdlet, which will allow you to run code against each item in the collection. Code inside the foreach-object block can refer to the $_ automatic variable which will contain the current object.

Assuming your CSV file is well formatted and has a header row with the column names, you can refer to each column by name e.g. $_.lastname & $_.firstname.

To put it all together:

import-csv C:\path\to\file.csv |
    foreach-object {
        write-host "Processing: $($_.lastname), $($_.firstname)"
        # logic here to calculate username and create AD account
    }

PowerShell can have a bit of a learning curve if you are coming from a different scripting environment. Here are a couple of resources that I've found helpful:

PowerShell 'gotchas' http://www.rlmueller.net/PSGotchas.htm

Keith Hill's Effective PowerShell: https://rkeithhill.wordpress.com/2009/03/08/effective-windows-powershell-the-free-ebook/

Also, check out the Technet Script Center, where there are many hundreds of Active Directory scripts. https://technet.microsoft.com/en-us/scriptcenter/bb410849.aspx


问:
Show contents for subdomain from folder
how can I do something like this: (possibly with .htaccess? or something else, need the fastest way)

subdomain:

```<code>subdomain.example.com
</code>```

shows content from:

```<code>https://example.com/folder/index.php?name=subdomain
</code>```

what would be the fastest way to do this?

also, do i have to setup anything in ubuntu, apache, or dns?

答:
add a  VirtualHost entry for Apache config:

```<code><VirtualHost *:80>
    ServerName subdomain.example.com
    ServerAlias example.com
    DocumentRoot /folder/index.php
</VirtualHost>
</code>```

change the document root to match your server path

Title: Show contents for subdomain from folder

Body:
how can I do something like this: (possibly with .htaccess? or something else, need the fastest way)

subdomain:

subdomain.example.com

shows content from:

https://example.com/folder/index.php?name=subdomain

what would be the fastest way to do this?

also, do i have to setup anything in ubuntu, apache, or dns?

Body:
add a  VirtualHost entry for Apache config:

<VirtualHost *:80>
    ServerName subdomain.example.com
    ServerAlias example.com
    DocumentRoot /folder/index.php
</VirtualHost>

change the document root to match your server path


问:
Can not change original file name,Compiler Error Message: CS0433:
It's a little bit complicated.I got a .net class library project form someone else and added it in my solution referenced by a asp.net mvc project. For some reason I changed the project name form "abc" to "xyz" and also Assembly name, Default namespace name in project properties page. I could build the solution and get the xyz.dll in the bin folder.
The problem is I can't run the web application because of the error "Compiler Error Message: CS0433:". I looked into the folder "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\" and found out the abc.dll still there and I checked the file detail information on properties page. The file description and product name are the same xyz, but the original filename is still abc.dll. I really don't know what's going on here.
I wish some could help me out,Thanks in advance.</p>

答:
You probably have figure it out but for other peoples who might search for the solution.
Right click on your solution or project file ->  Click on properties ->  And then there is first tab with name application Click on that. You will find two text box one for Assembly Name (Change this to xyz).
see attached image.properties dialogue box</p>


问:
Java web service frameworks
This is my first time with Web services. I have to develop web services in java which should be having good WS-* standards, should loosely-coupled, scalable, highly secure, fast response time. I know I've to consider trade-offs. I have checked on some frameworks like Axis2, CXF, Spring WS. Please share your experiences and views on these frameworks and other frameworks, which will help me in deciding which one to go to.</p>

答:
Metro is the JAX-WS reference implementation with support for various WS-* specification. I find it easy to understand and use. It provides interoperability with the Microsoft .NET WCF stack and integration with Spring, Netbeans, Maven2 and ant.

Metro is fully supported on Glassfish and both can be installed together easily with the latest Glassfish v3 prelude (commercial support available from Sun).

The Metro's homepage reference a web services stack comparison at the Apache WS Wiki.

OwnerDisplayName: kaychaks

Title: Java web service frameworks


问:
Why can I off a mousedown event, but not its chained mouseup event?
I have two chained mouse-events:

```<code>$('body > form').on("mousedown", function(e){
    //Do stuff
}).on("mouseup", function(){
    /*More stuff, including
       window.addEventListener(...
    */
});
</code>```

However, when I try to off() them both from another external function, I can only off() mousedown, but not mouseup, whose functionality continues to work.

Could that nested addEventListener be preventing me from offing its event?  (

By the way, it doesn't matter how I
chain: ($().off().off();), or unchain ($().off(); $().off();), or combine ($().off(A B);) or reverse (A B <-> B A) the elements; consistently, off(mousedown) works, but never off(up).

Here's my full JS code:

(The problematic part is the 2nd script, at the end:)

```<code><script>
function comment() {

    $('body > form').on("mousedown.markerPlacer", function(e){
     //Place the cursor marker on the screen

        var newComment2 = $('<div id="newComm" class="marker" class="deg45" ↑</div>');
        $('form').append(newComment2);

    }).on("mouseup", function(){
    //Now use the Q-key to rotate the marker.

       window.addEventListener("keydown", extraKey, false);
       window.addEventListener("keyup", keysReleased2, false);

            function extraKey(e) {
                var deg = e.keyCode;
                    if (deg == 81)  { //81 is the keycode, which codes for Q
                        $('#newComm').attr('class', 'marker').addClass('deg0');
                    } else {
                        return false;
                    };
                    e.preventDefault();
            };
            function keysReleased2(e) {
                e.keyCode = false;
            };
    });
};
</script>

<script>
function dismissComment() {
        $('body > form').off("mousedown mouseup");
}
</script>
</code>```

答:
Out of curiosity I wrote a similar chained mousedown and mouseup as shown in your code.

And I unbind them on button click.
It seems to work fine and I'm not able to reproduce your issues.

It's able to "off" both mousedown and mouseup event listener.

```<code>$("#testMe")
  .on("mousedown", function(e) {
    appendText(getButton(e.button) + " | " + $(this).attr("id") + " | " + "mouseDOWN | " + new Date());
  })
  .on("mouseup", function(e) {
    appendText(getButton(e.button) + " | " + $(this).attr("id") + " | " + "mouseUP | " + new Date());

    $(document).off("keydown keyup");
    $(document).on("keydown", keydown_pressed);
    $(document).on("keyup", keyup_pressed);
  });
</code>```

Unbind / "off" code

```<code>$("#unbind").click(function(e) {
  $("#testMe").off("mousedown mouseup");
  $(document).off("keydown keyup");
});
</code>```

On page load, mousedown and mouseup are attached to input textbox.

After mouseclick on textbox, window keydown and keyup event listeners are added.

After I "off" or unbind, all event listeners are removed.

jsfiddle link

Body:
I have two chained mouse-events:

$('body > form').on("mousedown", function(e){
    //Do stuff
}).on("mouseup", function(){
    /*More stuff, including
       window.addEventListener(...
    */
});

However, when I try to off() them both from another external function, I can only off() mousedown, but not mouseup, whose functionality continues to work.

Could that nested addEventListener be preventing me from offing its event?  (

By the way, it doesn't matter how I
chain: ($().off().off();), or unchain ($().off(); $().off();), or combine ($().off(A B);) or reverse (A B <-> B A) the elements; consistently, off(mousedown) works, but never off(up).

Here's my full JS code:

(The problematic part is the 2nd script, at the end:)

Body:
Out of curiosity I wrote a similar chained mousedown and mouseup as shown in your code.

And I unbind them on button click.
It seems to work fine and I'm not able to reproduce your issues.

It's able to "off" both mousedown and mouseup event listener.

$("#testMe")
  .on("mousedown", function(e) {
    appendText(getButton(e.button) + " | " + $(this).attr("id") + " | " + "mouseDOWN | " + new Date());
  })
  .on("mouseup", function(e) {
    appendText(getButton(e.button) + " | " + $(this).attr("id") + " | " + "mouseUP | " + new Date());

    $(document).off("keydown keyup");
    $(document).on("keydown", keydown_pressed);
    $(document).on("keyup", keyup_pressed);
  });

Unbind / "off" code

$("#unbind").click(function(e) {
  $("#testMe").off("mousedown mouseup");
  $(document).off("keydown keyup");
});

On page load, mousedown and mouseup are attached to input textbox.

After mouseclick on textbox, window keydown and keyup event listeners are added.

After I "off" or unbind, all event listeners are removed.

jsfiddle link


问:
How to access nutrition facts data from Google search?
I am trying to extract the data you get from googling nutrition facts. For example, when you search "1 lb of chicken nutrition facts" it will return links (per usual), but also give valuable nutrition information. I wanted parse the information shown in the nutrition fact section with BeautifulSoup in Python, but have had no luck.</p>

答: If memory serves, the Google results for generic foods often come from the USDA data. The USDA has an API you can probably tap into. </p>


问:
Vuejs 2 + splice
I'd like to know why when I use splice in VueJS 2 it removes the last index instead of the index that I want.
Have a look at this example https://jsfiddle.net/tiagomatosweb/t121ufk5/

```<code>removeSection: function(index) {

            this.sections.splice(index, 1)
    },
</code>```

What I am missing?

UPDATE

I found the reason why it wasn't removing the right array. Actually, it was, but the select wasn't updating.

1) I was using the internal model var for the select v-model="fruitId", for instance.
2) It has to be external var, that comes from the section, as you wrote v-model="section.fruit".

That makes the trick.

Then I come back to use the Vuejs index and worked very well.

https://jsfiddle.net/tiagomatosweb/t121ufk5/2

Title: Vuejs 2 + splice

Body:
I'd like to know why when I use splice in VueJS 2 it removes the last index instead of the index that I want.
Have a look at this example https://jsfiddle.net/tiagomatosweb/t121ufk5/

removeSection: function(index) {

            this.sections.splice(index, 1)
    },

What I am missing?

UPDATE

I found the reason why it wasn't removing the right array. Actually, it was, but the select wasn't updating.

1) I was using the internal model var for the select v-model="fruitId", for instance.
2) It has to be external var, that comes from the section, as you wrote v-model="section.fruit".

That makes the trick.

Then I come back to use the Vuejs index and worked very well.

https://jsfiddle.net/tiagomatosweb/t121ufk5/2