问:
Odd SQL connection error received when under high load
I can connect to my MSSQL 2017 database via JDBC just fine, however when the database server is under heavy load, I get this connection error when running a query.

Have I simply maxed out what the server can do?
Maybe this is a NIC related issue?
Any performance settings adjustments to make?

```<code>com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host 192.168.1.150, port 1433 has failed.
Error: "Connection timed out: no further information.
Verify the connection properties. Make sure that an instance of
SQL Server is running on the host and accepting TCP/IP connections
at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
</code>```

答:
MS SQL Server have problems when are too many connections and worker threads from clients.

You can check current count of connections.

```<code>Select Count(*) FROM MASTER.DBO.SYSPROCESSES
</code>```

There are dependencies between CPU cores and worker threads.
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-max-worker-threads-server-configuration-option?view=sql-server-2017

Max worker threads on your host.

```<code>Select max_workers_count from sys.dm_os_sys_info
</code>```

Also you can see wait types THREADPOOL in TOP.

```<code>SELECT TOP 100
 [Wait type] = wait_type,
 [Wait time (s)] = wait_time_ms / 1000,
 [% waiting] = CONVERT(DECIMAL(12,2), wait_time_ms * 100.0
               / SUM(wait_time_ms) OVER())
FROM sys.dm_os_wait_stats
WHERE wait_type NOT LIKE '%SLEEP%'
ORDER BY wait_time_ms DESC;
</code>```

About waits threadpool:
https://www.sqlskills.com/help/waits/threadpool/

Check this version.

Or I don't understand situation and you have problem after X seconds after connection and work query.
Check query timeout in your application via the connection string something like "queryTimeout=..."

Body:
I can connect to my MSSQL 2017 database via JDBC just fine, however when the database server is under heavy load, I get this connection error when running a query.

Have I simply maxed out what the server can do?
Maybe this is a NIC related issue?
Any performance settings adjustments to make?

com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host 192.168.1.150, port 1433 has failed.
Error: "Connection timed out: no further information.
Verify the connection properties. Make sure that an instance of
SQL Server is running on the host and accepting TCP/IP connections
at the port. Make sure that TCP connections to the port are not blocked by a firewall.".

Body:
MS SQL Server have problems when are too many connections and worker threads from clients.

You can check current count of connections.

Select Count(*) FROM MASTER.DBO.SYSPROCESSES

There are dependencies between CPU cores and worker threads.
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-max-worker-threads-server-configuration-option?view=sql-server-2017

Max worker threads on your host.

Select max_workers_count from sys.dm_os_sys_info

Also you can see wait types THREADPOOL in TOP.

SELECT TOP 100
 [Wait type] = wait_type,
 [Wait time (s)] = wait_time_ms / 1000,
 [% waiting] = CONVERT(DECIMAL(12,2), wait_time_ms * 100.0
               / SUM(wait_time_ms) OVER())
FROM sys.dm_os_wait_stats
WHERE wait_type NOT LIKE '%SLEEP%'
ORDER BY wait_time_ms DESC;

About waits threadpool:
https://www.sqlskills.com/help/waits/threadpool/

Check this version.

Or I don't understand situation and you have problem after X seconds after connection and work query.
Check query timeout in your application via the connection string something like "queryTimeout=..."


来源: stackexchange

问:
Popup notifiers in C/C++
I've been working on a project that will need a notifier in the system tray (sorry, "System Notification Area"). It will be a simple app that just generates popup notifications when it receives a message via a Zeromq socket.

I am not having any luck finding anything other than .NET resources and examples. Does anyone have a sample in C/C++?

答:
What framework are you using? There should probably be several implementations for MFC, but there might different implementation for WTL and other frameworks. If you want to use the Windows API with no object orientation - well, you won't need any wrapper library then, but you can look at these libraries for example.

Here's one that has MFC and non-MFC version from CodeProject:
http://www.codeproject.com/KB/shell/systemtray.aspx

What you want here is probably ShowBalloon() function, which shows a balloon notification, but I'm pretty sure you must create a tray icon for that (can't have a notification balloon without having a tray icon).

ContentLicense: CC BY-SA 3.0

Title: Popup notifiers in C/C++


问:
How to check if a string date has passed a certain date
I have these strings:

```<code>yy = "19";
mm = "05";
dd = "31";
</code>```

These represent the creation date of a certain object in my project. This object expires after one month. How do I check if the object has expired already?

(I came across this solution but thought there might be another way to do it.)

UPDATE: the string date apparently represent the actual expiry date

答:
I ended up using the date format "yymmdd" so I can convert it to type long and do a simple number comparison.

