答:
Use position: absolute on the two elements and consider the additional 20px for widths and positions caused by the padding of the footer. Also don't forget to reset the padding for the ul. See the code in my snippet for details:

html,
body {
  margin: 0;
}

footer {
  box-sizing: border-box;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 70px;
  padding: 0 20px;
  background-color: #262626;
}

.test {
  position: absolute;
  display: inline-block;
  top: 50%;
  width: calc(50% - 20px);
  transform: translateY(-50%);
}

footer p {
  font-size: 100%;
  color: #888;
}

.social-links {
  position: absolute;
  left: calc(50% - 20px);
  top: 50%;
  width: calc(50% - 20px);
  transform: translateY(-50%);
  text-align: right;
  margin: 0;
  padding: 0;
}

.social-links ul {}

.social-links li {
  display: inline-block;
  margin-right: 35px;
  text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="test">
    <p>Footer Text</p>
  </div>
  <ul class="social-links">
    <li>Link 1</li>
    <li>Link 2</li>
  </ul>
</footer></code>```

Title: I don't understand why these two elements are not aligning side by side?

Body:
Use position: absolute on the two elements and consider the additional 20px for widths and positions caused by the padding of the footer. Also don't forget to reset the padding for the ul. See the code in my snippet for details:

html,
body {
  margin: 0;
}

footer {
  box-sizing: border-box;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 70px;
  padding: 0 20px;
  background-color: #262626;
}

.test {
  position: absolute;
  display: inline-block;
  top: 50%;
  width: calc(50% - 20px);
  transform: translateY(-50%);
}

footer p {
  font-size: 100%;
  color: #888;
}

.social-links {
  position: absolute;
  left: calc(50% - 20px);
  top: 50%;
  width: calc(50% - 20px);
  transform: translateY(-50%);
  text-align: right;
  margin: 0;
  padding: 0;
}

.social-links ul {}

.social-links li {
  display: inline-block;
  margin-right: 35px;
  text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}

<footer>
  <div class="test">
    <p>Footer Text</p>
  </div>
  <ul class="social-links">
    <li>Link 1</li>
    <li>Link 2</li>
  </ul>
</footer>


来源: stackexchange

问:
C# and SQLite: "no such table error" when using relative path?
I am having issues connecting to my sqlite database. The file is located in the application's folder. Here is the connection string

```<code>string path = "Data Source=MY.db";
</code>```

I can get it to work if I use the absolute path, but it gives me a "table not found" error if I try to use a relative path. Any ideas?

答:
This happened when you haven't saved the database and its table while using GUI Manager for SQLite .
Two solution;
1) Save your database and its table with CTR+S in GUI Manager
2) Or Simply Just close your GUI manager of SQlite and save all .

Important !  I am using GUI manger for SQLITE (DB Browser for SQLITE) and its all about that.

ContentLicense: CC BY-SA 3.0

Body:
I am having issues connecting to my sqlite database. The file is located in the application's folder. Here is the connection string

string path = "Data Source=MY.db";

I can get it to work if I use the absolute path, but it gives me a "table not found" error if I try to use a relative path. Any ideas?


问:
Update Map based on another nested Map iteration
Immutability in Elixir is really blowing my mind and makes the languages so confusing to use. I need to iterate a nested map and simple update some counts based on the iteration, but Enum.reduce just makes it difficult for me. Say I have:

```<code>defmodule Predictor do

  def past_matches() do
    [
      team1: %{team2: %{f: 0, a: 1},  team3: %{f: 1, a: 3}},
      team2: %{team1: %{f: 3, a: 0},  team3: %{f: 2, a: 0}},
      team3: %{team1: %{f: 1, a: 0},  team2: %{f: 0, a: 1}},
    ]
  end

  def init_indexes(matches) do
    local = Enum.reduce matches, %{}, fn({team, _scores}, acc) ->
      Map.put acc, team, %{f: 0, a: 0, n_games: 0}
    end

    Enum.each matches, fn({team, scores}) ->
      Enum.each scores, fn({vteam, %{f: ff, a: aa}}) ->
        %{f: fi, a: ai, n_games: ni} = local[team]
        put_in(local[team], %{f: fi+ff, a: ai+aa, n_games: ni+1})
      end
    end

    local
  end

  def run() do
    local = past_matches() |> init_indexes()
  end
end
</code>```

I need local to just sum f,a and n_games.

```<code>local = %{
    team1: %{f: 1, a: 4, n_games: 2}
    ...
}
</code>```

At the end of run() obviously the Map local has all 0's and no updated value.

答:
There are a couple of things I can see off the bat that are tripping you up:

Enum.each/2 will apply a function to every item in a list, but it doesn't accumulate the results or modify the original list in any way. I can't remember the last time I used Enum.each -- it has its place, but it's pretty rare.

What that means is that the places where you're calling local[team] aren't actually updating any values because that output is not being passed through to anything else. It's essentially just sending those changes into the ether.

The solution: pipes! I promise you that the |> pipe operator will change your life. It's a little mind-boggly at first if you come from an OO background, but stick with it and I promise you will never want to go back. The shift in thinking that helped me wrap my head around it was to use as few anonymous functions as possible at first. It helped me adjust to the concept of immutability because it forced me to think about what values each function actually needs, and how to pass those values to each function.

Here's my stab at rewriting your module using a more pipeline-centric approach -- hope it helps. It produces the expected results when you run it in IEx. I'm happy to clarify anything if you have questions.

```<code>defmodule Predictor do

  @past_matches [
    team1: %{
      team2: %{f: 0, a: 1},
      team3: %{f: 1, a: 3}
    },
    team2: %{
      team1: %{f: 3, a: 0},
      team3: %{f: 2, a: 0}
    },
    team3: %{
      team1: %{f: 1, a: 0},
      team2: %{f: 0, a: 1}
    }
  ]

  # see note 1
  @baseline %{f: 0, a: 0, n_games: 0}

  def run(past_matches \\ @past_matches) do
    past_matches
    |> Enum.map(&build_histories/1)
    |> Enum.into(%{})
    # see note 2
  end

  def build_histories({team, scores}) do
    history = Enum.reduce(scores, @baseline, &build_history/2)
    {team, history}
  end

  def build_history({_vteam, vresults}, acc) do
    # see note 3
    %{acc | f: acc.f + vresults.f,
            a: acc.a + vresults.a,
            n_games: acc.n_games + 1}
  end
end

(1) since the baseline is the same for every team, you can
    set it as a module attribute -- basically like setting a global
    (immutable) variable that you can use as a starting point for a new
    value. Another option would be to create a %BaseLine{} struct that
    has default values.

(2) you could also use `Enum.reduce/2` here instead, but this does
    effectively the same thing -- the output of the `Enum.map/1`
    call is a list of {atom, _val} which is interpreted as a Keyword
    list; calling `Enum.into(%{}) turns a Keyword list into a map
    (and vice versa with `Enum.into([])`).

(3) NB:  %{map | updated_key: updated_val} only works on maps or
    structs where the key to be updated already exists -- it'll throw
    an error if the key isn't found on the original map.
</code>```

Body:
Immutability in Elixir is really blowing my mind and makes the languages so confusing to use. I need to iterate a nested map and simple update some counts based on the iteration, but Enum.reduce just makes it difficult for me. Say I have:

defmodule Predictor do

  def past_matches() do
    [
      team1: %{team2: %{f: 0, a: 1},  team3: %{f: 1, a: 3}},
      team2: %{team1: %{f: 3, a: 0},  team3: %{f: 2, a: 0}},
      team3: %{team1: %{f: 1, a: 0},  team2: %{f: 0, a: 1}},
    ]
  end

  def init_indexes(matches) do
    local = Enum.reduce matches, %{}, fn({team, _scores}, acc) ->
      Map.put acc, team, %{f: 0, a: 0, n_games: 0}
    end

    Enum.each matches, fn({team, scores}) ->
      Enum.each scores, fn({vteam, %{f: ff, a: aa}}) ->
        %{f: fi, a: ai, n_games: ni} = local[team]
        put_in(local[team], %{f: fi+ff, a: ai+aa, n_games: ni+1})
      end
    end

    local
  end

  def run() do
    local = past_matches() |> init_indexes()
  end
end

I need local to just sum f,a and n_games.

local = %{
    team1: %{f: 1, a: 4, n_games: 2}
    ...
}

At the end of run() obviously the Map local has all 0's and no updated value.

Body:
There are a couple of things I can see off the bat that are tripping you up:

Enum.each/2 will apply a function to every item in a list, but it doesn't accumulate the results or modify the original list in any way. I can't remember the last time I used Enum.each -- it has its place, but it's pretty rare.

What that means is that the places where you're calling local[team] aren't actually updating any values because that output is not being passed through to anything else. It's essentially just sending those changes into the ether.

The solution: pipes! I promise you that the |> pipe operator will change your life. It's a little mind-boggly at first if you come from an OO background, but stick with it and I promise you will never want to go back. The shift in thinking that helped me wrap my head around it was to use as few anonymous functions as possible at first. It helped me adjust to the concept of immutability because it forced me to think about what values each function actually needs, and how to pass those values to each function.

Here's my stab at rewriting your module using a more pipeline-centric approach -- hope it helps. It produces the expected results when you run it in IEx. I'm happy to clarify anything if you have questions.

defmodule Predictor do

  @past_matches [
    team1: %{
      team2: %{f: 0, a: 1},
      team3: %{f: 1, a: 3}
    },
    team2: %{
      team1: %{f: 3, a: 0},
      team3: %{f: 2, a: 0}
    },
    team3: %{
      team1: %{f: 1, a: 0},
      team2: %{f: 0, a: 1}
    }
  ]

  # see note 1
  @baseline %{f: 0, a: 0, n_games: 0}

  def run(past_matches \\ @past_matches) do
    past_matches
    |> Enum.map(&build_histories/1)
    |> Enum.into(%{})
    # see note 2
  end

  def build_histories({team, scores}) do
    history = Enum.reduce(scores, @baseline, &build_history/2)
    {team, history}
  end

  def build_history({_vteam, vresults}, acc) do
    # see note 3
    %{acc | f: acc.f + vresults.f,
            a: acc.a + vresults.a,
            n_games: acc.n_games + 1}
  end
end

(1) since the baseline is the same for every team, you can
    set it as a module attribute -- basically like setting a global
    (immutable) variable that you can use as a starting point for a new
    value. Another option would be to create a %BaseLine{} struct that
    has default values.

(2) you could also use `Enum.reduce/2` here instead, but this does
    effectively the same thing -- the output of the `Enum.map/1`
    call is a list of {atom, _val} which is interpreted as a Keyword
    list; calling `Enum.into(%{}) turns a Keyword list into a map
    (and vice versa with `Enum.into([])`).

(3) NB:  %{map | updated_key: updated_val} only works on maps or
    structs where the key to be updated already exists -- it'll throw
    an error if the key isn't found on the original map.


问:
Query generated by Hibernate
I have my service up and running but there's still a few things i can't figure out.

I have a query that is similar to the following

@Query("SELECT t FROM Tablename t")

Then hibernate will generate the following query

Hibernate: select tname.column1 as a, tname.column2 as b, tname.column3 as c, tname.column4 as d from tablename tname

The problem is that Tablename is case sensitive when i query against a mysql database. Is there a way in hibernate to execute the query exactly the way it is spelled out in the annotation? Also, is it possible to stop hibernate from breaking camelcased columns into two works. For example if i had a column named columnOne hibernate will want to generate a column with the name column_one.

I know this more than likely has something to do with hibernate's naming strategy but i haven't been able to find a solution.

答:
Try adding the following in your application.properties file.

```<code> spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

Documentation about naming strategies are here

Title: Query generated by Hibernate

Body:
Try adding the following in your application.properties file.

 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Documentation about naming strategies are here


问:
fprintf and ctime without passing \n from ctime
I have an issue with inserting time in a text file. I use the following code and i get |21,43,1,3,10,5| Wed Feb 01 20:42:32 2012 which is normal but what i WANT TO DO is place the time before the numbers for example like Wed Feb 01 20:42:32 2012  |21,43,1,3,10,5| However, i cant do so cause when i use the fprintf with ctime function before fprintf the numbers it recognizes the \n within ctime and so it changes line 1st and then printing the numbers. It goes like:

```<code>    Wed Feb 01 20:42:32 2012
    |21,43,1,3,10,5|
</code>```

which is something that i dont want... How can i fprintf the time without swiching to the next line in the text??? Thanks in advance!

```<code>fprintf(file,"   |");
    for (i=0;i<6;i++)
    {
        buffer[i]=(lucky_number=rand()%49+1);       //range 1-49
        for (j=0;j<i;j++)
        {
            if (buffer[j]==lucky_number)
                i--;
        }
        itoa (buffer[i],draw_No,10);
        fprintf(file,"%s",draw_No);
        if (i!=5)
            fprintf(file,",");
    }
    fprintf(file,"|     %s",ctime(&t));
</code>```

答:
in c++11 you can do it like this:

```<code>#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace chrono;

// Prints UTC timestamp
void printTime() {
    time_point<system_clock> now = system_clock::now();
    time_t now_time = system_clock::to_time_t(now);

    auto gmt_time = gmtime(&now_time);
    auto timestamp = std::put_time(gmt_time, "%Y-%m-%d %H:%M:%S");
    cout << timestamp << endl;
}
</code>```

Output:

2017-06-05 00:31:49

Body:
I have an issue with inserting time in a text file. I use the following code and i get |21,43,1,3,10,5| Wed Feb 01 20:42:32 2012 which is normal but what i WANT TO DO is place the time before the numbers for example like Wed Feb 01 20:42:32 2012  |21,43,1,3,10,5| However, i cant do so cause when i use the fprintf with ctime function before fprintf the numbers it recognizes the \n within ctime and so it changes line 1st and then printing the numbers. It goes like:

    Wed Feb 01 20:42:32 2012
    |21,43,1,3,10,5|

which is something that i dont want... How can i fprintf the time without swiching to the next line in the text??? Thanks in advance!

fprintf(file,"   |");
    for (i=0;i<6;i++)
    {
        buffer[i]=(lucky_number=rand()%49+1);       //range 1-49
        for (j=0;j<i;j++)
        {
            if (buffer[j]==lucky_number)
                i--;
        }
        itoa (buffer[i],draw_No,10);
        fprintf(file,"%s",draw_No);
        if (i!=5)
            fprintf(file,",");
    }
    fprintf(file,"|     %s",ctime(&t));

Body:
in c++11 you can do it like this:

#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace chrono;

// Prints UTC timestamp
void printTime() {
    time_point<system_clock> now = system_clock::now();
    time_t now_time = system_clock::to_time_t(now);

    auto gmt_time = gmtime(&now_time);
    auto timestamp = std::put_time(gmt_time, "%Y-%m-%d %H:%M:%S");
    cout << timestamp << endl;
}

Output:

2017-06-05 00:31:49

ContentLicense: CC BY-SA 4.0


问:
echo outputs -e parameter in bash scripts. How can I prevent this?
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

```<code>$ echo -e 'foo\nbar'
</code>```

into an interactive bash shell, I get the expected output:

```<code>foo
bar
</code>```

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

```<code>-e foo
 bar
</code>```

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?

答:
You need to use #!/bin/bash as the first line in your script. If you don't, or if you use #!/bin/sh, the script will be run by the Bourne shell and its echo doesn't recognize the -e option. In general, it is recommended that all new scripts use printf instead of echo if portability is important.

In Ubuntu, sh is provided by a symlink to /bin/dash.

ContentLicense: CC BY-SA 2.5

Body:
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

$ echo -e 'foo\nbar'

into an interactive bash shell, I get the expected output:

foo
bar

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

-e foo
 bar

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?


问:
Android Facebook sdk 4.0 : Null exception while getting facebook user information?
As the title implied, I got a null pointer exception while getting facebook user information (e.g name, user id, etc).

I notice that it happens due to these scenarios:

No Facebook app installed

User logs in from the facebook Intent (since there is no FB app).

First time authenticating the app will cause a null pointer.

This is my code snippet for onSucces on login:

```<code>@Override
public void onSuccess(LoginResult loginResult) {

    ProfileTracker profileTracker;

    Profile profile = Profile.getCurrentProfile();
    final SocialProfileModel userprofile = new SocialProfileModel();

    if(profile == null){
        Log.d("user profile", "null");
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                userprofile.setProfileID(currentProfile.getId());
                userprofile.setFirst_name(currentProfile.getFirstName());
                userprofile.setLast_name(currentProfile.getLastName());
                userprofile.setMiddle_name(currentProfile.getMiddleName());
                userprofile.setProfile_pic(currentProfile.getProfilePictureUri(200,200).toString());
            }
        };
    }else {

        userprofile.setProfileID(profile.getId());
        userprofile.setUserName(profile.getName());
        userprofile.setFirst_name(profile.getFirstName());
        userprofile.setLast_name(profile.getLastName());
        userprofile.setMiddle_name(profile.getMiddleName());
        userprofile.setProfile_pic(profile.getProfilePictureUri(200,200).toString());
    }

    tv1.setText(profile.getId());
    tv2.setText(profile.getName());

}
</code>```

I'm aware of things like profile and token tracker, but I could not make sense of how I could make use those in this regards!

Any help is much appreciated!
Thanks!

Edit:

included is the stacktrace for the event:

04-26 16:20:10.671 2580-2580/packagename/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: packagename, PID: 2580
                                                                                java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {packagename.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                                                                                at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                                at com.agmostudio.socialsdk.socialsdk.MainActivity$1$1.onSuccess(MainActivity.java:98)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onSuccess(FacebookLogin.java:97)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onSuccess(FacebookLogin.java:26)
                                                                                at com.facebook.login.LoginManager.finishLogin(LoginManager.java:577)
                                                                                at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:216)
                                                                                at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:159)
                                                                                at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onActivityResult(FacebookLogin.java:65)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.SocialLoginManager.getOnActivityResult(SocialLoginManager.java:103)
                                                                                at com.agmostudio.socialsdk.socialsdk.MainActivity.onActivityResult(MainActivity.java:556)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                                                                                at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