```<code>sprintf(buffer, "%s%s%s", yy, mm, dd);
expiryDate = atol(buffer);

// get current date of format "yymmdd" as well
// getCurrentDate() is my function that gets the date from my SDK
currentDate = getCurrentDate();

if(expiryDate >= currentDate)
{
    // expired object!
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have these strings:

yy = "19";
mm = "05";
dd = "31";

These represent the creation date of a certain object in my project. This object expires after one month. How do I check if the object has expired already?

(I came across this solution but thought there might be another way to do it.)

UPDATE: the string date apparently represent the actual expiry date

Body:
I ended up using the date format "yymmdd" so I can convert it to type long and do a simple number comparison.

sprintf(buffer, "%s%s%s", yy, mm, dd);
expiryDate = atol(buffer);

// get current date of format "yymmdd" as well
// getCurrentDate() is my function that gets the date from my SDK
currentDate = getCurrentDate();

if(expiryDate >= currentDate)
{
    // expired object!
}


问:
Complex Group by in C#
I have a set of rows as below in DB

```<code>ID,CompName,identifier,DesId,SubId,SRO,PDiam
-----------------------------------------------
1,resistor,R1,10,20,30,45
2,resistor,R2,10,20,40,50
3,capacitor,C1,10,20,33,5
4,Inductor,I1,10,20,22,32
1,Inductor,I2,10,20,42,52
</code>```

I am trying to group them and siplay based on their Identifier as follows.
Assume column separator is pipe(|)

```<code>Ids|CompName|SRO|PDiam
-------------------------------
R1,R2|resistor|30|45  //Since there are two resistors, 2 rows foreach SRO and Pdiam Pair
R1,R2|resistor|40|50
C1|Capacitor|33|5 //One Row for Capacitor as only 1 component in DB and one pair of SRO and Pdiam Pair
I1,I2|Inductor|22|32 //2 Rows for 2 capacitors and 1 row for each pair of SRO and PDiam
I1,I2|Inductor|42|52
</code>```

I know we should use group by but not sure how to proceed it in an efficient way. The only way I could think of is iterate through the result of Group by ComponentName and Identifier but that seems too complex logic to me.

Any better way to achieve this?

答:
You could make a join of your table with the aggregated version of your table. The aggregated table would group by CompName and use string aggregation function on Identifier.

```<code>SELECT G.Ids, T.compname, T.SRO, T.PDiam FROM
components T LEFT JOIN
(SELECT compname, STRING_AGG(identifier, ',') ids FROM components GROUP BY compname) G
ON T.compname = G.compname
</code>```

(not tested)

String aggregation is however problematic in T-SQL before SqlServer 2017, so it may be difficult to do. See this post

If you need to do this in EF, the approach would be the same. Not sure if you can 'export' the string aggregation function to EF. (should be possible).

For small data in EF you can use something like this

Title: Complex Group by in C#

Body:
I have a set of rows as below in DB

ID,CompName,identifier,DesId,SubId,SRO,PDiam
-----------------------------------------------
1,resistor,R1,10,20,30,45
2,resistor,R2,10,20,40,50
3,capacitor,C1,10,20,33,5
4,Inductor,I1,10,20,22,32
1,Inductor,I2,10,20,42,52

I am trying to group them and siplay based on their Identifier as follows.
Assume column separator is pipe(|)

Ids|CompName|SRO|PDiam
-------------------------------
R1,R2|resistor|30|45  //Since there are two resistors, 2 rows foreach SRO and Pdiam Pair
R1,R2|resistor|40|50
C1|Capacitor|33|5 //One Row for Capacitor as only 1 component in DB and one pair of SRO and Pdiam Pair
I1,I2|Inductor|22|32 //2 Rows for 2 capacitors and 1 row for each pair of SRO and PDiam
I1,I2|Inductor|42|52

I know we should use group by but not sure how to proceed it in an efficient way. The only way I could think of is iterate through the result of Group by ComponentName and Identifier but that seems too complex logic to me.

Any better way to achieve this?

Body:
You could make a join of your table with the aggregated version of your table. The aggregated table would group by CompName and use string aggregation function on Identifier.

SELECT G.Ids, T.compname, T.SRO, T.PDiam FROM
components T LEFT JOIN
(SELECT compname, STRING_AGG(identifier, ',') ids FROM components GROUP BY compname) G
ON T.compname = G.compname

(not tested)

String aggregation is however problematic in T-SQL before SqlServer 2017, so it may be difficult to do. See this post

If you need to do this in EF, the approach would be the same. Not sure if you can 'export' the string aggregation function to EF. (should be possible).

For small data in EF you can use something like this


问:
Elasticsearch querying number of dates in array matching query
I have documents in the following form

```<code>PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}
</code>```

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

答:
I recently faced the same problem. However came up with two solutions.

1) If you do not want to change your current mapping, you could query for the documents using query_string. Also note you will have to create the query object according to the range that you have. ("\"2019-04-08\" OR \"2019-04-09\" OR \"2019-04-10\" ")

```<code>      {
  "query": {
    "query_string": {
      "default_field": "dates",
      "query": "\"2019-04-08\" OR \"2019-04-09\" OR \"2019-04-10\" "
    }
  }
}
</code>```

However,this type of a query only makes sense if the range is short.

2) So the second way is the nested method. But you will have to change your current mapping in such a way.

```<code> {
  "properties": {
    "dates": {
      "type": "nested",
      "properties": {
        "key": {
              "type": "date",
              "format": "YYYY-MM-dd"
            }
      }
    }
  }
}
</code>```

So your query will look something like this :-

```<code>     {
  "query": {
    "nested": {
      "path": "dates",
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "dates.key": {
                  "gte": "2018-04-01",
                  "lte": "2018-12-31"
                }
              }
            }
          ]
        }
      }
    }
  }
}
</code>```

Body:
I have documents in the following form

PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

Body:
I recently faced the same problem. However came up with two solutions.

1) If you do not want to change your current mapping, you could query for the documents using query_string. Also note you will have to create the query object according to the range that you have. ("\"2019-04-08\" OR \"2019-04-09\" OR \"2019-04-10\" ")

      {
  "query": {
    "query_string": {
      "default_field": "dates",
      "query": "\"2019-04-08\" OR \"2019-04-09\" OR \"2019-04-10\" "
    }
  }
}

However,this type of a query only makes sense if the range is short.

2) So the second way is the nested method. But you will have to change your current mapping in such a way.

 {
  "properties": {
    "dates": {
      "type": "nested",
      "properties": {
        "key": {
              "type": "date",
              "format": "YYYY-MM-dd"
            }
      }
    }
  }
}

So your query will look something like this :-

     {
  "query": {
    "nested": {
      "path": "dates",
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "dates.key": {
                  "gte": "2018-04-01",
                  "lte": "2018-12-31"
                }
              }
            }
          ]
        }
      }
    }
  }
}


问:
Selectively @JsonIgnore Immutables accessor methods, ONLY during serialization or deserialization using Jackson
This is definitely not a duplicate of Only using @JsonIgnore during serialization, but not deserialization. The problem is the same but in the context of Immutables.

When a model(DTO/DAO) is decorated as an Immutable, I am not able to selectively @JsonIgnore one of the properties during serialization. Suppose that we have a UserDto which is defined as an Immutable as follow

```<code>@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSerialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    @JsonProperty("id")
    @Value.Default
    public int getId() {
        return 0;
    }

    @JsonProperty("username")
    public abstract String getUsername();

    @JsonProperty("email")
    public abstract String getEmail();

    @JsonProperty("password")
    public abstract String getPassword();
}
</code>```

I believe it is fair to expect that during serialization we would want to ignore the password from the response of the service.

Without using Immutables if we were working with a simple class, then there are many ways to accomplish this. For example - annotate only the getter with @JsonIgnore. Or if possible define a different accessor method (something that doesn't have the get prefix) and only define the regular setter method... and so on.

If I try the same on the Immutables accessor method for the password as shown below:

```<code>@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSersonIgnoreialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    ....

    @JsonProperty("password")
    @JsonIgnore
    public abstract String getPassword();
}
</code>```

then, the generated ImmutableUserDto adds the @JsonIgnore on both the getter and setter as shown below.

```<code>@Generated(from = "UserDto", generator = "Immutables")
@SuppressWarnings({"all"})
@ParametersAreNonnullByDefault
@javax.annotation.Generated("org.immutables.processor.ProxyProcessor")
@Immutable
@CheckReturnValue
public final class ImmutableUserDto extends UserDto {
  ...
  ...
  private final String password;

  ...
  ...

  /**
   * @return The value of the {@code password} attribute
   */
  @JsonProperty("password")
  @JsonIgnore
  @Override
  public String getPassword() {
    return password;
  }

  ...
  ...
  ...

  @Generated(from = "UserDto", generator = "Immutables")
  @NotThreadSafe
  public static final class Builder {

    ...
    ...

    private String password;