答:
Try adding this two lines to your onCurrentProfileChanged method

```<code>this.stopTracking();
Profile.setCurrentProfile(currentProfile);
</code>```

And this in the next line after profileTracker = new ProfileTracker()

```<code>profileTracker.startTracking();
</code>```

Like this:

```<code>@Override
public void onSuccess(LoginResult loginResult) {

    ProfileTracker profileTracker;

    Profile profile = Profile.getCurrentProfile();
    final SocialProfileModel userprofile = new SocialProfileModel();

    if(profile == null){
        Log.d("user profile", "null");
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

                this.stopTracking();
                Profile.setCurrentProfile(currentProfile);

                userprofile.setProfileID(currentProfile.getId());
                userprofile.setFirst_name(currentProfile.getFirstName());
                userprofile.setLast_name(currentProfile.getLastName());
                userprofile.setMiddle_name(currentProfile.getMiddleName());
                userprofile.setProfile_pic(currentProfile.getProfilePictureUri(200,200).toString());
            }
        };
        profileTracker.startTracking();
    }else {

        userprofile.setProfileID(profile.getId());
        userprofile.setUserName(profile.getName());
        userprofile.setFirst_name(profile.getFirstName());
        userprofile.setLast_name(profile.getLastName());
        userprofile.setMiddle_name(profile.getMiddleName());
        userprofile.setProfile_pic(profile.getProfilePictureUri(200,200).toString());
    }

    tv1.setText(profile.getId());
    tv2.setText(profile.getName());

}
</code>```

Body:
As the title implied, I got a null pointer exception while getting facebook user information (e.g name, user id, etc).

I notice that it happens due to these scenarios:

No Facebook app installed

User logs in from the facebook Intent (since there is no FB app).

First time authenticating the app will cause a null pointer.

This is my code snippet for onSucces on login:

@Override
public void onSuccess(LoginResult loginResult) {

    ProfileTracker profileTracker;

    Profile profile = Profile.getCurrentProfile();
    final SocialProfileModel userprofile = new SocialProfileModel();

    if(profile == null){
        Log.d("user profile", "null");
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                userprofile.setProfileID(currentProfile.getId());
                userprofile.setFirst_name(currentProfile.getFirstName());
                userprofile.setLast_name(currentProfile.getLastName());
                userprofile.setMiddle_name(currentProfile.getMiddleName());
                userprofile.setProfile_pic(currentProfile.getProfilePictureUri(200,200).toString());
            }
        };
    }else {

        userprofile.setProfileID(profile.getId());
        userprofile.setUserName(profile.getName());
        userprofile.setFirst_name(profile.getFirstName());
        userprofile.setLast_name(profile.getLastName());
        userprofile.setMiddle_name(profile.getMiddleName());
        userprofile.setProfile_pic(profile.getProfilePictureUri(200,200).toString());
    }

    tv1.setText(profile.getId());
    tv2.setText(profile.getName());

}

I'm aware of things like profile and token tracker, but I could not make sense of how I could make use those in this regards!

Any help is much appreciated!
Thanks!

Edit:

included is the stacktrace for the event:

04-26 16:20:10.671 2580-2580/packagename/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: packagename, PID: 2580
                                                                                java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {packagename.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                                                                                at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                                at com.agmostudio.socialsdk.socialsdk.MainActivity$1$1.onSuccess(MainActivity.java:98)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onSuccess(FacebookLogin.java:97)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onSuccess(FacebookLogin.java:26)
                                                                                at com.facebook.login.LoginManager.finishLogin(LoginManager.java:577)
                                                                                at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:216)
                                                                                at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:159)
                                                                                at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.facebook.FacebookLogin.onActivityResult(FacebookLogin.java:65)
                                                                                at com.agmostudio.socialsdk.socialsdk_lib.login.SocialLoginManager.getOnActivityResult(SocialLoginManager.java:103)
                                                                                at com.agmostudio.socialsdk.socialsdk.MainActivity.onActivityResult(MainActivity.java:556)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                                                                                at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
Try adding this two lines to your onCurrentProfileChanged method

this.stopTracking();
Profile.setCurrentProfile(currentProfile);

And this in the next line after profileTracker = new ProfileTracker()

profileTracker.startTracking();

Like this:

@Override
public void onSuccess(LoginResult loginResult) {

    ProfileTracker profileTracker;

    Profile profile = Profile.getCurrentProfile();
    final SocialProfileModel userprofile = new SocialProfileModel();

    if(profile == null){
        Log.d("user profile", "null");
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

                this.stopTracking();
                Profile.setCurrentProfile(currentProfile);

                userprofile.setProfileID(currentProfile.getId());
                userprofile.setFirst_name(currentProfile.getFirstName());
                userprofile.setLast_name(currentProfile.getLastName());
                userprofile.setMiddle_name(currentProfile.getMiddleName());
                userprofile.setProfile_pic(currentProfile.getProfilePictureUri(200,200).toString());
            }
        };
        profileTracker.startTracking();
    }else {

        userprofile.setProfileID(profile.getId());
        userprofile.setUserName(profile.getName());
        userprofile.setFirst_name(profile.getFirstName());
        userprofile.setLast_name(profile.getLastName());
        userprofile.setMiddle_name(profile.getMiddleName());
        userprofile.setProfile_pic(profile.getProfilePictureUri(200,200).toString());
    }

    tv1.setText(profile.getId());
    tv2.setText(profile.getName());

}


问:
How to show data from selected option in a dropdown to a textbox using cfquery where the id = selected option in the dropdown?
Check the Image here for reference

What I want is that when I click/change dropdown for itemcode it will show the corresponding data for that particular ID on the textbox beside it. 1 for Item Description and the other is for the Item Price
My CFQUERY is :

```<code><cfquery name="getItemDesc" datasource="laundry" >
   SELECT * FROM items
   WHERE itemcode = <cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.getItemCode#">

</cfquery>
</code>```

My HTML code is :

```<code>    <table class="table" name="addedItem" class="addedItem" disabled>
    <tr>
        <td>
            <select class="form-control" name="getItemCode" id="getItemCode"  required disabled>
                <cfoutput query="getItem">
                <option value="#itemcode#">#itemcode#</option>
                </cfoutput>
            </select>
        </td>
        <td>
            <input type="text" class="form-control" placeholder=" Item Name" name="itemDesc" id="itemDesc" disabled/>
        </td>

        <td>
            <input type="text" class="form-control" placeholder=" Price" name="itemPrice" id="itemPrice" disabled/>
        </td>

        <td>
            <input type="text" class="form-control" name="itemQty" id="itemQty" placeholder=" Input Qty" disabled/>
        </td>

        <td>
            <button name="addItem" id="addItem" disabled><i class="fa fa-plus-circle " aria-hidden="true"></i> ADD</button>
        </td>
    </tr>
</code>```

Your help is highly appreciated. I'm sorry, I'm just new here so if there's anything that is not properly explained, let me know :D

答:
Thanks for those who answered my question. I will post my solution here for future reference.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td>
<select class="form-control" name="getItemCode" id="getItemCode"
onchange="aa()" required disabled>
<option value=""> -- </option>
<cfoutput query="getItem">
<option value="#itemcode#" data-itemdesc="#itemdesc#" data-
itemprice="#selling_price#">#itemcode#</option>
</cfoutput>
<input type="hidden" name="tempItemCode" id="tempItemCode">
</select>
</td></code>```

for ColdFusion Query:

```<code><!--- DEFAULT QUERY for GETTING ITEMCODE--->
<cfquery name="getItem" datasource="laundry" >
    SELECT * FROM items;
</cfquery>
</code>```

Body:
Check the Image here for reference

What I want is that when I click/change dropdown for itemcode it will show the corresponding data for that particular ID on the textbox beside it. 1 for Item Description and the other is for the Item Price
My CFQUERY is :

<cfquery name="getItemDesc" datasource="laundry" >
   SELECT * FROM items
   WHERE itemcode = <cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.getItemCode#">

</cfquery>

My HTML code is :

            <select class="form-control" name="getItemCode" id="getItemCode"  required disabled>
                <cfoutput query="getItem">
                <option value="#itemcode#">#itemcode#</option>
                </cfoutput>
            </select>

            <input type="text" class="form-control" placeholder=" Item Name" name="itemDesc" id="itemDesc" disabled/>

            <input type="text" class="form-control" placeholder=" Price" name="itemPrice" id="itemPrice" disabled/>

            <input type="text" class="form-control" name="itemQty" id="itemQty" placeholder=" Input Qty" disabled/>

            <button name="addItem" id="addItem" disabled> ADD</button>

Your help is highly appreciated. I'm sorry, I'm just new here so if there's anything that is not properly explained, let me know :D

Body:
Thanks for those who answered my question. I will post my solution here for future reference.

<script>
    /* WHEN ITEMCODE onChange :JMGR*/
    function aa(){
        var itemdesc = $('#getItemCode').find(":selected").data('itemdesc');
        var itemprice =
        $('#getItemCode').find(":selected").data('itemprice');
        document.getElementById('itemDesc').value=itemdesc;
        document.getElementById('itemPrice').value=itemprice;

        document.getElementById('tempItemDesc').value=itemdesc;
        document.getElementById('tempItemPrice').value=itemprice;

    }

</script>

<td>
<select class="form-control" name="getItemCode" id="getItemCode"
onchange="aa()" required disabled>
<option value=""> -- </option>
<cfoutput query="getItem">
<option value="#itemcode#" data-itemdesc="#itemdesc#" data-
itemprice="#selling_price#">#itemcode#</option>
</cfoutput>
<input type="hidden" name="tempItemCode" id="tempItemCode">
</select>
</td>

for ColdFusion Query:

<!--- DEFAULT QUERY for GETTING ITEMCODE--->
<cfquery name="getItem" datasource="laundry" >
    SELECT * FROM items;
</cfquery>


问:
Trying to connect JS and HTML. Receiving ERR_FILE NOT_FOUND
I'm a relative beginner so apologies if this is a dumb question. I have no idea if I'm using the wrong path while trying to link my JS to HTML. I've tried absolute paths, adding the files to a JS folder in the root folder. I can't even get jQuery to link. Here's a snippet:</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Guessing Game</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-theme.css">
    <!-- Bootstrap and CSS here-->

  </head>
  <body>

      <div id='app' class='center' class='container'>

        <div id='headers'>
          <!-- Title and subtitles! -->
          <h1 id='title'> Rav's Cheesy Guessing Game! </h1>
          <h2 id='subtitle'> Guess A Number Between 1-100, You Won't </h2>
        </div>

        <div id='main'>
          <div id='input-parent'>
            <!-- Player's guess input, and submit button -->
            <input id='player-input' class='center' placeholder="#" autofocus maxlength=2></input>
            <button id='submit-button' type=submit>Go!</button>
          </div>

          <div id='guesses'>
            <ul id='guess-list'>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
            </ul>
            <!-- unordered list of guesses -->
          </div>

          <div id="menu-btns">
            <!-- reset and hint buttons -->
            <button id='reset' class='btn btn-warning btn-sm'>Reset</button>
            <button id='hint' class='btn btn-primary btn-sm'>Hint</button>
          </div>
        </div>
      </div>

    <div id='footer' class='center' class="container">
        <div class="row">
          <div class='col-md-4 col-sm-4'>
            <img src='fa-logo@2x.png'>
          </div>

          <div class='col-md-4 col-sm-4'>
            <h4>Project by Ravish Rawal</h4>
          </div>

          <div class='col-md-4 col-sm-4'>
            <img src='grace_hopper_academy.png'>
          </div>

        </div>
    </div>
    <script type='text/javascript' src='js/jquery.min.js'></script>
    <script type='text/javascript' src='js/GuessingGame.js'></script>
  </body>
</html>
</code>```