    @JsonProperty("password")
    @JsonIgnore
    public final Builder setPassword(String password) {
      this.password = password;
      return this;
    }
  }
}
</code>```

Serialization will work as expected. The password attribute will be excluded from the JSON. But when I try to de-serialize, I get the following error:

```<code>java.lang.IllegalStateException: Cannot build UserDto, some of the required attributes are not set [password]
</code>```

Which is obvious as Immutables added the @JsonIgnore to the setter as well.

The documentation isn't of much help. In their Things to be aware of section, it just mentions the following regarding @JsonIgnore

If using @JsonIgnore, you should explicitly make an attribute
  non-mandatory. In Immutables, an attribute can be declared as
  non-mandatory via @Nullable, Optional or @Value.Default which are all
  different in their effect and we do not derive anything automatically.

Using @Nullable or Optional or @Value.Default is not of any use in case of fields like password.

I have gone through the issue list on their GitHub page and there is a similar issue  but the user was asking for a slightly different use case and using @Nullable could solve the problem which doesn't work in my case.

I have also tried to use one of the answers here. Still resulted in the same error.

It looked like this is not supported by Immutables library. I have created a new issue myself. Once I get some feedback from users on SOF, I will probably create a sscce.

答:
I had to use the suggestion given by @benarena in this comment. However I had to explicitly specify the value attribute of the property along with the Access attribute.

@JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY) solved the problem.

The Immutable class would look like:

```<code>@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSersonIgnoreialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    ....

    @JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY)
    public abstract String getPassword();
}
</code>```

Body:
This is definitely not a duplicate of Only using @JsonIgnore during serialization, but not deserialization. The problem is the same but in the context of Immutables.

When a model(DTO/DAO) is decorated as an Immutable, I am not able to selectively @JsonIgnore one of the properties during serialization. Suppose that we have a UserDto which is defined as an Immutable as follow

@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSerialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    @JsonProperty("id")
    @Value.Default
    public int getId() {
        return 0;
    }

    @JsonProperty("username")
    public abstract String getUsername();

    @JsonProperty("email")
    public abstract String getEmail();

    @JsonProperty("password")
    public abstract String getPassword();
}

I believe it is fair to expect that during serialization we would want to ignore the password from the response of the service.

Without using Immutables if we were working with a simple class, then there are many ways to accomplish this. For example - annotate only the getter with @JsonIgnore. Or if possible define a different accessor method (something that doesn't have the get prefix) and only define the regular setter method... and so on.

If I try the same on the Immutables accessor method for the password as shown below:

@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSersonIgnoreialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    ....

    @JsonProperty("password")
    @JsonIgnore
    public abstract String getPassword();
}

then, the generated ImmutableUserDto adds the @JsonIgnore on both the getter and setter as shown below.

@Generated(from = "UserDto", generator = "Immutables")
@SuppressWarnings({"all"})
@ParametersAreNonnullByDefault
@javax.annotation.Generated("org.immutables.processor.ProxyProcessor")
@Immutable
@CheckReturnValue
public final class ImmutableUserDto extends UserDto {
  ...
  ...
  private final String password;

  ...
  ...

  /**
   * @return The value of the {@code password} attribute
   */
  @JsonProperty("password")
  @JsonIgnore
  @Override
  public String getPassword() {
    return password;
  }

  ...
  ...
  ...

  @Generated(from = "UserDto", generator = "Immutables")
  @NotThreadSafe
  public static final class Builder {

    ...
    ...

    private String password;

    @JsonProperty("password")
    @JsonIgnore
    public final Builder setPassword(String password) {
      this.password = password;
      return this;
    }
  }
}

Serialization will work as expected. The password attribute will be excluded from the JSON. But when I try to de-serialize, I get the following error:

java.lang.IllegalStateException: Cannot build UserDto, some of the required attributes are not set [password]

Which is obvious as Immutables added the @JsonIgnore to the setter as well.

The documentation isn't of much help. In their Things to be aware of section, it just mentions the following regarding @JsonIgnore

If using @JsonIgnore, you should explicitly make an attribute
  non-mandatory. In Immutables, an attribute can be declared as
  non-mandatory via @Nullable, Optional or @Value.Default which are all
  different in their effect and we do not derive anything automatically.

Using @Nullable or Optional or @Value.Default is not of any use in case of fields like password.

I have gone through the issue list on their GitHub page and there is a similar issue  but the user was asking for a slightly different use case and using @Nullable could solve the problem which doesn't work in my case.

I have also tried to use one of the answers here. Still resulted in the same error.

It looked like this is not supported by Immutables library. I have created a new issue myself. Once I get some feedback from users on SOF, I will probably create a sscce.

Body:
I had to use the suggestion given by @benarena in this comment. However I had to explicitly specify the value attribute of the property along with the Access attribute.

@JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY) solved the problem.

The Immutable class would look like:

@Value.Immutable
@Value.Style(defaults = @Value.Immutable(copy = false), init = "set*")
@JsonSersonIgnoreialize(as = ImmutableUserDto.class)
@JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {

    ....

    @JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY)
    public abstract String getPassword();
}


问:
Nested Fragment does not show properly
I am running into an issue where I have a fragment, which contains a tab layout/view pager which handles 3 sub fragments, and when I open the main fragment the first time all the data in the sub fragments shows up properly, but when I re-open the main fragment again (clicking on a seperate listview item), the data does not get populated properly (even though it exists).

I also noticed that the only time the sub-fragment gets its data is when view paging over to the last tab,  or when rotating the screen. Also, when I try to move the screen to the right using the view pager the tab indicator will get stuck mid way between the first and second tab.

What can I do to fix this issue?

Fragment Adapter

```<code>public class DetailFragmentPagerAdapter extends FragmentPagerAdapter {

    Context context;
    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[] { "Plot", "Trailers", "Reviews" };
    private Movie movie;

    public DetailFragmentPagerAdapter(FragmentManager fm, Context context, Movie movie) {
        super(fm);
        this.context = context;
        this.movie = movie;
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0){
            return PlotFragment.newInstance(movie);
        } else if (position == 1){
            return TrailerFragment.newInstance();
        } else if (position == 2){
            return ReviewFragment.newInstance();
        } else {
            Log.e("RETURNING NULL", "RETURNING NULL");
            return null;
        }
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}
</code>```

Main Fragment

```<code>public class MovieItemDetailFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public String TAG = MovieItemDetailFragment.class.getCanonicalName();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private TextView tvTitle, tvReleaseDate, tvRating;
    private ImageView ivMoviePoster;
    private Movie movie;
    private Handler handler;

    private Button btnFavorite;
    private boolean isFavorited = false;

    private View.OnClickListener mOnClickListener;

    private ViewPager viewpager;
    private TabLayout tablayout;
    private DetailFragmentPagerAdapter adapter;

    // TODO: Rename and change types and number of parameters
    public static MovieItemDetailFragment newInstance(String param1, String param2) {
        MovieItemDetailFragment fragment = new MovieItemDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public MovieItemDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_movie_item_detail, container, false);
        init();
        return view;
    }

    private void init() {
        handler = new Handler();
        this.movie = (Movie) getArguments().getSerializable("MOVIE");

        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        tvReleaseDate = (TextView) view.findViewById(R.id.tvReleaseDate);
        tvRating = (TextView) view.findViewById(R.id.tvAvgRating);
        ivMoviePoster = (ImageView) view.findViewById(R.id.ivMoviePoster);
        btnFavorite = (Button) view.findViewById(R.id.btnFavorite);
        btnFavorite.setOnClickListener(this);

        viewpager = (ViewPager) view.findViewById(R.id.pager);
        tablayout = (TabLayout) view.findViewById(R.id.sliding_tabs);

        adapter = new DetailFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
                getActivity(), getMovie());

        viewpager.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        tablayout.post(new Runnable() {
            @Override
            public void run() {
                tablayout.setupWithViewPager(viewpager);
            }
        });

        mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFavorited = true;
                btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
            }
        };

        setElementValues();
    }

    private void setElementValues() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                tvTitle.setText(getMovie().getTitle());
                tvReleaseDate.setText(getMovie().getRelease_date());
                tvRating.setText(String.valueOf(getMovie().getVote_average()));

                Picasso.with(getActivity()).load(getMovie().getFull_poster_path()).into(ivMoviePoster);

                if (isFavorited) {
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
                } else {
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
                }

            }
        });

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnFavorite:
                if (isFavorited) {
                    isFavorited = false;
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
                    showSnackbar("I thought that was one of your favorites.");
                } else {
                    isFavorited = true;
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
                }
                break;
        }

    }

    private void showSnackbar(String msg) {
        Snackbar
                .make(view, msg, Snackbar.LENGTH_LONG)
                .setAction(R.string.snackbar_action, mOnClickListener)
                .setActionTextColor(getActivity().getResources().getColor(R.color.material_yellow_400))
                .show();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    public Movie getMovie() {
        return movie;
    }
}
</code>```

答:
This is also working for me.

Basically, the difference is that Fragment's now have their own internal FragmentManager that can handle Fragments. The child FragmentManager is the one that handles Fragments contained within only the Fragment that it was added to. The other FragmentManager is contained within the entire Activity.

for further detail about getChildFragmentManager()
visit this question

[What is difference between getSupportFragmentManager() and getChildFragmentManager()?

Title: Nested Fragment does not show properly

Body:
I am running into an issue where I have a fragment, which contains a tab layout/view pager which handles 3 sub fragments, and when I open the main fragment the first time all the data in the sub fragments shows up properly, but when I re-open the main fragment again (clicking on a seperate listview item), the data does not get populated properly (even though it exists).

I also noticed that the only time the sub-fragment gets its data is when view paging over to the last tab,  or when rotating the screen. Also, when I try to move the screen to the right using the view pager the tab indicator will get stuck mid way between the first and second tab.

What can I do to fix this issue?

Fragment Adapter

public class DetailFragmentPagerAdapter extends FragmentPagerAdapter {

    Context context;
    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[] { "Plot", "Trailers", "Reviews" };
    private Movie movie;

    public DetailFragmentPagerAdapter(FragmentManager fm, Context context, Movie movie) {
        super(fm);
        this.context = context;
        this.movie = movie;
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0){
            return PlotFragment.newInstance(movie);
        } else if (position == 1){
            return TrailerFragment.newInstance();
        } else if (position == 2){
            return ReviewFragment.newInstance();
        } else {
            Log.e("RETURNING NULL", "RETURNING NULL");
            return null;
        }
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}

Main Fragment

public class MovieItemDetailFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public String TAG = MovieItemDetailFragment.class.getCanonicalName();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private TextView tvTitle, tvReleaseDate, tvRating;
    private ImageView ivMoviePoster;
    private Movie movie;
    private Handler handler;

    private Button btnFavorite;
    private boolean isFavorited = false;

    private View.OnClickListener mOnClickListener;

    private ViewPager viewpager;
    private TabLayout tablayout;
    private DetailFragmentPagerAdapter adapter;

    // TODO: Rename and change types and number of parameters
    public static MovieItemDetailFragment newInstance(String param1, String param2) {
        MovieItemDetailFragment fragment = new MovieItemDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public MovieItemDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_movie_item_detail, container, false);
        init();
        return view;
    }

    private void init() {
        handler = new Handler();
        this.movie = (Movie) getArguments().getSerializable("MOVIE");

        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        tvReleaseDate = (TextView) view.findViewById(R.id.tvReleaseDate);
        tvRating = (TextView) view.findViewById(R.id.tvAvgRating);
        ivMoviePoster = (ImageView) view.findViewById(R.id.ivMoviePoster);
        btnFavorite = (Button) view.findViewById(R.id.btnFavorite);
        btnFavorite.setOnClickListener(this);

        viewpager = (ViewPager) view.findViewById(R.id.pager);
        tablayout = (TabLayout) view.findViewById(R.id.sliding_tabs);

        adapter = new DetailFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
                getActivity(), getMovie());

        viewpager.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        tablayout.post(new Runnable() {
            @Override
            public void run() {
                tablayout.setupWithViewPager(viewpager);
            }
        });

        mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFavorited = true;
                btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
            }
        };

        setElementValues();
    }

    private void setElementValues() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                tvTitle.setText(getMovie().getTitle());
                tvReleaseDate.setText(getMovie().getRelease_date());
                tvRating.setText(String.valueOf(getMovie().getVote_average()));

                Picasso.with(getActivity()).load(getMovie().getFull_poster_path()).into(ivMoviePoster);

                if (isFavorited) {
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
                } else {
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
                }

            }
        });

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnFavorite:
                if (isFavorited) {
                    isFavorited = false;
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
                    showSnackbar("I thought that was one of your favorites.");
                } else {
                    isFavorited = true;
                    btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
                }
                break;
        }

    }

    private void showSnackbar(String msg) {
        Snackbar
                .make(view, msg, Snackbar.LENGTH_LONG)
                .setAction(R.string.snackbar_action, mOnClickListener)
                .setActionTextColor(getActivity().getResources().getColor(R.color.material_yellow_400))
                .show();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    public Movie getMovie() {
        return movie;
    }
}


问:
SQL Server select query very slow
I have direct table with 2 million records, while running select statement in the SQL query builder, it is very fast, but through program, it takes 35 minutes for 1100 records. I have two columns icno and efpno. These two columns have duplicate records. My table has a clustered index and one nonclustered index with icno and efpno.

Please check my query and advice.

SELECT COUNT(*)
INTO p_count
FROM ct_rgpldgr
WHERE ctrgp_nric = p_ctegd.ctegd_nric
  AND ctrgp_epfno = p_ctegd.ctegd_epfno
```