答:
For root you need to
Type this "/"

this will returns to the root directory and starts there

Body:
I'm a relative beginner so apologies if this is a dumb question. I have no idea if I'm using the wrong path while trying to link my JS to HTML. I've tried absolute paths, adding the files to a JS folder in the root folder. I can't even get jQuery to link. Here's a snippet:

<!DOCTYPE html>

    <title>Guessing Game</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-theme.css">

 Rav's Cheesy Guessing Game!

 Guess A Number Between 1-100, You Won't

            <input id='player-input' class='center' placeholder="#" autofocus maxlength=2></input>
            <button id='submit-button' type=submit>Go!</button>

_

_

_

_

_

            <button id='reset' class='btn btn-warning btn-sm'>Reset</button>
            <button id='hint' class='btn btn-primary btn-sm'>Hint</button>

Project by Ravish Rawal


问:
How can I find the specific interval (via list) within which a given value occurs, in order to return the corresponding value from a second list?
I am writing a python code to act as a gradebook. I have calculated the total number of points earned by each student and am now stuck on the last step of my code - assigning a letter grade to a student. The structure of my code is to define functions that evaluate a single student's performance, so that one "master function" can repeatedly call the functions by an index number corresponding to each student. As such, I was able to produce a working code that I am trying to condense and simplify. I've checked out similar questions in posts like these, but I haven't been able to adapt these approaches to my problem (I think because my for-loop screws up the indexing).

Working code:

```<code>import numpy as np

failing_score = 100
perfect_score = 200
letter_grades = ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
grade_borders = np.linspace(perfect_score, failing_score, len(letter_grades))

print(grade_borders)
>> [ 200.          190.90909091  181.81818182  172.72727273  163.63636364
  154.54545455  145.45454545  136.36363636  127.27272727  118.18181818
  109.09090909  100.        ]

def get_letter_grade(student_grade, grade_borders=grade_borders):
    """
    perfect score = 200, failing score ≤ 100

    190.9 - 200:    A
    181.8 - 190.9:  A-
    172.7 - 181.8:  B+
    etc
    """
    if student_grade >= grade_borders[1]:
        letter = 'A'
    elif grade_borders[2] <= student_grade < grade_borders[1]:
        letter = 'A-'
    elif grade_borders[3] <= student_grade < grade_borders[2]:
        letter = 'B+'
    elif grade_borders[4] <= student_grade < grade_borders[3]:
        letter = 'B'
    elif grade_borders[5] <= student_grade < grade_borders[4]:
        letter = 'B-'
    elif grade_borders[6] <= student_grade < grade_borders[5]:
        letter = 'C+'
    elif grade_borders[7] <= student_grade < grade_borders[6]:
        letter = 'C'
    elif grade_borders[8] <= student_grade < grade_borders[7]:
        letter = 'C-'
    elif grade_borders[9] <= student_grade < grade_borders[8]:
        letter = 'D+'
    elif grade_borders[10] <= student_grade < grade_borders[9]:
        letter = 'D'
    elif grade_borders[11] <= student_grade < grade_borders[10]:
        letter = 'D-'
    elif student_grade < grade_borders[11]:
        letter = 'F'
    return letter

print(get_letter_grade(182))
>> A-
</code>```

I don't like having to specify each index and each letter grade using so many if/elif loops. So I tried to modify my approach by using a for-loop; the values at the boundaries (A and F) are handled separately while the grades in-between can be handled by the same code as functions of index.

Unsuccessful attempt:

```<code>def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    """
    This is my unsuccessful attempt at replicating the function above.
    """
    res = 0 # not including this line ==> UnboundLocalError: local variable 'res' referenced before assignment
    for idx in range(len(grade_borders)):
        if idx == 0:
            if student_score >= grade_borders[1]:
                res = letter_grades[idx]
                print("--", res)
        elif idx > 0 and idx < len(letter_grades)-1:
            if (student_score >= grade_borders[idx+1]) and (student_score < grade_borders[idx]) is True:
                res = letter_grades[idx]
                print("--", res)
        elif idx == len(letter_grades)-1:
            if student_score < grade_borders[len(grade_borders)-1]:
                res = letter_grades[idx]
                print("--", res)
    return res

print(assign_letter_grade(182))
</code>```

Question:
What is my mistake in the code just above? Is this a dumb approach (and why /why not?) I've thought about another alternate method that uses a histogram to find the non-zero interval corresponding to a student's grade, but I'm not sure about the efficiency and implementation.

答:
I was able to adapt the histogram approach, but with a deprecation warning.

```<code>def hlet(student_score, grade_borders=grade_borders):
    bins = grade_borders[::-1]
    interval, _, _ = plt.hist(student_score, bins=bins)
    interval = interval[::-1]
    letter_idx = np.where(interval>0)[0]
    return letter_grades[letter_idx]

print(hlet(182))

>> VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future
  return letter_grades[letter_idx]
A-
</code>```

While this approach works, I am still curious to see how other approaches attack this problem.

Body:
I am writing a python code to act as a gradebook. I have calculated the total number of points earned by each student and am now stuck on the last step of my code - assigning a letter grade to a student. The structure of my code is to define functions that evaluate a single student's performance, so that one "master function" can repeatedly call the functions by an index number corresponding to each student. As such, I was able to produce a working code that I am trying to condense and simplify. I've checked out similar questions in posts like these, but I haven't been able to adapt these approaches to my problem (I think because my for-loop screws up the indexing).

Working code:

import numpy as np

failing_score = 100
perfect_score = 200
letter_grades = ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
grade_borders = np.linspace(perfect_score, failing_score, len(letter_grades))

print(grade_borders)
>> [ 200.          190.90909091  181.81818182  172.72727273  163.63636364
  154.54545455  145.45454545  136.36363636  127.27272727  118.18181818
  109.09090909  100.        ]

def get_letter_grade(student_grade, grade_borders=grade_borders):
    """
    perfect score = 200, failing score ≤ 100

    190.9 - 200:    A
    181.8 - 190.9:  A-
    172.7 - 181.8:  B+
    etc
    """
    if student_grade >= grade_borders[1]:
        letter = 'A'
    elif grade_borders[2] <= student_grade < grade_borders[1]:
        letter = 'A-'
    elif grade_borders[3] <= student_grade < grade_borders[2]:
        letter = 'B+'
    elif grade_borders[4] <= student_grade < grade_borders[3]:
        letter = 'B'
    elif grade_borders[5] <= student_grade < grade_borders[4]:
        letter = 'B-'
    elif grade_borders[6] <= student_grade < grade_borders[5]:
        letter = 'C+'
    elif grade_borders[7] <= student_grade < grade_borders[6]:
        letter = 'C'
    elif grade_borders[8] <= student_grade < grade_borders[7]:
        letter = 'C-'
    elif grade_borders[9] <= student_grade < grade_borders[8]:
        letter = 'D+'
    elif grade_borders[10] <= student_grade < grade_borders[9]:
        letter = 'D'
    elif grade_borders[11] <= student_grade < grade_borders[10]:
        letter = 'D-'
    elif student_grade < grade_borders[11]:
        letter = 'F'
    return letter

print(get_letter_grade(182))
>> A-

I don't like having to specify each index and each letter grade using so many if/elif loops. So I tried to modify my approach by using a for-loop; the values at the boundaries (A and F) are handled separately while the grades in-between can be handled by the same code as functions of index.

Unsuccessful attempt:

def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    """
    This is my unsuccessful attempt at replicating the function above.
    """
    res = 0 # not including this line ==> UnboundLocalError: local variable 'res' referenced before assignment
    for idx in range(len(grade_borders)):
        if idx == 0:
            if student_score >= grade_borders[1]:
                res = letter_grades[idx]
                print("--", res)
        elif idx > 0 and idx < len(letter_grades)-1:
            if (student_score >= grade_borders[idx+1]) and (student_score < grade_borders[idx]) is True:
                res = letter_grades[idx]
                print("--", res)
        elif idx == len(letter_grades)-1:
            if student_score < grade_borders[len(grade_borders)-1]:
                res = letter_grades[idx]
                print("--", res)
    return res

print(assign_letter_grade(182))

Question:
What is my mistake in the code just above? Is this a dumb approach (and why /why not?) I've thought about another alternate method that uses a histogram to find the non-zero interval corresponding to a student's grade, but I'm not sure about the efficiency and implementation.

Body:
I was able to adapt the histogram approach, but with a deprecation warning.