ctrgp_nric,ctrgp_epfno from load file. this query reading from .txt file. This nric and epf number will be inside the load file.

I run tuning adviser and execution plane but it show estimation cost 0.03.

Please advice

Thanks

答:
Most of the times the reason for the query being slow are full table scans. In order to find out where these full table scans happens you need to know the execution plan off your query. This can be done for example with Microsoft SQL Server Management Studio.

You can get the estimated execution plan in Microsoft SQL Server Management Studio by highlighting your query and then clicking on the following menu item:

This will display a graph like this one:

This graph has a cost estimation on each node. Especially interesting are the nodes which have a high cost like the one which is highlighted above. The nodes with a high cost indicate mostly tables where MSSQL is performing a full table scan and on which potentially you will need to add some index. After you know which tables are being fully scanned you will need to find the column on which you should build the index and that is typically a column in your query on which you are performing an inner join.

Title: SQL Server select query very slow

Body:
I have direct table with 2 million records, while running select statement in the SQL query builder, it is very fast, but through program, it takes 35 minutes for 1100 records. I have two columns icno and efpno. These two columns have duplicate records. My table has a clustered index and one nonclustered index with icno and efpno.

Please check my query and advice.

SELECT COUNT(*)
INTO p_count
FROM ct_rgpldgr
WHERE ctrgp_nric = p_ctegd.ctegd_nric
  AND ctrgp_epfno = p_ctegd.ctegd_epfno

ctrgp_nric,ctrgp_epfno from load file. this query reading from .txt file. This nric and epf number will be inside the load file.

I run tuning adviser and execution plane but it show estimation cost 0.03.

Please advice

Thanks


问:
Best method for measure memory usage during matlab operation
How can I get the memory usage for execution of an instruction in matlab? I look like for something like the tic toc function.
The problem is that the method must work on windows and on linux.

I try to use this function that use the whos command but it doesn't work, it return a wrong value.

I would get the memory usage of this command

```<code>solution = matrix \ knownTerms;
</code>```

where solution and knownTerms are two vector.
How can I get the memory used by this operation?

答: If your code is inside a function, you can use the memory mode of the Matlab Profiler to get rough function-level memory usage. Run profile on -memory, run your code, and then run profile report. If you need to get the memory usage of just that one statement, wrap it in a local function.

Body:
How can I get the memory usage for execution of an instruction in matlab? I look like for something like the tic toc function.
The problem is that the method must work on windows and on linux.

I try to use this function that use the whos command but it doesn't work, it return a wrong value.

I would get the memory usage of this command

solution = matrix \ knownTerms;

where solution and knownTerms are two vector.
How can I get the memory used by this operation?


问:
how to set prompt textbox field in js as required field?
How to set the textbox field in the prompt box as a required field?</p>

```<code>var answer=prompt('Reason for deletion?');
</code>```

答:
If you want be able to also cancel prompt it's possible to modify condition from @A.Wolf post.

```<code>do{
    var answer = prompt('Reason for deletion? Note is required');
} while(answer !== null && answer === "")
</code>```

fiddle example

Body:
How to set the textbox field in the prompt box as a required field?

var answer=prompt('Reason for deletion?');

Body:
If you want be able to also cancel prompt it's possible to modify condition from @A.Wolf post.

do{
    var answer = prompt('Reason for deletion? Note is required');
} while(answer !== null && answer === "")

fiddle example


问:
Why a:active pseudo class does not working
Am using css for some site. I noticed that the a:active style definition in my css file does not work at all. I was told by someone that I have to put the definitions in this order

```<code>a:link {...}
a:visited {...}
a:hover {...}
a:active {...}
</code>```

I have done so but it's still not working. Please could someone tell me why it is not working and a possible workaround. Thanks

答:
a:active just stay for the few milliseconds you are clicking the link.

May i ask what you expect to see? In case you want a link to be a different color if you are on that page, thats not what a:active is for

Body:
Am using css for some site. I noticed that the a:active style definition in my css file does not work at all. I was told by someone that I have to put the definitions in this order

a:link {...}
a:visited {...}
a:hover {...}
a:active {...}

I have done so but it's still not working. Please could someone tell me why it is not working and a possible workaround. Thanks


问:
Kotlin - How do I concatenate a String to an Int value?
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

```<code>for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}
</code>```

Expected Outcome

15 14 13 12 11 10

答:
The Int::toString method does what you're looking for. Instead of explicit loops, consider functional approaches like map:

```<code>(15 downTo 10).map(Int::toString).joinToString { " " }
</code>```

Note that the map part is even redundant since joinToString can handle the conversion internally.

Body:
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}

Expected Outcome

15 14 13 12 11 10

Body:
The Int::toString method does what you're looking for. Instead of explicit loops, consider functional approaches like map:

(15 downTo 10).map(Int::toString).joinToString { " " }

Note that the map part is even redundant since joinToString can handle the conversion internally.


问:
Given two lists(A,B) with same length, How can I find the index(i) which makes the max(sum(A[:i],B[i:]),sum(A[i:],B[:i])) smallest?
I am working on an online challenge problem, and I can solve this problem with brute force, but when the length became very large, the runtime is significantly increased, I believe there must be a better algorithm to solve this problem, but it is just out of my hand. I appreciate any brilliant ideas.</p>

答:
If you are allowed to use numpy, by using numpy.cumsum method you can find store sum(A[:i]), sum(A[i:]), sum(B[:i]), and sum(B[i:]) values in four different arrays as follows

import numpy as np

A = []  # Array A
B = []  # Array B
A_start_to_i = np.cumsum(A)  # A_start_to_i[i] = sum(A[:i])
A.reverse()  # Reverse the order
A_i_to_end = np.cumsum(A)  # A_i_to_end[i] = sum(A[i:])
B_start_to_i = np.cumsum(B)  # B_start_to_i[i] = sum(B[:i])
B.reverse()  # Reverse the order
B_i_to_end = np.cumsum(B)  # B_i_to_end = sum(B[i:])
```

<p>Now all you need to do is to create <code>sum(A[:i], B[i:])</code> and <code>sum(B[:i], A[i:])</code> and find the index with the minimum element.</p>

<pre class="lang-py prettyprint-override"><code>first_array = A_start_to_i + B_i_to_end  # first_array[i] = sum(A[:i], B[i:])
second_array = A_i_to_end + B_start_to_i  # second_array[i] = sum(B[:i], A[i:])

# Find which array has the minimum element
idx = np.argmin([min(first_array), min(second_array)])
if idx == 0:
   # First array has the minimum element
   i = np.argmin(first_array)
else:
   # Second array has the minimum element
   i = np.argmin(second_array)

</code>```

Body:
If you are allowed to use numpy, by using numpy.cumsum method you can find store sum(A[:i]), sum(A[i:]), sum(B[:i]), and sum(B[i:]) values in four different arrays as follows

import numpy as np

A = []  # Array A
B = []  # Array B
A_start_to_i = np.cumsum(A)  # A_start_to_i[i] = sum(A[:i])
A.reverse()  # Reverse the order
A_i_to_end = np.cumsum(A)  # A_i_to_end[i] = sum(A[i:])
B_start_to_i = np.cumsum(B)  # B_start_to_i[i] = sum(B[:i])
B.reverse()  # Reverse the order
B_i_to_end = np.cumsum(B)  # B_i_to_end = sum(B[i:])

Now all you need to do is to create sum(A[:i], B[i:]) and sum(B[:i], A[i:]) and find the index with the minimum element.

first_array = A_start_to_i + B_i_to_end  # first_array[i] = sum(A[:i], B[i:])
second_array = A_i_to_end + B_start_to_i  # second_array[i] = sum(B[:i], A[i:])

# Find which array has the minimum element
idx = np.argmin([min(first_array), min(second_array)])
if idx == 0:
   # First array has the minimum element
   i = np.argmin(first_array)
else:
   # Second array has the minimum element
   i = np.argmin(second_array)


问:
How to get hierarchy children based on a parent id in a SQL table?
I am using postgresql for laravel api. I have users table that contain data like below,

```<code>id    parent_id
2
7     2
3     2
14    3
5     3
6     3
17    3
4     3
</code>```

I face difficulties to query the data, if I have parameters parent_id = 2, then the result data should be like this,

```<code>id

7
3
14
5
6
17
4
</code>```

I had been tried this SQL code

```<code>WITH    q AS
        (
        SELECT  *
        FROM    users
        WHERE   parent_id = 2
        UNION ALL
        SELECT  m.*
        FROM    users as m
        JOIN    q
        ON      m.parent_id = q.id
        )
SELECT  *
FROM    q
</code>```

But it showed error

```<code>SQL Error [42P01]: ERROR: relation "q" does not exist¶  Detail: There is a WITH item named "q", but it cannot be referenced from this part of the query.¶  Hint: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.¶  Position: 269
</code>```

I don't know what's the problem is,
Can somebody help me to solve this problem?
Any help would be appreciate ! Thanks!

答:
try like below</p>

```<code>select id from users where parent_id=2
union
select id from users
where parent_id in ( select id from table where parentid=2)
</code>```

Body:
I am using postgresql for laravel api. I have users table that contain data like below,

id    parent_id
2
7     2
3     2
14    3
5     3
6     3
17    3
4     3

I face difficulties to query the data, if I have parameters parent_id = 2, then the result data should be like this,

id

7
3
14
5
6
17
4

I had been tried this SQL code

WITH    q AS
        (
        SELECT  *
        FROM    users
        WHERE   parent_id = 2
        UNION ALL
        SELECT  m.*
        FROM    users as m
        JOIN    q
        ON      m.parent_id = q.id
        )
SELECT  *
FROM    q

But it showed error

SQL Error [42P01]: ERROR: relation "q" does not exist¶  Detail: There is a WITH item named "q", but it cannot be referenced from this part of the query.¶  Hint: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.¶  Position: 269

I don't know what's the problem is,
Can somebody help me to solve this problem?
Any help would be appreciate ! Thanks!

Body:
try like below

select id from users where parent_id=2
union
select id from users
where parent_id in ( select id from table where parentid=2)


问:
AES de/encryption in C and PHP
So this is the code I am using as an example

```<code>Aes128KeyLength = 128/8;

    //
    // Allocate Key buffer
    //

    Aes128Key = (PBYTE) HeapAlloc( GetProcessHeap(), 0, Aes128KeyLength);
    if( NULL == Aes128Key )
    {
        Status = STATUS_NO_MEMORY;
        ReportError(Status);
        goto cleanup;
    }

    //
    // Derive the AES 128 key from the password
    // Using PBKDF2
    //

    //
    // Open an algorithm handle
    //

    Status = BCryptOpenAlgorithmProvider(
                                        &KdfAlgHandle,              // Alg Handle pointer
                                        BCRYPT_PBKDF2_ALGORITHM,    // Cryptographic Algorithm name (null terminated unicode string)
                                        NULL,                       // Provider name; if null, the default provider is loaded
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

    //
    // Create a key handle to the password
    //

    Status = BCryptGenerateSymmetricKey(
                                        KdfAlgHandle,               // Algorithm Handle
                                        &Aes128PasswordKeyHandle,   // A pointer to a key handle
                                        NULL,                       // Buffer that recieves the key object;NULL implies memory is allocated and freed by the function
                                        0,                          // Size of the buffer in bytes
                                        (PBYTE)Aes128Password,      // Buffer that contains the key material
                                        sizeof (Aes128Password),    // Size of the buffer in bytes
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

    //
    // Derive AES key from the password
    //

    Status = BCryptKeyDerivation(
                                        Aes128PasswordKeyHandle,    // Handle to the password key
                                        &PBKDF2Parameters,          // Parameters to the KDF algorithm
                                        Aes128Key,                  // Address of the buffer which recieves the derived bytes
                                        Aes128KeyLength,            // Size of the buffer in bytes
                                        &ResultLength,              // Variable that recieves number of bytes copied to above buffer
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

</code>```