def hlet(student_score, grade_borders=grade_borders):
    bins = grade_borders[::-1]
    interval, _, _ = plt.hist(student_score, bins=bins)
    interval = interval[::-1]
    letter_idx = np.where(interval>0)[0]
    return letter_grades[letter_idx]

print(hlet(182))

>> VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future
  return letter_grades[letter_idx]
A-

While this approach works, I am still curious to see how other approaches attack this problem.


问:
Read bunch of tags in SAX in QT
I'm using a QXMLSimpleReader to parse through an XML file via SAX.

I know this goes against the principle of SAX, but is there a neat way to grab the content of a parent tag without having to reassemble it manually ?

For example, given the following XML example (not real):

```<code><record>
  <person level="manager">
    <personal>
      <male/>
      <birthday>2010-12-13T20:00</birthday>
      <promotions>2</promotions>
      <salary high="200000"/>
    </personal>
  </person>
</record>
</code>```

I would like to grab a string containing all of the personal tag, i.e.

```<code><male/>
<birthday>2010-12-13T20:00</birthday>
<promotions>2</promotions>
<salary high="200000"/>
</code>```

The thing is, SAX automatically splits everything up into atomic tags so the personal tag parses as empty.

Solutions ideally for QT 2.3 please!

答:
You may want to try QXmlStreamReader. It's not SAX, but it's fast and easy to use. As docs say:

```<code>QXmlStreamReader is a faster and more convenient replacement for Qt's own
SAX parser (see QXmlSimpleReader).
</code>```

Also, Qt 2.3?!

Title: Read bunch of tags in SAX in QT

Body:
I'm using a QXMLSimpleReader to parse through an XML file via SAX.

I know this goes against the principle of SAX, but is there a neat way to grab the content of a parent tag without having to reassemble it manually ?

For example, given the following XML example (not real):

<record>
  <person level="manager">
    <personal>
      <male/>
      <birthday>2010-12-13T20:00</birthday>
      <promotions>2</promotions>
      <salary high="200000"/>
    </personal>
  </person>
</record>

I would like to grab a string containing all of the personal tag, i.e.

<male/>
<birthday>2010-12-13T20:00</birthday>
<promotions>2</promotions>
<salary high="200000"/>

The thing is, SAX automatically splits everything up into atomic tags so the personal tag parses as empty.

Solutions ideally for QT 2.3 please!

Body:
You may want to try QXmlStreamReader. It's not SAX, but it's fast and easy to use. As docs say:

QXmlStreamReader is a faster and more convenient replacement for Qt's own
SAX parser (see QXmlSimpleReader).

Also, Qt 2.3?!


问:
Does Visual Studio Community 2017 require sign in with microsoft account?
The question pretty much is self explanatory. I just want to know if I can use Visual Studio without signing into my Microsoft account.</p>

答: The community edition is free for 30 days. After that you'll have to sign in/create an account.</p>


问:
regex to extract show name, which include the year
I'm working on a .net program that will use regex to capture the title of a show from a filename, but having trouble when the show name should include a year. Here is what I have so far.

```<code>(?i)(.*?(?:19\d{2}|20\d{2})(?=[ -]+([\d]|[S][\d]|Season)))
</code>```

The trouble is that this will match The Flash 2014 but not Top Chef. And if I make the (?:19\d{2}|20\d{2}) optional by adding a question mark at the end it will then match Top Chef but not The Flash 2014, it will be missing the year.

Example files:

```<code>Top Chef S14E14 Comida Final.mkv
The Flash 2014 03x01 720p HDTV X264-DIMENSION.mkv
</code>```

Is my issue related to the optional group being in front of the positive lookahead? How do I fix it so that the query matches both shows?

答:
With the 2 lines you provided, this regex works:

```<code>^([\w\s]+)(?=\s{2,}|\-\d|s\d{2}|season|\d{4})
</code>```

It matches every sequence of characters, spaces or underscores that are followed by one of the following:

at least 2 spaces

a dash and a number

"s" followed by 2 digits

"season"

4 digits

You should then trim the result to remove the trailing space, if present

Body:
I'm working on a .net program that will use regex to capture the title of a show from a filename, but having trouble when the show name should include a year. Here is what I have so far.

(?i)(.*?(?:19\d{2}|20\d{2})(?=[ -]+([\d]|[S][\d]|Season)))

The trouble is that this will match The Flash 2014 but not Top Chef. And if I make the (?:19\d{2}|20\d{2}) optional by adding a question mark at the end it will then match Top Chef but not The Flash 2014, it will be missing the year.

Example files:

Top Chef S14E14 Comida Final.mkv
The Flash 2014 03x01 720p HDTV X264-DIMENSION.mkv

Is my issue related to the optional group being in front of the positive lookahead? How do I fix it so that the query matches both shows?

Body:
With the 2 lines you provided, this regex works:

^([\w\s]+)(?=\s{2,}|\-\d|s\d{2}|season|\d{4})

It matches every sequence of characters, spaces or underscores that are followed by one of the following:

at least 2 spaces

a dash and a number

"s" followed by 2 digits

"season"

4 digits

You should then trim the result to remove the trailing space, if present


问:
Oracle partition using 2 columns
I have a table as like below

```<code>Id RC_CLASS  RC_DATE    RC_TYPE
14 FI-321619 22-Jan-16   S
14 FI-399481 29-Jan-16   D
14 FI-321619 20-Jan-17   S
</code>```

Here is what i tried

```<code>SELECT *
FROM (SELECT rc.*,
             RANK() OVER (PARTITION BY ID,RC_CLASS order by rc__date) AS LATEST_VERSION
      FROM table
     )
WHERE LATEST_VERSION = 1
ORDER BY rc_vendorid;
</code>```

Expected output

```<code>Id RC_CLASS  RC_DATE    RC_TYPE
14 FI-399481 29-Jan-16   D
14 FI-321619 20-Jan-17   S
</code>```

I wanna group by ID and Class and bring top one sort by the RC_DATE. What i am getting is always the top one based on date, partition is not working here. What is missing?

答:
I think you are very close.  Basically, you just need a descending sort to get the latest version:

```<code>SELECT rc.*
FROM (SELECT rc.*,
             RANK() OVER (PARTITION BY ID, RC_CLASS ORDER BY rc_date DESC) AS LATEST_VERSION
      FROM table rc
     ) rc
WHERE LATEST_VERSION = 1
ORDER BY rc_vendorid;
</code>```

I note that you use RANK() for this.  This can return duplicates, if you have two rows on the same date.  If that is not desirable, you can use ROW_NUMBER() which would arbitrarily choose one (if all the other keys are the same).

Title: Oracle partition using 2 columns

Body:
I have a table as like below

Id RC_CLASS  RC_DATE    RC_TYPE
14 FI-321619 22-Jan-16   S
14 FI-399481 29-Jan-16   D
14 FI-321619 20-Jan-17   S

Here is what i tried

SELECT *
FROM (SELECT rc.*,
             RANK() OVER (PARTITION BY ID,RC_CLASS order by rc__date) AS LATEST_VERSION
      FROM table
     )
WHERE LATEST_VERSION = 1
ORDER BY rc_vendorid;

Expected output

Id RC_CLASS  RC_DATE    RC_TYPE
14 FI-399481 29-Jan-16   D
14 FI-321619 20-Jan-17   S

I wanna group by ID and Class and bring top one sort by the RC_DATE. What i am getting is always the top one based on date, partition is not working here. What is missing?

Body:
I think you are very close.  Basically, you just need a descending sort to get the latest version:

SELECT rc.*
FROM (SELECT rc.*,
             RANK() OVER (PARTITION BY ID, RC_CLASS ORDER BY rc_date DESC) AS LATEST_VERSION
      FROM table rc
     ) rc
WHERE LATEST_VERSION = 1
ORDER BY rc_vendorid;

I note that you use RANK() for this.  This can return duplicates, if you have two rows on the same date.  If that is not desirable, you can use ROW_NUMBER() which would arbitrarily choose one (if all the other keys are the same).


问:
How are the "plot.gam" confidence intervals calculated?
If a model is fitted using mgcv and then the smooth terms are plotted,

```<code>m <- gam(y ~ s(x))
plot(m, shade = TRUE)
</code>```

then you get a plot of the curve with a confidence interval. These are, I presume, pointwise-confidence intervals. How are they computed?

I tried to write

```<code>object <- plot(m, shade = true)
object[[1]]$fit +- 2*object[[1]]$se
</code>```

in order to extract the lower and upper bounds using the standard errors and a multiplier of 2, but when I plot it, it looks a bit different than the confidence intervals plotted by plot.gam?

So, how are those calculated?

I do not use seWithMean = true or anything like that.

答:
It is 1 standard deviation.

```<code>oo <- plot.gam(m)
oo <- oo[[1]]
points(oo$x, oo$fit, pch = 20)
points(oo$x, oo$fit - oo$se, pch = 20)
</code>```

Reproducible example:

```<code>x <- seq(0, 2 * pi, length = 100)
y <- x * sin(x) + rnorm(100, 0, 0.5)
m <- gam(y ~ s(x))
</code>```

Body:
If a model is fitted using mgcv and then the smooth terms are plotted,

m <- gam(y ~ s(x))
plot(m, shade = TRUE)

then you get a plot of the curve with a confidence interval. These are, I presume, pointwise-confidence intervals. How are they computed?

I tried to write

object <- plot(m, shade = true)
object[[1]]$fit +- 2*object[[1]]$se

in order to extract the lower and upper bounds using the standard errors and a multiplier of 2, but when I plot it, it looks a bit different than the confidence intervals plotted by plot.gam?

So, how are those calculated?

I do not use seWithMean = true or anything like that.

Body:
It is 1 standard deviation.