I am using hash_pbkdf2 function for the same thing on the PHP side.
in PHP i added echo hash_pbkdf2("sha256","PASSWORD", $salt,1000, 16, TRUE);

what is the reason for this? I have tried various standard tests I found online but still the output is not the same. I cannot see where I am possibly messing up. For the C code from the the number of iterations is 1000 along with the same value on the PHP side. All the values I am passing to the function are the same on the PHP and C side. yet the output on the C and PHP side the derived key is not the same? What am I doing wrong or Is there some capability issue I should be aware of?

答:
Except iterations you have mentioned, salt also effect the generated key.

The following I use the same salt 'a' / 0x61 in both php and C++ (sample).

```<code><?php
$password = "PASSWORD";
$iterations = 1000;
$salt = 'a'; //0x61

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 16);
echo $hash;
?>
</code>```

So if you use the same salt value with the one in CipherEncryptionDecryption.cpp you will get the same result.

```<code>static const
BYTE Salt [] =
{
    0x61
};
</code>```

Both give me the result:

32f8b5d8c4d1aa1fbb39a0a33338ccb1

Title: AES de/encryption in C and PHP

Body:
So this is the code I am using as an example

Aes128KeyLength = 128/8;

    //
    // Allocate Key buffer
    //

    Aes128Key = (PBYTE) HeapAlloc( GetProcessHeap(), 0, Aes128KeyLength);
    if( NULL == Aes128Key )
    {
        Status = STATUS_NO_MEMORY;
        ReportError(Status);
        goto cleanup;
    }

    //
    // Derive the AES 128 key from the password
    // Using PBKDF2
    //

    //
    // Open an algorithm handle
    //

    Status = BCryptOpenAlgorithmProvider(
                                        &KdfAlgHandle,              // Alg Handle pointer
                                        BCRYPT_PBKDF2_ALGORITHM,    // Cryptographic Algorithm name (null terminated unicode string)
                                        NULL,                       // Provider name; if null, the default provider is loaded
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

    //
    // Create a key handle to the password
    //

    Status = BCryptGenerateSymmetricKey(
                                        KdfAlgHandle,               // Algorithm Handle
                                        &Aes128PasswordKeyHandle,   // A pointer to a key handle
                                        NULL,                       // Buffer that recieves the key object;NULL implies memory is allocated and freed by the function
                                        0,                          // Size of the buffer in bytes
                                        (PBYTE)Aes128Password,      // Buffer that contains the key material
                                        sizeof (Aes128Password),    // Size of the buffer in bytes
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

    //
    // Derive AES key from the password
    //

    Status = BCryptKeyDerivation(
                                        Aes128PasswordKeyHandle,    // Handle to the password key
                                        &PBKDF2Parameters,          // Parameters to the KDF algorithm
                                        Aes128Key,                  // Address of the buffer which recieves the derived bytes
                                        Aes128KeyLength,            // Size of the buffer in bytes
                                        &ResultLength,              // Variable that recieves number of bytes copied to above buffer
                                        0);                         // Flags
    if( !NT_SUCCESS(Status) )
    {
        ReportError(Status);
        goto cleanup;
    }

I am using hash_pbkdf2 function for the same thing on the PHP side.
in PHP i added echo hash_pbkdf2("sha256","PASSWORD", $salt,1000, 16, TRUE);

what is the reason for this? I have tried various standard tests I found online but still the output is not the same. I cannot see where I am possibly messing up. For the C code from the the number of iterations is 1000 along with the same value on the PHP side. All the values I am passing to the function are the same on the PHP and C side. yet the output on the C and PHP side the derived key is not the same? What am I doing wrong or Is there some capability issue I should be aware of?

Body:
Except iterations you have mentioned, salt also effect the generated key.

The following I use the same salt 'a' / 0x61 in both php and C++ (sample).

<?php
$password = "PASSWORD";
$iterations = 1000;
$salt = 'a'; //0x61

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 16);
echo $hash;
?>

So if you use the same salt value with the one in CipherEncryptionDecryption.cpp you will get the same result.

static const
BYTE Salt [] =
{
    0x61
};

Both give me the result:

32f8b5d8c4d1aa1fbb39a0a33338ccb1


问:
React Native Elements Line underneath FormInput Component
I'm using the FormInput element from React Native Elements, which seems to produce a line underneath each FormInput component. One is more faint than the other.

Form looks as follows

```<code><View style={styles.container}>
                <Image
                    style={styles.image}
                    source={app.imageBackground}
                />
                <View style={{ alignItems: 'center' }}>
                    <Image
                        style={styles.logo}
                        source={app.logo}
                    />
                </View>

                <View  style={styles.cardWrapper}>
                    <View style={styles.card}>
                        <FormInput
                            inputStyle={styles.textInput}
                            placeholder='user@email.com'
                            autoCapitalize='none'
                            autoCorrect={false}
                            underlineColorAndroid='transparent'
                            placeholderTextColor='white'
                            onChangeText={this.onEmailChange.bind(this)}
                        />
                        <FormInput
                            secureTextEntry={true}
                            autoCapitalize='none'
                            placeholder='password'
                            autoCorrect={false}
                            inputStyle={styles.textInput}
                            underlineColorAndroid='transparent'
                            placeholderTextColor = 'white'
                            onChangeText={this.onPasswordChange.bind(this)}
                        />
                        <FormValidationMessage>{this.renderError()}</FormValidationMessage>
                        {this.renderButton()}

                        <Text style={{color:'white', textAlign:'center'}}>New to Foodspecials?<Text style={{fontWeight:'900'}} onPress={() => this.props.navigation.navigate('SignUp')}> Sign up</Text></Text>
                    </View>
                </View>

            </View>
</code>```

Here are my styles

```<code>const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    cardWrapper: {
        padding: 20
    },
    card: {

    },
    logo: {
        justifyContent: 'center',
    },
    image: {
        backgroundColor: '#ccc',
        flex: 1,
        position: 'absolute',
        width: '100%',
        height: '100%',
        justifyContent: 'center',
    },
    textInput: {
        height: 50,
        fontSize: 20,
        borderRadius: 50,
        backgroundColor: 'rgba(255, 255, 255, 0.3)',
        color: 'white',
        width: '100%',
        paddingLeft: 20,
        marginTop: 10,
        marginBottom: 10
    },
    button: {
        borderWidth: 2,
        borderColor: 'white',
        marginTop: 10,
        marginBottom: 10
    }
})
</code>```

I've tried to add a borderWidth property of 0 to the FormInput but this doesn't seem to work.

I've also tried to set a borderColor to transparent which didn't work either.

I've also noticed, if I remove the FormValidationMessage component, both line become more apparent.

Is there a workaround for this?

答:
I was facing the same issue and fixed it by adding borderBottomWidth:0 as belows:

```<code><Input inputContainerStyle={{borderBottomWidth:0}} />
</code>```

Body:
I'm using the FormInput element from React Native Elements, which seems to produce a line underneath each FormInput component. One is more faint than the other.

Form looks as follows

<View style={styles.container}>
                <Image
                    style={styles.image}
                    source={app.imageBackground}
                />
                <View style={{ alignItems: 'center' }}>
                    <Image
                        style={styles.logo}
                        source={app.logo}
                    />
                </View>

                <View  style={styles.cardWrapper}>
                    <View style={styles.card}>
                        <FormInput
                            inputStyle={styles.textInput}
                            placeholder='user@email.com'
                            autoCapitalize='none'
                            autoCorrect={false}
                            underlineColorAndroid='transparent'
                            placeholderTextColor='white'
                            onChangeText={this.onEmailChange.bind(this)}
                        />
                        <FormInput
                            secureTextEntry={true}
                            autoCapitalize='none'
                            placeholder='password'
                            autoCorrect={false}
                            inputStyle={styles.textInput}
                            underlineColorAndroid='transparent'
                            placeholderTextColor = 'white'
                            onChangeText={this.onPasswordChange.bind(this)}
                        />
                        <FormValidationMessage>{this.renderError()}</FormValidationMessage>
                        {this.renderButton()}

                        <Text style={{color:'white', textAlign:'center'}}>New to Foodspecials?<Text style={{fontWeight:'900'}} onPress={() => this.props.navigation.navigate('SignUp')}> Sign up</Text></Text>
                    </View>
                </View>

            </View>

Here are my styles

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    cardWrapper: {
        padding: 20
    },
    card: {

    },
    logo: {
        justifyContent: 'center',
    },
    image: {
        backgroundColor: '#ccc',
        flex: 1,
        position: 'absolute',
        width: '100%',
        height: '100%',
        justifyContent: 'center',
    },
    textInput: {
        height: 50,
        fontSize: 20,
        borderRadius: 50,
        backgroundColor: 'rgba(255, 255, 255, 0.3)',
        color: 'white',
        width: '100%',
        paddingLeft: 20,
        marginTop: 10,
        marginBottom: 10
    },
    button: {
        borderWidth: 2,
        borderColor: 'white',
        marginTop: 10,
        marginBottom: 10
    }
})

I've tried to add a borderWidth property of 0 to the FormInput but this doesn't seem to work.

I've also tried to set a borderColor to transparent which didn't work either.

I've also noticed, if I remove the FormValidationMessage component, both line become more apparent.

Is there a workaround for this?

Body:
I was facing the same issue and fixed it by adding borderBottomWidth:0 as belows:

<Input inputContainerStyle={{borderBottomWidth:0}} />


问:
cx_freeze error with pyodbc
if you have a simple program name pyodbcTest.py

```<code>import pyodbc
print "pass"
</code>```

and then use cx_freeze to compile it

```<code>cxfreeze --targe-dir=cxTest pyodbcTest.py
</code>```

and then run that program it throws the following error.

```<code>C:\temp\pythonWork\cxTest>pyodbcTest.exe
Traceback (most recent call last):
    File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
        exec code in m.__dict__
    File "pyodbcTest.py", line 1, in <module>
 RuntimeError: Unable to import decimal
</code>```

Any ideas?

答: I had to add the option --include-module decimal to solve the problem.  Not sure why it could not find that one on its own during the freeze process, but its working now</p>

Title: cx_freeze error with pyodbc

Body:
if you have a simple program name pyodbcTest.py

import pyodbc
print "pass"

and then use cx_freeze to compile it

cxfreeze --targe-dir=cxTest pyodbcTest.py

and then run that program it throws the following error.

C:\temp\pythonWork\cxTest>pyodbcTest.exe
Traceback (most recent call last):
    File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
        exec code in m.__dict__
    File "pyodbcTest.py", line 1, in <module>
 RuntimeError: Unable to import decimal

Any ideas?


问:
How to Use a Wildcard (%) in Pandas read_sql()
I am trying to run a MySQL query that has a text wildcard in as demonstrated below:

```<code>import sqlalchemy
import pandas as pd

#connect to mysql database
engine = sqlalchemy.create_engine('mysql://user:@localhost/db?charset=utf8')
conn = engine.connect()

#read sql into pandas dataframe
mysql_statement = """SELECT * FROM table WHERE field LIKE '%part%'; """
df = pd.read_sql(mysql_statement, con=conn)
</code>```

When run I get the error as shown below related to formatting.

TypeError: not enough arguments for format string

How can I use a wild card when reading MySQL with Pandas?

答:
```<code>from sqlalchemy import create_engine, text
import pandas as pd

mysql_statement = """SELECT * FROM table WHERE field LIKE '%part%'; """
df = pd.read_sql( text(mysql_statement), con=conn)
</code>```

You can use text() function from sqlalchemy

Body:
I am trying to run a MySQL query that has a text wildcard in as demonstrated below:

import sqlalchemy
import pandas as pd

#connect to mysql database
engine = sqlalchemy.create_engine('mysql://user:@localhost/db?charset=utf8')
conn = engine.connect()

#read sql into pandas dataframe
mysql_statement = """SELECT * FROM table WHERE field LIKE '%part%'; """
df = pd.read_sql(mysql_statement, con=conn)

When run I get the error as shown below related to formatting.

TypeError: not enough arguments for format string

How can I use a wild card when reading MySQL with Pandas?

Body:
from sqlalchemy import create_engine, text
import pandas as pd

mysql_statement = """SELECT * FROM table WHERE field LIKE '%part%'; """
df = pd.read_sql( text(mysql_statement), con=conn)

You can use text() function from sqlalchemy


答:
You can use kotlin string template for that:

```<code>for (i in 15 downTo 10){
  print("$i ");
}
</code>```

https://kotlinlang.org/docs/reference/basic-types.html#string-templates

Title: Kotlin - How do I concatenate a String to an Int value?

Body:
You can use kotlin string template for that:

for (i in 15 downTo 10){
  print("$i ");
}

https://kotlinlang.org/docs/reference/basic-types.html#string-templates


问:
Access Control Allow Origin error with WordPress subdomain
I'm facing a problem with my WordPress website, it has a subdomain, blog.domain.com, when I access the blog I get the following error in my console:

Access to Font at www.domain.com/wp-content/themes/Divi/core/admin/fonts/modules.ttf from origin blog.domain.com has been blocked by CORS policy: No Access-Control-Allow-Origin header is present on the requested resource.

Currently, my website is hosted in Azure, I tried activating the option "Cross-Origin Resource Sharing - Cors" in my hosting options, it solved the issue, but it made the website a lot slower (16 sec), so I'm looking for an alternative to this issue.

If anyone has any idea how I can resolve this, I am opened to suggestions, I would appreciate it!

Thanks

答:
If you use the windows azure web app, I suggest you could try to access below url:

https://yourwebappname.scm.azurewebsites.net/DebugConsole

Then you should go to the site\wwwroot and find the web.config file and add below config setting:

```<code> <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</code>```

Body:
If you use the windows azure web app, I suggest you could try to access below url:

https://yourwebappname.scm.azurewebsites.net/DebugConsole

Then you should go to the site\wwwroot and find the web.config file and add below config setting:

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>


问:
Package signatures do not match the previously installed version
This my project: https://github.com/kenpeter/my_hak_news, which is a direct copy of https://github.com/grigio/HAgnostic-News.

Git clone https://github.com/kenpeter/my_hak_news, then run react-native run-android

Got this error:

```<code>* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.hagnosticnews signatures do not match the previously installed version; ignoring!
</code>```

Relevant issue: https://github.com/grigio/HAgnostic-News/issues/1, I follow various ways, but not able to resolve this issue.

答: In my case, uninstall installed application in connected device resolved my problem</p>