oo <- plot.gam(m)
oo <- oo[[1]]
points(oo$x, oo$fit, pch = 20)
points(oo$x, oo$fit - oo$se, pch = 20)

Reproducible example:

x <- seq(0, 2 * pi, length = 100)
y <- x * sin(x) + rnorm(100, 0, 0.5)
m <- gam(y ~ s(x))


问:
Java almostIncreasingSequence
Okay so i just started out on CodeFight, I got this question:

After a couple of hours of trying to figure a way by myself to solve it i got it fully functional but apperently its not within the time limit, and I do not know how to fix it even more to solve it.

```<code>boolean almostIncreasingSequence(int[] sequence) {
    List<Integer> A = new ArrayList<Integer>();
    for (int i = 0; i < sequence.length; i++){
        A.add(sequence[i]);
    }
    for (int i = 0; i < A.size(); i++){
        ArrayList<Integer> AC = new ArrayList<Integer>(A);
        AC.remove(i);
        boolean ps = true;
        for (int x = 0; x < AC.size()-1; x++){
            if (AC.get(x) >= AC.get(x+1)){
                ps = false;
                break;
            }
        }
        if (ps){
            return true;
        }
    }
    return false;
}
</code>```

This what I'm getting

I know there are questions just like this out there but i haven't found a solution. I hope someone can help. I have been stuck for hours on this.

答:
You might need to consider another approach to the problem. This problem can be solved in linear time by evaluating each entry once. An entry can either be part of an increasing sequence, part of an almost increasing sequence or neither.

A sequence will be almost increasing if it contains less than two of these almost increasing entries, so we can simply check for that at the end.

```<code>public enum EntryState {
    INCREASING(0), ALMOST_INCREASING(1), DECREASING(2);

    private final int state;
    private EntryState(int state) {
        this.state = state;
    }
    public int getValue() { return state; }
}

public boolean almostIncreasingSequence(int[] sequence) {
    int l = sequence.length;
    EntryState[] sequenceState = new EntryState[l];
    for(int i = 0; i < l - 1; i++) {
        if(sequence[i] <= sequence[i + 1])
            sequenceState[i] = EntryState.INCREASING;
        else if((i + 2 >= l) || (i + 2 < l && sequence[i] <= sequence[i + 2]))
            sequenceState[i] = EntryState.ALMOST_INCREASING;
        else
            sequenceState[i] = EntryState.DECREASING;
    }
    sequenceState[l - 1] = EntryState.INCREASING;

    int sum = 0;
    for(EntryState e : sequenceState)
        sum += e.getValue();

    int sumWithoutStart = sum - sequenceState[0].getValue();
    int sumWithoutEnd = sum - sequenceState[l - 1].getValue();
    return sumWithoutStart == 0 || sumWithoutEnd == 0 || sum < 2;
}
</code>```

Title: Java almostIncreasingSequence

Body:
Okay so i just started out on CodeFight, I got this question:

After a couple of hours of trying to figure a way by myself to solve it i got it fully functional but apperently its not within the time limit, and I do not know how to fix it even more to solve it.

boolean almostIncreasingSequence(int[] sequence) {
    List<Integer> A = new ArrayList<Integer>();
    for (int i = 0; i < sequence.length; i++){
        A.add(sequence[i]);
    }
    for (int i = 0; i < A.size(); i++){
        ArrayList<Integer> AC = new ArrayList<Integer>(A);
        AC.remove(i);
        boolean ps = true;
        for (int x = 0; x < AC.size()-1; x++){
            if (AC.get(x) >= AC.get(x+1)){
                ps = false;
                break;
            }
        }
        if (ps){
            return true;
        }
    }
    return false;
}

This what I'm getting

I know there are questions just like this out there but i haven't found a solution. I hope someone can help. I have been stuck for hours on this.

Body:
You might need to consider another approach to the problem. This problem can be solved in linear time by evaluating each entry once. An entry can either be part of an increasing sequence, part of an almost increasing sequence or neither.

A sequence will be almost increasing if it contains less than two of these almost increasing entries, so we can simply check for that at the end.

public enum EntryState {
    INCREASING(0), ALMOST_INCREASING(1), DECREASING(2);

    private final int state;
    private EntryState(int state) {
        this.state = state;
    }
    public int getValue() { return state; }
}

public boolean almostIncreasingSequence(int[] sequence) {
    int l = sequence.length;
    EntryState[] sequenceState = new EntryState[l];
    for(int i = 0; i < l - 1; i++) {
        if(sequence[i] <= sequence[i + 1])
            sequenceState[i] = EntryState.INCREASING;
        else if((i + 2 >= l) || (i + 2 < l && sequence[i] <= sequence[i + 2]))
            sequenceState[i] = EntryState.ALMOST_INCREASING;
        else
            sequenceState[i] = EntryState.DECREASING;
    }
    sequenceState[l - 1] = EntryState.INCREASING;

    int sum = 0;
    for(EntryState e : sequenceState)
        sum += e.getValue();

    int sumWithoutStart = sum - sequenceState[0].getValue();
    int sumWithoutEnd = sum - sequenceState[l - 1].getValue();
    return sumWithoutStart == 0 || sumWithoutEnd == 0 || sum < 2;
}


问:
How to access a column in a list of lists in python
I have a 2D array in python modeled by a list of lists and I want to extract the column. I made a quick research and I found a way that uses numpy arrays. The problem is that I do not want to use numpy so I don't want to convert my list of lists into a numpy array and then use [:,1] syntax. I tried using it on a normal list of lists but it shows an error so it's not possible. I am asking for a similar thing for list of lists without having to go through each element (In numpy arrays, it's faster to access a column by using [:,1] syntax than iterating over the elements of the array).

I found this link but again it suggests iterating over elements without a shortcut.

Body:
List comprehensions are your friend when working with lists of lists:

In [111]: alist
Out[111]:
[[0, 1, 2, 3, 4, 5],
 [6, 7, 8, 9, 10, 11],
 [12, 13, 14, 15, 16, 17],
 [18, 19, 20, 21, 22, 23]]
In [112]: [row[1] for row in alist]
Out[112]: [1, 7, 13, 19]

There's also a handy 'idiom' for transposing a nested list, turning 'columns' into 'rows':

In [113]: tlist = list(zip(*alist))
In [114]: tlist
Out[114]:
[(0, 6, 12, 18),
 (1, 7, 13, 19),
 (2, 8, 14, 20),
 (3, 9, 15, 21),
 (4, 10, 16, 22),
 (5, 11, 17, 23)]
In [115]: tlist[1]
Out[115]: (1, 7, 13, 19)


问:
Best way to define error code and error message mapping in .NET
I want to create custom error code and message mapping file. Currently I use Dictionary<int, string> to store them but I think they may have better way to achieve this.

If there is common practice to do this please let me know.

答: You could define an enum for your error codes that map to a resource file, that way they can be esaly manage, localized, etc.</p>


问:
Gradle jacoco multi project. How to output the code coverage of all the project in the terminal?
I am using Gradle jacoco plugin and have JUnit tests in a gradle multi project.

I have installed jacoco in order to report to sonarqube my code coverage, which I did.

Gitlab-CI also offer a badge for the code coverage, I only need to output the code coverage in a terminal and use a regex to find it.

Is there a way to output the code coverage of all the project in the terminal ?

答:
AFAIK Gradle does not support this, each project is treated separately.

To support your use case some aggregation task can be created to parse a report and to update some value at root project and finally print that value to stdout.

Update with approximate code for solution:

```<code>subprojects {
    task aggregateCoverage {
        // parse report from each module into ext.currentCoverage
        rootProject.ext.coverage += currentCoverage
    }
}
</code>```

Body:
AFAIK Gradle does not support this, each project is treated separately.

To support your use case some aggregation task can be created to parse a report and to update some value at root project and finally print that value to stdout.

Update with approximate code for solution:

subprojects {
    task aggregateCoverage {
        // parse report from each module into ext.currentCoverage
        rootProject.ext.coverage += currentCoverage
    }
}


问:
HTML data-id value to Javascript Array name
I am trying to map a data-id attribute value to a Javascript Array name.

I would like to have product = productid01 where productid01 is the text value of data-id.

```<code><html>
 <table>
  <tr>
   <td>$200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button></td>
  </tr>
 </table>
</html>

<script>
 $( document ).ready(function() {

  var productid01 = {desc:"This is a product", price:200.00};

  $(document).on('click', '.function-buy', function(){
   id = $(this).data("id");      //id = productid01
   var product = id;             //var product = productid01 (would like !)
   document.write(product.desc); //Expected output : This is a product
  });
 });
</script>
</code>```

I have discovered that eval() seems to work :

```<code>var product = eval(id);
</code>```

but is there a better way to achieve this without using eval() ?

For sure i have a kind of datatype mismatch here, but i cannot figure out how to work around this.

Thanks for your help.

答:
You can define productidN as properties of an object, use bracket notation.

    $200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button>

```

Body:
I am trying to map a data-id attribute value to a Javascript Array name.

I would like to have product = productid01 where productid01 is the text value of data-id.

   $200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button>

I have discovered that eval() seems to work :

var product = eval(id);

but is there a better way to achieve this without using eval() ?

For sure i have a kind of datatype mismatch here, but i cannot figure out how to work around this.

Thanks for your help.

Body:
You can define productidN as properties of an object, use bracket notation.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<table>
  <tr>
    <td>$200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button></td>
  </tr>
</table>

<script>
  $(document).ready(function() {

    var options = {
      productid01: {
        desc: "This is a product",
        price: 200.00
      }
    };

    $(document).on('click', '.function-buy', function() {
      var id = $(this).data("id"); //id = productid01
      var product = id; //var product = productid01 (would like !)
      product = options[product];
      $("body").append(product.desc); //Expected output : This is a product
    });
  });
</script>

</html>


问:
Doing a simple substraction and elminiation of values right after
I've been tyring to get a table to do a simple "taxing" system for a little game I work with sometimes. It's supposed to basically substract a money value from one row, and save it as a different value in that same row.

The table is basically

```<code>Name - Money - Tax - ETC - ETC - ETC
</code>```

Those are the only 3 values I really want to touch with the query, but I have no idea how to make it happen.
It's supposed to Create a value in tax that is Tax = Money * 0.10

Then it's supposed to call forth a different action, where It deducts that Tax from the Money itself, and not change anything else.
The goal there is to later make it add to a different Name field the tax from all of the affected rows. Yes, I have been looking through the site, but can't seem to find an answer. Soo, someone please save me?

答:
Have you tried an update?

```<code>update t
    set tax = money * 0.1,
        money = money * 0.9
    where name = ?;
</code>```

Body:
I've been tyring to get a table to do a simple "taxing" system for a little game I work with sometimes. It's supposed to basically substract a money value from one row, and save it as a different value in that same row.

The table is basically

Name - Money - Tax - ETC - ETC - ETC

Those are the only 3 values I really want to touch with the query, but I have no idea how to make it happen.
It's supposed to Create a value in tax that is Tax = Money * 0.10

Then it's supposed to call forth a different action, where It deducts that Tax from the Money itself, and not change anything else.
The goal there is to later make it add to a different Name field the tax from all of the affected rows. Yes, I have been looking through the site, but can't seem to find an answer. Soo, someone please save me?

Body:
Have you tried an update?

update t
    set tax = money * 0.1,
        money = money * 0.9
    where name = ?;


问:
How to stop losing proper location/url when smooth scrolling to hash
Ok, I have a few issues... I'm building my site with bootstrap/jquery. I'm using bootstrap nav and all nav links are hash links to different containers on the same page.

Issue #1
When using the method below to 'hijack' the link I lose the URL address thus look the ability for people to grab the link and share or link to it later.

Issue #2
There are a few other pages with content that aren't on the homepage. So obviously when users click on the link /somepage/#photography doesn't work. Is the only solution here to not use relative links?

```<code><nav>
  <a href="#photography">Photography</a>
</nav>

// smooth scroll from navigation
$('nav a').click(function(evt){
  evt.preventDefault();
  var $section = $($(this).attr('href'));
  scrollToObject($section);
});
</code>```

答:
Issue 1: the reason for losing the hash at the end of the URL is because the call to evt.preventDefault() is preventing the hash from being added.

I am not 100% sure on the inner-workings of the scroll effect in scrollToObject(), but if you can provide a callback function when the scrolling is complete you could then add location.assign( evt.target.hash ); which will add the hash to the URL (and it will show up in the user's history.) Of course, you can get the hash value from the anchor object, event, etc.

You can read about the location interface in js on MDN here: https://developer.mozilla.org/en-US/docs/Web/API/Location

Issue 2: You could actually accomplish this once again using location.assign(). Once again, without seeing all of your code, you can create a conditional in a callback and then send the user back to the page with the scrolling anchors: location.assign( location.origin + '/' + evt.target.hash ).

Body:
Ok, I have a few issues... I'm building my site with bootstrap/jquery. I'm using bootstrap nav and all nav links are hash links to different containers on the same page.

Issue #1
When using the method below to 'hijack' the link I lose the URL address thus look the ability for people to grab the link and share or link to it later.

Issue #2
There are a few other pages with content that aren't on the homepage. So obviously when users click on the link /somepage/#photography doesn't work. Is the only solution here to not use relative links?

  Photography

// smooth scroll from navigation
$('nav a').click(function(evt){
  evt.preventDefault();
  var $section = $($(this).attr('href'));
  scrollToObject($section);
});


问:
Run function from the command line
I have this code:

```<code>def hello():
    return 'Hi :)'
</code>```

How would I run this directly from the command line?

答:
Let's make this a little easier on ourselves and just use a module...

Try: pip install compago

Then write:

```<code>import compago
app = compago.Application()

@app.command
def hello():
    print "hi there!"

@app.command
def goodbye():
    print "see ya later."

if __name__ == "__main__":
    app.run()
</code>```

Then use like so:

```<code>$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.
</code>```

Note: There's a bug in Python 3 at the moment, but works great with Python 2.

Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire. From their GitHub:

Here's a simple example.

```<code>import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)
</code>```

Then, from the command line, you can run:

```<code>python calculator.py double 10  # 20
python calculator.py double --number=15  # 30
</code>```

Title: Run function from the command line

Body:
I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?

Body:
Let's make this a little easier on ourselves and just use a module...

Try: pip install compago

Then write:

import compago
app = compago.Application()

@app.command
def hello():
    print "hi there!"

@app.command
def goodbye():
    print "see ya later."

if __name__ == "__main__":
    app.run()

Then use like so:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

Note: There's a bug in Python 3 at the moment, but works great with Python 2.

Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire. From their GitHub:

Here's a simple example.

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

Then, from the command line, you can run:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答: Test, unit test, integration test, webtest, peer QA and end user review in the sprint review. Peer QA decides if anything else is necessary, all tests must pass in CI environment. This is in a scrum web-project. </p>

OwnerDisplayName: Micah

OwnerDisplayName: krosenvold

LastEditorDisplayName: krosenvold


问:
Decode Marshalled JSON unicode
I think the quickest way to explain my problem is with an example:

```<code>package main

import (
    "fmt"
    "encoding/json"
)

type JSON struct {
    Body string
}

func main() {
    body := "<html><body>Hello World</body></html>"

    obj := JSON{body}

    result, _ := json.Marshal(obj)
    fmt.Println(string(result))
}
</code>```

Output:

{"Body":"\u003chtml\u003e\u003cbody\u003eHello World\u003c/body\u003e\u003c/html\u003e"}

I'd like the result to be a utf8-encoded string that reads the same as it went in. How can I achieve this? I tried to use utf8.DecodeRune, in a loop:

```<code>str := ""

for _, res := range result {
    decoded, _ := utf8.DecodeRune(res)
    str += string(decoded)
}
</code>```

but that causes a compilation error

main.go:21: cannot use res (type byte) as type []byte in argument to utf8.DecodeRune

And calling DecodeRune on the marshalled object returns the first character, as you'd expect

{

Edit: I'm  using Go 1.6.2, which apparently doesn't have SetEscapeHTML for whatever reason.

答:
By the way, here's the reason for the compiler error.

json.Marshal returns a byte slice ([]byte), not a string.

When you iterate over a byte slice using range, you are not iterating over its runes but over single bytes at a time.  You can't use DecodeRune() on a byte value - it expects a rune, which is a 32-bit integer value representing a Unicode code point.  This is what you'd get if you iterate using range on a string.

Now, from what you are wanting to achieve, it doesn't look like you want DecodeRune at all.

The other answer adequately describes how to tell the JSON encode not to escape < and > characters ie

```<code>enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
</code>```

Title: Decode Marshalled JSON unicode

Body:
I think the quickest way to explain my problem is with an example:

package main

import (
    "fmt"
    "encoding/json"
)

type JSON struct {
    Body string
}

func main() {
    body := "Hello World"

    obj := JSON{body}

    result, _ := json.Marshal(obj)
    fmt.Println(string(result))
}

Output:

{"Body":"\u003chtml\u003e\u003cbody\u003eHello World\u003c/body\u003e\u003c/html\u003e"}

I'd like the result to be a utf8-encoded string that reads the same as it went in. How can I achieve this? I tried to use utf8.DecodeRune, in a loop:

str := ""

for _, res := range result {
    decoded, _ := utf8.DecodeRune(res)
    str += string(decoded)
}

but that causes a compilation error

main.go:21: cannot use res (type byte) as type []byte in argument to utf8.DecodeRune

And calling DecodeRune on the marshalled object returns the first character, as you'd expect

{

Edit: I'm  using Go 1.6.2, which apparently doesn't have SetEscapeHTML for whatever reason.

Body:
By the way, here's the reason for the compiler error.

json.Marshal returns a byte slice ([]byte), not a string.

When you iterate over a byte slice using range, you are not iterating over its runes but over single bytes at a time.  You can't use DecodeRune() on a byte value - it expects a rune, which is a 32-bit integer value representing a Unicode code point.  This is what you'd get if you iterate using range on a string.

Now, from what you are wanting to achieve, it doesn't look like you want DecodeRune at all.

The other answer adequately describes how to tell the JSON encode not to escape < and > characters ie

enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)


答:
You can make use of javascript objects, see example:

   $200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button>

```

Title: HTML data-id value to Javascript Array name

Body:
You can make use of javascript objects, see example:

<html>
 <table>
  <tr>
   <td>$200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button></td>
  </tr>
 </table>
</html>

<script>
 $( document ).ready(function() {

  var products = {
    productid01 : {desc:"This is a product", price:200.00}
  };

  $(document).on('click', '.function-buy', function(){
   id = $(this).data("id");      //id = productid01
   var product = products[ id ]; // get the product01
   document.write(product.desc); //Expected output : This is a product
  });
 });
</script>


问:
I can not post content to php through ajax with javascript
I have a problem when sending post content to a php file via ajax. My intention is to send an object that contains the data that will be used in the file save.php and it has to process the response so that it appears in an alert window.

```<code>var iden = true;

var object = {

    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

var xhr = new XMLHttpRequest();
xhr.open('POST', "save.php", false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send( object);

if (xhr.status == 200) {
    xhr.onload = function () {
        alert(this.responseText);
    };
} else {
    alert('error');
}
</code>```