Body:
This my project: https://github.com/kenpeter/my_hak_news, which is a direct copy of https://github.com/grigio/HAgnostic-News.

Git clone https://github.com/kenpeter/my_hak_news, then run react-native run-android

Got this error:

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.hagnosticnews signatures do not match the previously installed version; ignoring!

Relevant issue: https://github.com/grigio/HAgnostic-News/issues/1, I follow various ways, but not able to resolve this issue.


问:
Not able to curl jenkins service from other ec2 instances
I have jenkins installed on one of the ec2 instances. I am able to run the below commands on the same ec2 and confirm that the connection is successful.

```<code>curl -vk 'http://<private ip>:9009/jenkins'
curl -vk 'http://localhost:9009/jenkins'
</code>```

However, I cannot execute these commands from any other ec2 instance even though security group attached to the jenkins ec2 instance allows all kinds of inbound connections.

I get below error when I try connecting from other ec2 instances.

```<code>[root@ip-<private ip> ~]# curl -vk 'http://<private ip>:9009/jenkins'
* About to connect() to <private ip> port 9009 (#0)
*   Trying <private ip>...
* No route to host
* Failed connect to <private ip>:9009; No route to host
* Closing connection 0
curl: (7) Failed connect to <private ip>:9009; No route to host
</code>```

Can someone please tell me what is going wrong here ?

OS- Red Hat 7

答:
On Red Hat 7, firewalld is enabled by default. so, please disable firewalld on Red Hat 7

OR open port 9009 only as needed:

```<code>firewall-cmd --permanent --add-port=9009/tcp

firewall-cmd --reload
</code>```

Body:
I have jenkins installed on one of the ec2 instances. I am able to run the below commands on the same ec2 and confirm that the connection is successful.

curl -vk 'http://<private ip>:9009/jenkins'
curl -vk 'http://localhost:9009/jenkins'

However, I cannot execute these commands from any other ec2 instance even though security group attached to the jenkins ec2 instance allows all kinds of inbound connections.

I get below error when I try connecting from other ec2 instances.

[root@ip-<private ip> ~]# curl -vk 'http://<private ip>:9009/jenkins'
* About to connect() to <private ip> port 9009 (#0)
*   Trying <private ip>...
* No route to host
* Failed connect to <private ip>:9009; No route to host
* Closing connection 0
curl: (7) Failed connect to <private ip>:9009; No route to host

Can someone please tell me what is going wrong here ?

OS- Red Hat 7

Body:
On Red Hat 7, firewalld is enabled by default. so, please disable firewalld on Red Hat 7

OR open port 9009 only as needed:

firewall-cmd --permanent --add-port=9009/tcp

firewall-cmd --reload


问:
pselect() not recognizing the socket having any IO activity
take for instance the following code snippet, the creation of the socket, listening and acceptance of a new socket works fine.  The non-blocking mode is also working, however the pselect (or even replacing with select) is not recognizing any IO requests ready on the FDset.  so the return value is always 0 (timed out).

I was wondering if I need to set anything else further before going into pselect() so that it recognizes the IO activity.

```<code>.....
 // Create the socket
        *m_pSockFD = socket(AF_INET, SOCK_STREAM, 0);
        if( *this->m_pSockFD == -1 ){
            throw ....
        }

        // Set the socket address information
        m_pSockAddr->sin_family = AF_INET;
        m_pSockAddr->sin_port =  htons( 6001 );
        m_pSockAddr->sin_addr.s_addr = INADDR_ANY;

        if( bind(*m_pSockFD, (struct sockaddr *) m_pSockAddr, sizeof(*m_pSockAddr) ) != 0 ){
                .....
        }

        // Listen on this socket using a block queue of 5 - default Block Size
        if( listen( *m_pSockFD, 5) != 0 )
                ........

        // change function control to non blocking file descritor for I/O operations
        long fcntlArg;
        if( (fcntlArg = fcntl( *m_pSockFD, F_GETFL, NULL ) ) < 0 ){
               ...........
        }

        fcntlArg |= O_NONBLOCK;
        if( fcntl( *m_pSockFD, F_SETFL, fcntlArg ) <0 ){
              ...........
        }

        //.........

        int newFD = -1;
        socklen_t salen = sizeof(*m_pSockAddr);

        // loop selecting for a I/O operation ready on the file descriptor then go into accept mode
        struct timespec timeOut;
        timeOut.tv_sec = 1;
        timeOut.tv_nsec = 0;

        fd_set fdset;
        FD_SET( *this->m_pSockFD, &fdset );

        while( !m_bShutDownFinished ){

            // TODO pselect is not registering the activity on the socket
            if( pselect( *this->m_pSockFD, &fdset, NULL , NULL , &timeOut,  NULL ) > 0 ){
                cout << "hello client" << endl;
                break;
            }

            // re-initialize the time struct
            timeOut.tv_sec = 1;
            timeOut.tv_nsec = 0;
        }

        // application is shutting down do not try to accept a new socket
        if( m_bShutDownFinished ) return -1;

        newFD = accept(*m_pSockFD, (struct sockaddr *) m_pSockAddr, &salen);
        if( newFD > -1 ){
            ................
        }

        return newFD;
</code>```

答: First argument of pselect should be *this->m_pSockFD + 1, shouldn't it?

ContentLicense: CC BY-SA 2.5

Body:
take for instance the following code snippet, the creation of the socket, listening and acceptance of a new socket works fine.  The non-blocking mode is also working, however the pselect (or even replacing with select) is not recognizing any IO requests ready on the FDset.  so the return value is always 0 (timed out).

I was wondering if I need to set anything else further before going into pselect() so that it recognizes the IO activity.

.....
 // Create the socket
        *m_pSockFD = socket(AF_INET, SOCK_STREAM, 0);
        if( *this->m_pSockFD == -1 ){
            throw ....
        }

        // Set the socket address information
        m_pSockAddr->sin_family = AF_INET;
        m_pSockAddr->sin_port =  htons( 6001 );
        m_pSockAddr->sin_addr.s_addr = INADDR_ANY;

        if( bind(*m_pSockFD, (struct sockaddr *) m_pSockAddr, sizeof(*m_pSockAddr) ) != 0 ){
                .....
        }

        // Listen on this socket using a block queue of 5 - default Block Size
        if( listen( *m_pSockFD, 5) != 0 )
                ........

        // change function control to non blocking file descritor for I/O operations
        long fcntlArg;
        if( (fcntlArg = fcntl( *m_pSockFD, F_GETFL, NULL ) ) < 0 ){
               ...........
        }

        fcntlArg |= O_NONBLOCK;
        if( fcntl( *m_pSockFD, F_SETFL, fcntlArg ) <0 ){
              ...........
        }

        //.........

        int newFD = -1;
        socklen_t salen = sizeof(*m_pSockAddr);

        // loop selecting for a I/O operation ready on the file descriptor then go into accept mode
        struct timespec timeOut;
        timeOut.tv_sec = 1;
        timeOut.tv_nsec = 0;

        fd_set fdset;
        FD_SET( *this->m_pSockFD, &fdset );

        while( !m_bShutDownFinished ){

            // TODO pselect is not registering the activity on the socket
            if( pselect( *this->m_pSockFD, &fdset, NULL , NULL , &timeOut,  NULL ) > 0 ){
                cout << "hello client" << endl;
                break;
            }

            // re-initialize the time struct
            timeOut.tv_sec = 1;
            timeOut.tv_nsec = 0;
        }

        // application is shutting down do not try to accept a new socket
        if( m_bShutDownFinished ) return -1;

        newFD = accept(*m_pSockFD, (struct sockaddr *) m_pSockAddr, &salen);
        if( newFD > -1 ){
            ................
        }

        return newFD;

OwnerDisplayName: Ryan Graham