The problem is that when trying to send the data I get this message in console:

Test.js: 56 [Deprecation] Synchronous XMLHttpRequest on the main
  thread is deprecated because of its detrimental effects to the end
  user's experience. For more help, check https://xhr.spec.whatwg.org/.

Line 56 corresponds to:

Xhr.open ('POST', 'save.php', false);

If I set the async parameter to true, it jumps the else from the conditional if (xhr.status == 200) and displays the error alert.

Where could the problem be?

Also say that with jquery it works perfectly, but I would like to do it with Javascript.

With jquery:

```<code>$.ajax({
    url: "save.php",
    type: "post",
    data: object
}).done(function(data) {
    alert(data);
});
</code>```

EDIT:

console.log(xhr);

XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false,
  upload: XMLHttpRequestUpload, onreadystatechange: function…} onabort :
  null onerror : null onload : null onloadend : null onloadstart : null
  onprogress : null onreadystatechange : function () ontimeout : null
  readyState : 4 response : "" responseText : "" responseType : ""
  responseURL : "http://localhost/save.php" responseXML : null status :
  200 statusText : "OK" timeout : 0

答:
Try changing this line of code: xhttp.open("POST", "save.php", false); and set the third parameter to true. And follow this example if it can work.

var object = {
    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("POST", "save.php", true);
  xhttp.send(object);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div></code>```

Body:
I have a problem when sending post content to a php file via ajax. My intention is to send an object that contains the data that will be used in the file save.php and it has to process the response so that it appears in an alert window.

var iden = true;

var object = {

    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

var xhr = new XMLHttpRequest();
xhr.open('POST', "save.php", false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send( object);

if (xhr.status == 200) {
    xhr.onload = function () {
        alert(this.responseText);
    };
} else {
    alert('error');
}

The problem is that when trying to send the data I get this message in console:

Test.js: 56 [Deprecation] Synchronous XMLHttpRequest on the main
  thread is deprecated because of its detrimental effects to the end
  user's experience. For more help, check https://xhr.spec.whatwg.org/.

Line 56 corresponds to:

Xhr.open ('POST', 'save.php', false);

If I set the async parameter to true, it jumps the else from the conditional if (xhr.status == 200) and displays the error alert.

Where could the problem be?

Also say that with jquery it works perfectly, but I would like to do it with Javascript.

With jquery:

$.ajax({
    url: "save.php",
    type: "post",
    data: object
}).done(function(data) {
    alert(data);
});

EDIT:

console.log(xhr);

XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false,
  upload: XMLHttpRequestUpload, onreadystatechange: function…} onabort :
  null onerror : null onload : null onloadend : null onloadstart : null
  onprogress : null onreadystatechange : function () ontimeout : null
  readyState : 4 response : "" responseText : "" responseType : ""
  responseURL : "http://localhost/save.php" responseXML : null status :
  200 statusText : "OK" timeout : 0

Body:
Try changing this line of code: xhttp.open("POST", "save.php", false); and set the third parameter to true. And follow this example if it can work.

var object = {
    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("POST", "save.php", true);
  xhttp.send(object);

<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>


问:
How to get all values from resultset?
I'm trying to get all the values from the table and then assign them to a variable, there are only 2 options in the table so it can have 1 or 2 values, but when trying this it only gives back when first number (1) and the second (<code>$fila2 = $rs2[1];</code>) it says that is a Undefined offset </p>

```<code>include('conexion.php');
$str_query2 = "SELECT gc_id FROM prod_grupocompl where pr_id='171' "; //  Variable que guarda la consulta a efectuar
$query2 = mysqli_query($conexion,$str_query2) or die (mysql_error()); // EjecuciÛn de la consulta y se guarda el resultado en $query
$rs2 = mysqli_fetch_array($query2);
$fila = $rs2[0];
$fila2 = $rs2[1];
echo $fila;
echo $fila2;
</code>```

答:
The resultset will be returning two rows not two fields in one row.

To access the second row, I recommend a loop.

```<code>while($row=mysqli_fetch_array($query2, MYSQLI_NUM)){
    // now you can access the field value like this for each row...
    $fila=$row[0];  // do what you want with each value, echo or something.
}
</code>```

p.s. mysql_error() is missing an i.

Title: How to get all values from resultset?

Body:
I'm trying to get all the values from the table and then assign them to a variable, there are only 2 options in the table so it can have 1 or 2 values, but when trying this it only gives back when first number (1) and the second ($fila2 = $rs2[1];) it says that is a Undefined offset

include('conexion.php');
$str_query2 = "SELECT gc_id FROM prod_grupocompl where pr_id='171' "; //  Variable que guarda la consulta a efectuar
$query2 = mysqli_query($conexion,$str_query2) or die (mysql_error()); // EjecuciÛn de la consulta y se guarda el resultado en $query
$rs2 = mysqli_fetch_array($query2);
$fila = $rs2[0];
$fila2 = $rs2[1];
echo $fila;
echo $fila2;

Body:
The resultset will be returning two rows not two fields in one row.

To access the second row, I recommend a loop.

while($row=mysqli_fetch_array($query2, MYSQLI_NUM)){
    // now you can access the field value like this for each row...
    $fila=$row[0];  // do what you want with each value, echo or something.
}

p.s. mysql_error() is missing an i.


问:
Conditionally chaining promises - how to avoid code duplication?
I have the following:

```<code>if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseMakerB(someLongListOfArguments);
     });
}
else
    return promiseMakerB(someLongListOfArguments);
</code>```

How can I eliminate that code repetition (promiseMakerB)?

答:
you can do the following, however, it's not necessarily the most readable way of doing so</p>

```<code>return (someCondition ? promiseMakerA(): Promise.resolve()).then(function() {
    return promiseMakerB(someLongListOfArguments);
});
</code>```

Body:
I have the following:

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseMakerB(someLongListOfArguments);
     });
}
else
    return promiseMakerB(someLongListOfArguments);

How can I eliminate that code repetition (promiseMakerB)?

Body:
you can do the following, however, it's not necessarily the most readable way of doing so

return (someCondition ? promiseMakerA(): Promise.resolve()).then(function() {
    return promiseMakerB(someLongListOfArguments);
});


问:
Does Visual Studio Community 2017 require sign in with microsoft account?
The question pretty much is self explanatory. I just want to know if I can use Visual Studio without signing into my Microsoft account.</p>

答:
In Microsoft VS Community For individuals :

Any individual developer can use Visual Studio Community to create their own free or paid apps.

VS Community Free just in 30 Days after that you'll have to Sign in.


问:
Chef - Search within test kitchen context
I'm managing some scripts that can only be run on one server. I've decided the best way to single out one host that is assigned to a given role is by doing a search and then choosing the first element in the array returned.

Like this:

```<code>q = "roles:thumper"
arr = search(:node, q, filter_result: { fqdn: ['fqdn'] }).map { |n| n['fqdn'] }

 # => ["1.example", "2.example"]

arr.first
# "1.example"
</code>```

This works well in reality and chef-shell, but has difficulties in Test Kitchen where I am being returned an HTTP 500 on the search command.

```<code>     ================================================================================
     Recipe Compile Error in /tmp/kitchen/cache/cookbooks/test/recipes/full.rb
     ================================================================================

     Net::HTTPFatalError
     -------------------
     500 "Internal Server Error"
</code>```

I am using chef_zero with the vagrant driver. Is there anything special that must be done to let search functionality work in this type of scenario?

Integration json:

```<code>{
  "id": "thumper",
  "environment": "food",
  "run_list": ["role["thumper]"],
  "automatic": {
    "fqdn": "thumper",
    "ipaddress": "10.10.10.10",
    "roles": ["thumper"],
    "environment": "food"
  }
}
</code>```

Fixtures data is just calling the relevant cookbooks

```<code>include_recipe 'test_helpers'
include_recipe 'role_thumper'
</code>```

答: The underlying issue is probably that you aren't setting up the fixture node data correctly, or maybe some piece of the partial search API not working correctly under Zero. However this is mostly moot as this method for server election is unsafe and you shouldn't use it. At a minimum you need to sort the returned array in some way as search results in Chef are not stable to any external reference point (it sorts on a field called "object ID" but this is not exposed in the API). More to the point, this can easily result in a server being demoted but not realizing it until the next time Chef runs. Depending on how serious you are about the "only run in one place" rule you either need some slightly firmer code on the Chef side, or better yet use a tool actually designed for cluster coordination like Consul, ZooKeeper, or Etcd.</p>

Body:
I'm managing some scripts that can only be run on one server. I've decided the best way to single out one host that is assigned to a given role is by doing a search and then choosing the first element in the array returned.

Like this:

q = "roles:thumper"
arr = search(:node, q, filter_result: { fqdn: ['fqdn'] }).map { |n| n['fqdn'] }

 # => ["1.example", "2.example"]

arr.first
# "1.example"

This works well in reality and chef-shell, but has difficulties in Test Kitchen where I am being returned an HTTP 500 on the search command.

     ================================================================================
     Recipe Compile Error in /tmp/kitchen/cache/cookbooks/test/recipes/full.rb
     ================================================================================

     Net::HTTPFatalError
     -------------------
     500 "Internal Server Error"

I am using chef_zero with the vagrant driver. Is there anything special that must be done to let search functionality work in this type of scenario?

Integration json:

{
  "id": "thumper",
  "environment": "food",
  "run_list": ["role["thumper]"],
  "automatic": {
    "fqdn": "thumper",
    "ipaddress": "10.10.10.10",
    "roles": ["thumper"],
    "environment": "food"
  }
}

Fixtures data is just calling the relevant cookbooks

include_recipe 'test_helpers'
include_recipe 'role_thumper'