问:
Using Spring Security OAuth2, what's the right way to refresh the stored authentication in the TokenStore?
We're using resource-owner credentials grant type (with oauth2:password in security-config.xml. Let's play out this scenario to explain my predicament:

Bob was created with authorities ROLE_USER

Bob tries to access an oauth2 protected resource

Bob uses the official mobile app to access it, so the client credentials are correct

Bob's access token is created and stored in the TokenStore, keyed on his username, client_id, and scope. (see DefaultAuthenticationKeyGenerator.java)

Bob's phone tries to call the protected services with this access token, but those services require users to have an authority of ROLE_MOBILE_USER.

Bob contacts the db owner and has ROLE_MOBLE_USER added to his user in the database.

Bob tries to get another access token, but the DefaultTokenServices returns him the same, non-working access token.

The only way to take advantage of his new authority is to wait until his old access token expires so he can get a new access token with the correct authority.

There are a number of ways to address this.

For one, the administration app that adds ROLE_MOBILE_USER to Bob's authorities could then clear all access tokens and authorizations in the database. This way the DefaultTokenServices will just create a new one with the correct authorities serialized as his new OAuth2Authentication. However we may not want the Administration webapp to be concerned with OAuth at this point (at least not yet). If possible we'd like to keep the administration app concerns as concise as possible, and right now there are no dependencies on oauth.

We could expose the DELETE method to the /oauth/access_token endpoint and tell the mobile app to try deleting that access token and re-requesting one, just in case the stored authorities are stale. This feels more like a work-around though.

Finally I can serialize the authorities in my own defined AuthenticationKeyGenerator. It would basically use the username, client_id, scope, and authorities of the authorization and perform the same digest algorithm on them. This way when Bob tries to log in he'll get the same access token, but the underlying token store will recognize that he has a different authentication (from the authentication manager in the token granter bean) and refresh its database. The problem I have with this solution is that it simply relies on the implementation behavior of the underlying token store (though both InMemoryTokenStore and JdbcTokenStore behave this way).

Can you think of any better/cleaner solutions? Am I over-thinking this?

Thanks in advance.

答:
I had the same problem and I solved it with this function:

```<code>protected void reloadUserFromSecurityContext(SecurityContext securityContext, Person user){
    OAuth2Authentication requestingUser = (OAuth2Authentication) securityContext.getUserPrincipal();
    Object principal = (PersonUserDetails) requestingUser.getUserAuthentication().getPrincipal();
    if(principal instanceof PersonUserDetails) {
        ((PersonUserDetails) principal).setPerson(user);
    }
    OAuth2AuthenticationDetails authDetails = (OAuth2AuthenticationDetails) requestingUser.getDetails();
    OAuth2AccessToken tokenStored = jdbcTokenStore.readAccessToken(authDetails.getTokenValue());
    jdbcTokenStore.storeAccessToken(tokenStored, requestingUser);
}
</code>```

That is a example for update an attribute for PersonUserDetails object that is in OAuth2Authentication

Body:
I had the same problem and I solved it with this function:

protected void reloadUserFromSecurityContext(SecurityContext securityContext, Person user){
    OAuth2Authentication requestingUser = (OAuth2Authentication) securityContext.getUserPrincipal();
    Object principal = (PersonUserDetails) requestingUser.getUserAuthentication().getPrincipal();
    if(principal instanceof PersonUserDetails) {
        ((PersonUserDetails) principal).setPerson(user);
    }
    OAuth2AuthenticationDetails authDetails = (OAuth2AuthenticationDetails) requestingUser.getDetails();
    OAuth2AccessToken tokenStored = jdbcTokenStore.readAccessToken(authDetails.getTokenValue());
    jdbcTokenStore.storeAccessToken(tokenStored, requestingUser);
}

That is a example for update an attribute for PersonUserDetails object that is in OAuth2Authentication


来源: stackexchange

问:
copy a descendant node and place it after the current node
In the below xml. I want to do following

match wrapper/item whose child or descendant is <olr>.

If found, copy <olr> and all its following-siblings, and paste it
after the current node i.e. end of wrapper/item. (other word,<olr> and its following-siblings will always be direct child of <wrapper>)

rest should be copied as it is.

Input XML:

```<code><root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
            <olr>outlier1</olr>
        </item>
    </item>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                    <olr>outlier2</olr>
                    <item>followingsibling1</item>
                    <item>followingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>
</code>```

```<code><root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
        </item>
    </item>
    <olr>outlier1</olr>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <olr>outlier2</olr>
    <item>followingsibling1</item>
    <item>followingsibling2</item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>
</code>```

I am trying something:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="item[descendant::olr]">
    <xsl:apply-templates select="node() except descendant::olr"/>
    <!-- ? not sure what to do here        -->
</xsl:template>
</code>```

答:
One way to achieve this is with

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="wrapper/item[descendant::olr]">
        <xsl:next-match/>
        <xsl:copy-of select="descendant::olr/(., following-sibling::node())"/>
    </xsl:template>

    <xsl:template match="wrapper/item//olr | wrapper/item//node()[preceding-sibling::olr]"/>
</xsl:transform>
</code>```

http://xsltransform.net/bFWR5Fg. I am not sure what happens if you have several olr elements.

ContentLicense: CC BY-SA 3.0

Body:
In the below xml. I want to do following

match wrapper/item whose child or descendant is <olr>.

If found, copy <olr> and all its following-siblings, and paste it
after the current node i.e. end of wrapper/item. (other word,<olr> and its following-siblings will always be direct child of <wrapper>)

rest should be copied as it is.

Input XML:

<root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
            <olr>outlier1</olr>
        </item>
    </item>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                    <olr>outlier2</olr>
                    <item>followingsibling1</item>
                    <item>followingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>

<root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
        </item>
    </item>
    <olr>outlier1</olr>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <olr>outlier2</olr>
    <item>followingsibling1</item>
    <item>followingsibling2</item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>

I am trying something:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="item[descendant::olr]">
    <xsl:apply-templates select="node() except descendant::olr"/>

</xsl:template>

Body:
One way to achieve this is with

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="wrapper/item[descendant::olr]">
        <xsl:next-match/>
        <xsl:copy-of select="descendant::olr/(., following-sibling::node())"/>
    </xsl:template>

    <xsl:template match="wrapper/item//olr | wrapper/item//node()[preceding-sibling::olr]"/>
</xsl:transform>

http://xsltransform.net/bFWR5Fg. I am not sure what happens if you have several olr elements.


问:
IntelliJ IDEA 13 extremely slow compilation
After setting up IntelliJ IDEA 13 with java 8 sdk for the first time i've noticed that the compilation process was extremely slow. Printing out a simple 'Hello world!' took exactly 3 minutes and 38 seconds. I have no idea what is causing it to be so slow. When i run the code in Netbeans for example it compiles and runs instantly. I've done some research and sought for solutions but other than removing plugins i wasn't able to find anything. Does anyone here have any idea what might cause this problem?</p>

答: Try to increase Build Process heap size.


问:
Return django validation errors in JSON format
Suppose I am building a registration/signup or any form in general for my web app in Django and I want the same form for Web/Android/IOS. So I want the frontend and backend(Django) to communicate via JSON. My question is how can I send validation errors in JSON format if the user on any platform(Web/Android/IOS) gives me invalid data like "the email already exists" type of errors?

I need the best way possible to handle this type of scenarios and well-detailed example/explanation will be much appreciated.

Thank You.

答:
The form's errors attribute has an as_json method you can use.

```<code>if form.is_valid():
    # process valid form
else:
    errors_json = form.errors.as_json()
    ...
</code>```

Note the warning in the docs about escaping the errors to avoid cross site scripting attacks.

Body:
The form's errors attribute has an as_json method you can use.

if form.is_valid():
    # process valid form
else:
    errors_json = form.errors.as_json()
    ...

Note the warning in the docs about escaping the errors to avoid cross site scripting attacks.


问:
Custom defined type for cv::Mat in OpenCV
I want to create an array using cv::Mat with my custom defined type. Here is my code:

```<code>typedef struct{
  int x;
  int y;
  float prob;
}CellXY;

void main(){

  cv::Mat_<CellXY> map(10, 10);

  std::cout << "Width = " << map.cols << ", Height = " << map.rows << std::endl;
  std::cout << "### Assignment ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      map.at<CellXY>(j, i).x = i;
      map.at<CellXY>(j, i).y = j;
      map.at<CellXY>(j, i).prob = (float)(i + j * map.cols);

      std::cout << map.at<CellXY>(j, i).prob
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl;
  }

  std::cout << "### Display ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      std::cout << map.at<CellXY>(j, i).prob
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl;
  }
  map.release();
}
</code>```

However results between "Assignment" and "Display" sections are not the same:

How do I make these results the same?

答:
This is becasue OpenCV doesn't know the DataType of your class. You need to a specialization for it, something like:

```<code>typedef struct {
    int x;
    int y;
    float prob;
}CellXY;

// Add this!!!!!!
namespace cv {
template<> class DataType<CellXY>
{
public:
    typedef CellXY      value_type;
    typedef value_type  work_type;
    typedef value_type  channel_type;
    typedef value_type  vec_type;
    enum { generic_type = 0,
        depth        = CV_32F, // Might cause problems... I'm saying it's all made of floats (and not 2 int a 1 float)
        channels     = 3,
        fmt          = (int)'p',
        type         = CV_MAKETYPE(depth, channels)
    };
};
}

void main() {
    ...
}
</code>```

But, in general, I think it's better to avoid messing up with these implementation details, and just use a better data structure. The recommendation is: use Mat only for primitive types. In fact, you can't use it in other OpenCV functions anyway...

Here a few ways to solve your problem:

Use another data structure: e.g. a std::vector<std::vector<CellXY>> or an "unrolled" std::vector<CellXY>

Make a class CellXYMatrix which deals with storing the CellXY:

```<code>class CellXYMatrix
{
     std::vector<CellXY> _mat; // your matrix of CellXY
     int _r; // rows
     int _c; // cols

public:
     CellXYMatrix(int rows, int cols) : _r(rows), _c(cols), _mat(rows * cols) {};

     void set(int row, int col, const CellXY& cell) {
        _mat[row * _c + col] = cell;
     }
     CellXY& get(int row, int col) {
        return _mat[row * _c + col];
     }
}
</code>```

You can eventually overload operator() to make the access similar to OpenCV Mats.

If the x and y fields in CellXY refer to the matrix position, why do you need them? You can simply have a Mat1f (aka Mat_<float>) for your probabilities, and x,y are the position in the matrix.

Body:
I want to create an array using cv::Mat with my custom defined type. Here is my code:

typedef struct{
  int x;
  int y;
  float prob;
}CellXY;

void main(){

  cv::Mat_<CellXY> map(10, 10);

  std::cout << "Width = " << map.cols << ", Height = " << map.rows << std::endl;
  std::cout << "### Assignment ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      map.at<CellXY>(j, i).x = i;
      map.at<CellXY>(j, i).y = j;
      map.at<CellXY>(j, i).prob = (float)(i + j * map.cols);

      std::cout << map.at<CellXY>(j, i).prob
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl;
  }

  std::cout << "### Display ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      std::cout << map.at<CellXY>(j, i).prob
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl;
  }
  map.release();
}

However results between "Assignment" and "Display" sections are not the same:

How do I make these results the same?

Body:
This is becasue OpenCV doesn't know the DataType of your class. You need to a specialization for it, something like:

typedef struct {
    int x;
    int y;
    float prob;
}CellXY;

// Add this!!!!!!
namespace cv {
template<> class DataType<CellXY>
{
public:
    typedef CellXY      value_type;
    typedef value_type  work_type;
    typedef value_type  channel_type;
    typedef value_type  vec_type;
    enum { generic_type = 0,
        depth        = CV_32F, // Might cause problems... I'm saying it's all made of floats (and not 2 int a 1 float)
        channels     = 3,
        fmt          = (int)'p',
        type         = CV_MAKETYPE(depth, channels)
    };
};
}

void main() {
    ...
}

But, in general, I think it's better to avoid messing up with these implementation details, and just use a better data structure. The recommendation is: use Mat only for primitive types. In fact, you can't use it in other OpenCV functions anyway...

Here a few ways to solve your problem:

Use another data structure: e.g. a std::vector<std::vector<CellXY>> or an "unrolled" std::vector<CellXY>

Make a class CellXYMatrix which deals with storing the CellXY:

class CellXYMatrix
{
     std::vector<CellXY> _mat; // your matrix of CellXY
     int _r; // rows
     int _c; // cols

public:
     CellXYMatrix(int rows, int cols) : _r(rows), _c(cols), _mat(rows * cols) {};

     void set(int row, int col, const CellXY& cell) {
        _mat[row * _c + col] = cell;
     }
     CellXY& get(int row, int col) {
        return _mat[row * _c + col];
     }
}

You can eventually overload operator() to make the access similar to OpenCV Mats.

If the x and y fields in CellXY refer to the matrix position, why do you need them? You can simply have a Mat1f (aka Mat_<float>) for your probabilities, and x,y are the position in the matrix.


问:
friend vs member functions in Operator Overloading C++
Previously I learnt about overloading Operators in C++ as member functions as well as friend functions of a class. Although, I know how to overload operators in C++ using both techniques. But I am still confused that ** which one is better** ? A member function or a friend function to overload operators, which one should i use and why?
 Please guide me ! Your response will be appreciated greatly. I shall be glad and thankful for your answers.</p>

答:
The choice isn't "member or friend" but "member or non-member".

(Friendship is frequently overused, and usually taught much too early in schools.)

This is because you can always add a public member function that a free function can call.

For instance:

```<code>class A
{
public:
    explicit A(int y) : x(y) {}
    A plus(const A& y) const { return A{x + y.x}; }
private:
    int x;
};

A operator+(const A& lhs, const A& rhs) { return lhs.plus(rhs); }
</code>```

As for how to choose: if the operator doesn't take an instance of the class as its left-hand operand, it must  be a free function, otherwise it's pretty much a matter of personal taste (or coding standards if you're not alone).

Example:

```<code>// Can't be a member because the int is on the left.
A operator+ (int x, const A& a) { return A{x} + a; }
</code>```

For operators that have a corresponding mutating operator (like + and  +=), it's common to do the mutating operator as a member and the other as a non-member:

```<code>class B
{
public:
    explicit B(int y) : x(y) {}
    B& operator+= (const B& y) { x += y.x; return *this; }
private:
    int x;
};

B operator+(B lhs, const B& rhs) { return lhs += rhs; }
</code>```

but you can spell this out too, of course:

```<code>class C
{
public:
    explicit C(int y) : x(y) {}
    C& add(const C& y) { x += y.x; return *this; }
private:
    int x;
};

C& operator+=(C& lhs, const C& rhs) { return lhs.add(rhs); }
C operator+(C lhs, const C& rhs) { return lhs += rhs; }
</code>```

Body:
The choice isn't "member or friend" but "member or non-member".

(Friendship is frequently overused, and usually taught much too early in schools.)

This is because you can always add a public member function that a free function can call.

For instance:

class A
{
public:
    explicit A(int y) : x(y) {}
    A plus(const A& y) const { return A{x + y.x}; }
private:
    int x;
};

A operator+(const A& lhs, const A& rhs) { return lhs.plus(rhs); }

As for how to choose: if the operator doesn't take an instance of the class as its left-hand operand, it must  be a free function, otherwise it's pretty much a matter of personal taste (or coding standards if you're not alone).

Example:

// Can't be a member because the int is on the left.
A operator+ (int x, const A& a) { return A{x} + a; }

For operators that have a corresponding mutating operator (like + and  +=), it's common to do the mutating operator as a member and the other as a non-member:

class B
{
public:
    explicit B(int y) : x(y) {}
    B& operator+= (const B& y) { x += y.x; return *this; }
private:
    int x;
};

B operator+(B lhs, const B& rhs) { return lhs += rhs; }

but you can spell this out too, of course:

class C
{
public:
    explicit C(int y) : x(y) {}
    C& add(const C& y) { x += y.x; return *this; }
private:
    int x;
};

C& operator+=(C& lhs, const C& rhs) { return lhs.add(rhs); }
C operator+(C lhs, const C& rhs) { return lhs += rhs; }


问:
What's the difference between a temporary #Stored procedure vs a phisical proc in terms of performance or execution plan?
main difference between those database objects</p>

答:
Temporary stored procedures are like normal stored procedures but, as their name suggests, have fleeting existence.

Since they are created in tempdb, they can be called from any database. SQL Server basically ignores database name and schema name in the case of temporary stored procedures.

Heavy use of temporary stored procedures can create contention on system tables in tempdb. But useful when connecting to earlier versions of SQL server that do not support reuse of execution plans for T-SQL statement or batches.

In terms of performance and execution plan, both normal and temporary stored procedures work the same way.

You can find more on this article.
Temporary Stored Procedures


问:
Error (in GTK?) when trying to install EclipseXul plugin
When installing EclipseXul plugin on EclipsePHP, it says:

Cannot complete the install because
  one or more required items could not
  be found.   Software currently
  installed: Shared profile
  1.0.0.1288098146566 (SharedProfile_epp.package.php
  1.0.0.1288098146566)   Missing requirement: Shared profile
  1.0.0.1288098146566 (SharedProfile_epp.package.php
  1.0.0.1288098146566) requires 'SharedProfile_epp.package.php
  [1.0.0.1288098145696]' but it could
  not be found

Any idea what's wrong?

--update

When running from the terminal, I can see a message, when I open the updates windows:

** (Eclipse:3364): CRITICAL **: murrine_style_draw_box: assertion
  `height >= -1' failed

Recently I have my whole home folder deleted by a script. Maybe there's something with this.. But I just downloaded a brand new Eclipse installation and put it in my /home/eclipse/ folder.

答: I got this same error in Win7 when I copied from the Eclipse .zip straight to Program Files.  Eclipse would run, but apparently didn't have write permissions.  Moving it somewhere else fixed it.</p>

ContentLicense: CC BY-SA 2.5


问:
how to take addition in json data
I need Addition of qty in + (sum of qty) +. What do I need to do?

```<code>[{"qty": "34"},{"qty": "5"}]
</code>```

$.ajax({
    url: "localhost/sp/text.json", //json link
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push("
");
            items.push("" + val.qty + 	");
            items.push("" + (sum of qty) + 	"); //need sum of qty here
            items.push("
");
        });
    }
});
```

答:
You need to calculate sum using other loop like :</p>

```<code>$.ajax({
url: "localhost/sp/text.json", //json link
dataType:'json',
success: function(data){
var items = [];

//count sum
var sumqty=0;
$.each(data,function(key,val){
sumqty=sumqty+parseInt(val.qty);
});
//

$.each(data,function(key,val){
items.push("<tr>");
items.push("<td id='" +key+ "'>" + val.qty+</td>");
items.push("<td id='" +key+ "'>" + sumqty +</td>"); //need sum of qty here
items.push("</tr>");
});}});
</code>```

Title: how to take addition in json data

Body:
I need Addition of qty in + (sum of qty) +. What do I need to do?

[{"qty": "34"},{"qty": "5"}]

$.ajax({
    url: "localhost/sp/text.json", //json link
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push("
");
            items.push("" + val.qty + 	");
            items.push("" + (sum of qty) + 	"); //need sum of qty here
            items.push("
");
        });
    }
});

Body:
You need to calculate sum using other loop like :

$.ajax({
url: "localhost/sp/text.json", //json link
dataType:'json',
success: function(data){
var items = [];

//count sum
var sumqty=0;
$.each(data,function(key,val){
sumqty=sumqty+parseInt(val.qty);
});
//

$.each(data,function(key,val){
items.push("<tr>");
items.push("<td id='" +key+ "'>" + val.qty+</td>");
items.push("<td id='" +key+ "'>" + sumqty +</td>"); //need sum of qty here
items.push("</tr>");
});}});


问:
TextWatcher warnings and slow type in android
I want to change on type a character in android. If user type space or - it will change it to _

So I tried:

```<code>TextWatcher tt = null;

final EditText etUsername = (EditText) findViewById(R.id.etUsername);
   tt = new TextWatcher() {
        public void afterTextChanged(Editable s){
            etUsername.setSelection(s.length());
        }
        public void beforeTextChanged(CharSequence s,int start,int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            etUsername.removeTextChangedListener(tt);
            etUsername.setText(etUsername.getText().toString().replace(" ", "_"));
            etUsername.setText(etUsername.getText().toString().replace("-", "_"));
            etUsername.addTextChangedListener(tt);
        }
    };
    etUsername.addTextChangedListener(tt);
</code>```

it "works" but if user types fast some letters will not appear and I got some warnings:

```<code>W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
</code>```

any ideas what is wrong?

答:
No need to remove and add text change listener again and again on text change, just put a condition to check if your editable is having "-" or " " then just replace and set it to EditText.</p>

```<code>etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && (s.toString().contains("-") || s.toString().contains(" "))) {
                    etUsername.setText(s.toString().replace("-", "_").replace(" ", "_"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                etUsername.setSelection(s.length());
            }
        });
</code>```

Body:
I want to change on type a character in android. If user type space or - it will change it to _

So I tried:

TextWatcher tt = null;

final EditText etUsername = (EditText) findViewById(R.id.etUsername);
   tt = new TextWatcher() {
        public void afterTextChanged(Editable s){
            etUsername.setSelection(s.length());
        }
        public void beforeTextChanged(CharSequence s,int start,int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            etUsername.removeTextChangedListener(tt);
            etUsername.setText(etUsername.getText().toString().replace(" ", "_"));
            etUsername.setText(etUsername.getText().toString().replace("-", "_"));
            etUsername.addTextChangedListener(tt);
        }
    };
    etUsername.addTextChangedListener(tt);

it "works" but if user types fast some letters will not appear and I got some warnings:

W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection

any ideas what is wrong?

Body:
No need to remove and add text change listener again and again on text change, just put a condition to check if your editable is having "-" or " " then just replace and set it to EditText.

etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && (s.toString().contains("-") || s.toString().contains(" "))) {
                    etUsername.setText(s.toString().replace("-", "_").replace(" ", "_"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                etUsername.setSelection(s.length());
            }
        });


问:
Making a simple C# API call
I'm trying to teach myself how to make simple API calls with C#. I'd like to call this "http://hivemc.com/json/userprofile/da10b68dea6a42d58ea8fea66a57b886". This should return some strings in json but I don't know what i'm supposed to do with that.

reference: https://apidoc.hivemc.com/#!/GameData/get_game_game_data_id_UUID

I'm new to programming and I've never done anything with API's. I've tried looking around the internet but I don't understand what I'm supposed to look for. Can someone refer me to an article that can teach me how to do this? I have no idea where to start. An example of the code with explanation would be great but I understand if it's too much to ask.

Thank you!

答:
You can start from the following.

```<code>using System;
using System.Net.Http;
using System.Threading.Tasks;

class Test
{
    public static void Do()
    {
        var result = GetGameData("da10b68dea6a42d58ea8fea66a57b886").Result;

        //TODO parse json here. For example, see http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c

        Console.WriteLine(result);
    }

    private static async Task<string> GetGameData(string id)
    {
        var url = "http://hivemc.com/json/userprofile/" + id;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);

            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string strResult = await response.Content.ReadAsStringAsync();

                return strResult;
            }
            else
            {
                return null;
            }
        }
    }
}
</code>```

Sample call

```<code>Test.Do();
</code>```

Title: Making a simple C# API call

Body:
You can start from the following.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Test
{
    public static void Do()
    {
        var result = GetGameData("da10b68dea6a42d58ea8fea66a57b886").Result;

        //TODO parse json here. For example, see http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c

        Console.WriteLine(result);
    }

    private static async Task<string> GetGameData(string id)
    {
        var url = "http://hivemc.com/json/userprofile/" + id;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);

            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string strResult = await response.Content.ReadAsStringAsync();

                return strResult;
            }
            else
            {
                return null;
            }
        }
    }
}

Sample call

Test.Do();


问:
CWinApp CFrameWindow not shown
i'm trying to create window using CFrameWindow, i used code from "Simulation for applied graph theory using Visual C++" but it didn't had entry point, so it doesn't work any way. So i simplified it as much as i could and now when application is launched in release mode window doesn't appear and in debug mode it throws error that assertion failed. I used MSVS Visual C++ -> General -> Empty project with "Use of MFC" set to Use MFC in a Shared DLL.

Here is the code :

```<code>#include <afxwin.h>

class MyWnd : public CFrameWnd
{
public:
    MyWnd()  { Create(0, "MyWnd"); }
    ~MyWnd() { }
};

class MyApp : public CWinApp
{
public:
    virtual BOOL InitInstance()
    {
        m_pMainWnd = new MyWnd;
        m_pMainWnd->ShowWindow(m_nCmdShow);
        return TRUE;
    }
};

int CALLBACK WinMain (_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    MyApp myApp;
    myApp.InitInstance();
    myApp.Run();
}
</code>```

EDIT: updated to call MyApp.Run(), but it still doesn't display anything, also checked Subsystem, none was selected, tried Console, Windows, Native, compiled only with Windows but didn't help.

答:
After InitInstance you should call CWinApp::Run in order to start message pumping.
Also, Run() blocks the WinMain function until it exits. Without Run(), your WinMain simply terminates before you see the window.</p>

Title: CWinApp CFrameWindow not shown

Body:
i'm trying to create window using CFrameWindow, i used code from "Simulation for applied graph theory using Visual C++" but it didn't had entry point, so it doesn't work any way. So i simplified it as much as i could and now when application is launched in release mode window doesn't appear and in debug mode it throws error that assertion failed. I used MSVS Visual C++ -> General -> Empty project with "Use of MFC" set to Use MFC in a Shared DLL.

Here is the code :

#include <afxwin.h>

class MyWnd : public CFrameWnd
{
public:
    MyWnd()  { Create(0, "MyWnd"); }
    ~MyWnd() { }
};

class MyApp : public CWinApp
{
public:
    virtual BOOL InitInstance()
    {
        m_pMainWnd = new MyWnd;
        m_pMainWnd->ShowWindow(m_nCmdShow);
        return TRUE;
    }
};

int CALLBACK WinMain (_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    MyApp myApp;
    myApp.InitInstance();
    myApp.Run();
}

EDIT: updated to call MyApp.Run(), but it still doesn't display anything, also checked Subsystem, none was selected, tried Console, Windows, Native, compiled only with Windows but didn't help.


答:
Use below query to get users returned in same month </p>

```<code>SELECT USER_ID
FROM #Table
GROUP BY USER_ID,(YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING COUNT(*) > 1
</code>```

Title: Users that returned

Body:
I have a table with [EVENT_DATE] and [USER_ID], I would like to know how to count the users who came back in the same month.

Table_01
-------------------------------------------
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

The answering being 2, because users 0006235012201 & 0006235012203 both came back within the same month.

EDIT: Sorry

I am looking to get the count by month.

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

This is what I have, but it isn't correct as it seems to be listing users.

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016. Compatibility level: SQL Server 2005 (90)

Body:
Use below query to get users returned in same month

SELECT USER_ID
FROM #Table
GROUP BY USER_ID,(YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING COUNT(*) > 1


问:
Ordered Value by Column / Row
Its a little difficult to explain. It might be easier to skip to the examples.

A table has an id and four columns that each allow null.

```<code>ID, Col1, Col2, Col3, Col4
</code>```

There are x number of rows. ( Usually less than 4 ) And only up to 4 distinct values will be used across the columns.

I am looking to return up to 4 rows, where each row in the resulting set is basically a column value where the value is selected left from right starting at the top preserving Col number. If another row has a value that is not column unique it is shifted to the next available column.

Examples:

If I have:

```<code>ID, Col1, Col2, Col3, Col4
0,  A   , B   ,     , C
1,      ,     , D   ,
</code>```

I would like to return

```<code>A
B
D
C
</code>```

and

```<code>ID, Col1, Col2, Col3, Col4
0,  A   , B   , D   ,
1,  C   ,     ,     ,
</code>```

Gives

```<code>A
B
D
C
</code>```

and

```<code>ID, Col1, Col2, Col3, Col4
0,  A   , B   , D   ,
1,  C   ,     ,     ,
2,  C   ,     ,     ,
</code>```

Gives

```<code>A
B
D
C
</code>```

Thanks!  The scenario when there are non unique columns and spaces between values can be thrown out.

This will not happen:

```<code>a,b,,d
c,,,
</code>```

This might help:

```<code>CREATE TABLE #original ( id int ,A INT, B INT, C INT, D INT );

INSERT INTO #original
--SELECT 0,1,2,null,4
--union
--select 1,null,null,3,null
--
--
--SELECT 0,1,2,3,null
--union
--select 1,4,null,null,null
--
--
SELECT 0,1,2,4,null
union
select 1,3,null,null,null
union
select 2,3,null,null,null

select * from #original order by id asc;

with cteOriginal as
(
    select *, RANK() over (partition by [SortOrder] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)

select [value] from
(
select top 50 [value], ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder]) sortedOrder
from cteOriginal
order by sortedOrder
) tmp
group by [value]
order by min(sortedOrder)

DROP TABLE #original
</code>```

答:
I may not understand everything that you described you wanted. From reading your problem and comments from others, I am guessing that this is what you are looking for:

Updated version:

```<code>with cteOriginal as
(
    select *, RANK() over (partition by [SortOrder] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)
select [value]
from cteOriginal
where id = (select MIN(tmp.id) from cteOriginal tmp where tmp.value = cteOriginal.value)
order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])
</code>```

I got rid of the duplicate values by picking the one with the smallest id, min(id). You can change it to use max(id).

Initial version:

```<code>with cteOriginal as
(
    select *, RANK() over (partition by [column] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 'A' as [Column], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 'B' as [Column], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 'C' as [Column], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 'D' as [Column], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)
select [value]
from cteOriginal
order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])
</code>```

By the way, I am using mssql 2005 for this query. Please comment and we'll refine it.

Title: Ordered Value by Column / Row

Body:
Its a little difficult to explain. It might be easier to skip to the examples.

A table has an id and four columns that each allow null.

ID, Col1, Col2, Col3, Col4

There are x number of rows. ( Usually less than 4 ) And only up to 4 distinct values will be used across the columns.

I am looking to return up to 4 rows, where each row in the resulting set is basically a column value where the value is selected left from right starting at the top preserving Col number. If another row has a value that is not column unique it is shifted to the next available column.

Examples:

If I have:

ID, Col1, Col2, Col3, Col4
0,  A   , B   ,     , C
1,      ,     , D   ,

I would like to return

A
B
D
C

and

ID, Col1, Col2, Col3, Col4
0,  A   , B   , D   ,
1,  C   ,     ,     ,

Gives

A
B
D
C

and

ID, Col1, Col2, Col3, Col4
0,  A   , B   , D   ,
1,  C   ,     ,     ,
2,  C   ,     ,     ,

Gives

A
B
D
C

Thanks!  The scenario when there are non unique columns and spaces between values can be thrown out.

This will not happen:

a,b,,d
c,,,

This might help:

CREATE TABLE #original ( id int ,A INT, B INT, C INT, D INT );

INSERT INTO #original
--SELECT 0,1,2,null,4
--union
--select 1,null,null,3,null
--
--
--SELECT 0,1,2,3,null
--union
--select 1,4,null,null,null
--
--
SELECT 0,1,2,4,null
union
select 1,3,null,null,null
union
select 2,3,null,null,null

select * from #original order by id asc;

with cteOriginal as
(
    select *, RANK() over (partition by [SortOrder] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)

select [value] from
(
select top 50 [value], ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder]) sortedOrder
from cteOriginal
order by sortedOrder
) tmp
group by [value]
order by min(sortedOrder)

DROP TABLE #original

Body:
I may not understand everything that you described you wanted. From reading your problem and comments from others, I am guessing that this is what you are looking for:

Updated version:

with cteOriginal as
(
    select *, RANK() over (partition by [SortOrder] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)
select [value]
from cteOriginal
where id = (select MIN(tmp.id) from cteOriginal tmp where tmp.value = cteOriginal.value)
order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])

I got rid of the duplicate values by picking the one with the smallest id, min(id). You can change it to use max(id).

Initial version:

with cteOriginal as
(
    select *, RANK() over (partition by [column] order by id asc) as [NonUniqueSortOrder]
    from
    (
        select id, A as [value], 'A' as [Column], 1 as [SortOrder]
        from #original
        where A is not null
        union all
        select id, B as [value], 'B' as [Column], 2 as [SortOrder]
        from #original
        where B is not null
        union all
        select id, C as [value], 'C' as [Column], 3 as [SortOrder]
        from #original
        where C is not null
        union all
        select id, D as [value], 'D' as [Column], 4 as [SortOrder]
        from #original
        where D is not null
    ) as temp
)
select [value]
from cteOriginal
order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])

By the way, I am using mssql 2005 for this query. Please comment and we'll refine it.


答:
you can do it with a query like this:

```<code>SELECT  CAST((
                CHAR_LENGTH('smilie_text This is the smilie_text search text ssmilie_text') -
               CHAR_LENGTH(REPLACE('smilie_text This is the smilie_text search text ssmilie_text','smilie_text',''))
            ) / CHAR_LENGTH('smilie_text') AS UNSIGNED );
</code>```

sample

```<code>mysql> SELECT  CAST((
    ->                 CHAR_LENGTH('smilie_text This is the smilie_text search text ssmilie_text') -
    ->                CHAR_LENGTH(REPLACE('smilie_text This is the smilie_text search text ssmilie_text','smilie_text',''))
    ->             ) / CHAR_LENGTH('smilie_text') AS UNSIGNED ) as result;
+--------+
| result |
+--------+
|      3 |
+--------+
1 row in set (0,00 sec)

mysql>
</code>```

Title: MySQL count usage of list of phrases in text field

Body:
Looking for a MySQL query that will enable me to count the usage of a list of phrases that may within a text column.

For example;

+--------------------+---------------------+------+-----+---------+
| Field              | Type                | Null | Key | Default |
+--------------------+---------------------+------+-----+---------+
| smilie_id          | int(10) unsigned    | NO   | PRI | NULL    |
| smilie_text        | text                | NO   |     | NULL    |

... and ...

+-------------------+---------------------------------------+------+-----+-------+
| Field             | Type                                  | Null | Key | Default
+-------------------+---------------------------------------+------+-----+-------+
| post_id           | int(10) unsigned                      | NO   | PRI | NULL
| message           | mediumtext                            | NO   |     | NULL

I want to count how many times smilie_text appears within message.

Thanks.

Body:
you can do it with a query like this:

SELECT  CAST((
                CHAR_LENGTH('smilie_text This is the smilie_text search text ssmilie_text') -
               CHAR_LENGTH(REPLACE('smilie_text This is the smilie_text search text ssmilie_text','smilie_text',''))
            ) / CHAR_LENGTH('smilie_text') AS UNSIGNED );

sample

mysql> SELECT  CAST((
    ->                 CHAR_LENGTH('smilie_text This is the smilie_text search text ssmilie_text') -
    ->                CHAR_LENGTH(REPLACE('smilie_text This is the smilie_text search text ssmilie_text','smilie_text',''))
    ->             ) / CHAR_LENGTH('smilie_text') AS UNSIGNED ) as result;
+--------+
| result |
+--------+
|      3 |
+--------+
1 row in set (0,00 sec)

mysql>


问:
jQuery checking if a link is clicked
I have created a burger menu using jQuery. And I have also created another jQuery function that automatically scrolls down the page to the anchor position when a link is clicked. Now what I need the burger menu function to do is close when one of the auto_close class links is clicked.

```<code><nav>
            <img class="logo_animated" src="images/popsies.svg">

            <ul id="height">
                <li class="auto_close"><a href="#welcomeAnchor">Welcome</a></li>
                <li class="auto_close"><a href="#menuAnchor">Menu</a></li>
                <li class="auto_close"><a href="#timesAnchor">Opening Times</a></li>
                <li id="mob_icons">
                    <a href=""><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>
                    <a href=""><i class="fa fa-twitter-square fa-2x" aria-hidden="true"></i></a>
                </li>
                <li class="mob_contact">Tel: 0113 0000000</li>
                <li class="mob_contact">Email: example@yahoo.co.uk</li>
            </ul>
        </nav>
</code>```

my burger menu function:

```<code>$(document).ready(function(){
$(".burger-button").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});
</code>```

答:
the simplest way, if your burger is always open, when one of your links is clicked.

```<code>$('.auto_close').click(function(){
    $(".burger-button").trigger('click')
})
</code>```

else if it isnt sure the burger is always open, just remove the classes

```<code>$('.auto_close').click(function(){
    $("nav").removeClass("show");
    $("body").removeClass("no_scroll");
});
</code>```

Title: jQuery checking if a link is clicked

Body:
I have created a burger menu using jQuery. And I have also created another jQuery function that automatically scrolls down the page to the anchor position when a link is clicked. Now what I need the burger menu function to do is close when one of the auto_close class links is clicked.

Welcome

Menu

Opening Times

Tel: 0113 0000000

Email: example@yahoo.co.uk

my burger menu function:

$(document).ready(function(){
$(".burger-button").click(function(){
    $("nav").toggleClass("show");
    $("body").toggleClass("no_scroll");
});
});

Body:
the simplest way, if your burger is always open, when one of your links is clicked.

$('.auto_close').click(function(){
    $(".burger-button").trigger('click')
})

else if it isnt sure the burger is always open, just remove the classes

$('.auto_close').click(function(){
    $("nav").removeClass("show");
    $("body").removeClass("no_scroll");
});


问:
How to check whether user has disable the downloadmanager
I use system's download manager to get files from server, but some user may disable the function of download manager in his/her mobile. So how can I check this situation in my app using program, then give tips to help user enable it? Thanks.

Here some sample code of my program:

```<code>private long downloadFile(Context context, String downloadUrl, String destFilename, boolean showNotify) {
    // ...

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl.trim()));
    request.setTitle(destFilename);
    request.setDestinationInExternalFilesDir(context, null, destFilename);
    request.setNotificationVisibility(showNotify ? DownloadManager.Request.VISIBILITY_VISIBLE :
            DownloadManager.Request.VISIBILITY_HIDDEN);

    // get the downloadManager
    mDownloadManager = (DownloadManager) getAppContext().getSystemService(Context.DOWNLOAD_SERVICE);

    long downloadId = mDownloadManager.enqueue(request);
    VLog.r(TAG, " downloadFile id : " + downloadId + " url : " + downloadUrl);
    downloadIds.put(downloadId, downloadUrl);

    return downloadId;
}
</code>```

答:
After reading the source code, I get a idea to check this situation. Since DownloadManager is realized based on ContentProvider, I try to get the "ContentProviderClient" of DownloadManager. If failed, it mean something wrong with the DownloadManager. Here the sample code.</p>

```<code>public static boolean isDownloadManagerEnable() {
    ContentProviderClient client = Util.getApplicationContext().getContentResolver().acquireContentProviderClient(Uri.parse("content://downloads/my_downloads").getAuthority());
    return client != null;
}
</code>```

Body:
I use system's download manager to get files from server, but some user may disable the function of download manager in his/her mobile. So how can I check this situation in my app using program, then give tips to help user enable it? Thanks.

Here some sample code of my program:

private long downloadFile(Context context, String downloadUrl, String destFilename, boolean showNotify) {
    // ...

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl.trim()));
    request.setTitle(destFilename);
    request.setDestinationInExternalFilesDir(context, null, destFilename);
    request.setNotificationVisibility(showNotify ? DownloadManager.Request.VISIBILITY_VISIBLE :
            DownloadManager.Request.VISIBILITY_HIDDEN);

    // get the downloadManager
    mDownloadManager = (DownloadManager) getAppContext().getSystemService(Context.DOWNLOAD_SERVICE);

    long downloadId = mDownloadManager.enqueue(request);
    VLog.r(TAG, " downloadFile id : " + downloadId + " url : " + downloadUrl);
    downloadIds.put(downloadId, downloadUrl);

    return downloadId;
}

Body:
After reading the source code, I get a idea to check this situation. Since DownloadManager is realized based on ContentProvider, I try to get the "ContentProviderClient" of DownloadManager. If failed, it mean something wrong with the DownloadManager. Here the sample code.

public static boolean isDownloadManagerEnable() {
    ContentProviderClient client = Util.getApplicationContext().getContentResolver().acquireContentProviderClient(Uri.parse("content://downloads/my_downloads").getAuthority());
    return client != null;
}


问:
Python Requests and persistent sessions
I am using the requests module.
I have figured out how to submit data to a login form on a website and retrieve the session key, but I can't see an obvious way to use this session key in subsequent requests.
Can someone fill in the ellipsis in the code below or suggest another approach?

```<code>>>> import requests
>>> login_data =  {'formPosted': '1', 'login_email': 'me@example.com', 'password': 'pw'}
>>> r = requests.post('https://localhost/login.py', login_data)
>>>
>>> r.text
'You are being redirected <a href="profilePage?_ck=1349394964">here</a>'
>>> r.cookies
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
>>>
>>> r2 = requests.get('https://localhost/profile_data.json', ...)
</code>```

答:
snippet to retrieve json data, password protected</p>

```<code>import requests

username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"

session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
                  data={
                      'username': username,
                      'password': password,
                      'csrfmiddlewaretoken': csrf_token,
                      'next': the_page_i_want,
                  },
                  headers=dict(Referer=url+"/login"))
print(resp.json())
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python Requests and persistent sessions

Body:
I am using the requests module.
I have figured out how to submit data to a login form on a website and retrieve the session key, but I can't see an obvious way to use this session key in subsequent requests.
Can someone fill in the ellipsis in the code below or suggest another approach?

>>> import requests
>>> login_data =  {'formPosted': '1', 'login_email': 'me@example.com', 'password': 'pw'}
>>> r = requests.post('https://localhost/login.py', login_data)
>>>
>>> r.text
'You are being redirected here'
>>> r.cookies
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
>>>
>>> r2 = requests.get('https://localhost/profile_data.json', ...)

Body:
snippet to retrieve json data, password protected

import requests

username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"

session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
                  data={
                      'username': username,
                      'password': password,
                      'csrfmiddlewaretoken': csrf_token,
                      'next': the_page_i_want,
                  },
                  headers=dict(Referer=url+"/login"))
print(resp.json())


问:
How to drop unique in MySQL?
```<code>Create Table: CREATE TABLE `fuinfo` (
  `fid` int(10) unsigned NOT NULL,
  `name` varchar(40) NOT NULL,
  `email` varchar(128) NOT NULL,
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `fid` (`fid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
</code>```

I want to drop the unique key on email,how?

答:
Try it to remove uique of a column:

```<code>ALTER TABLE  `0_ms_labdip_details` DROP INDEX column_tcx
</code>```

Run this code in phpmyadmin and remove unique of column

Title: How to drop unique in MySQL?

Body:
Create Table: CREATE TABLE `fuinfo` (
  `fid` int(10) unsigned NOT NULL,
  `name` varchar(40) NOT NULL,
  `email` varchar(128) NOT NULL,
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `fid` (`fid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

I want to drop the unique key on email,how?

Body:
Try it to remove uique of a column:

ALTER TABLE  `0_ms_labdip_details` DROP INDEX column_tcx

Run this code in phpmyadmin and remove unique of column


问:
How to Call Javascript method from a javascript file in the Iframe of aspx page?
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

```<code><script type="text/javascript">
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $(window).load(function () {
        var flgInsidePresentation = getParameterByName("flgInsidePresentation");
        if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
    });

</script>
</code>```

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

Please let me know if there is any other way. Thanks for the help in advance.

答:
Actually you are calling the method correctly. parent.MethodName should work

i think the problem is with " $(window).load(function (){})", it should be like window.onload = function () { //code here; }

```<code><script type="text/javascript">
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
}

 window.onload = function () {
    var flgInsidePresentation = getParameterByName("flgInsidePresentation");
    if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
};
</code>```

Also make sure that your updateButtons works without any error

Body:
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

Please let me know if there is any other way. Thanks for the help in advance.

Body:
Actually you are calling the method correctly. parent.MethodName should work

i think the problem is with " $(window).load(function (){})", it should be like window.onload = function () { //code here; }

<script type="text/javascript">
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
}

 window.onload = function () {
    var flgInsidePresentation = getParameterByName("flgInsidePresentation");
    if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
};

Also make sure that your updateButtons works without any error


问:
Transposing a pandas dataframe with multiple columns
I have a dataframe that currently looks like this:

```<code>import numpy as np
raw_data = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['Series_Date','SP','1M','3M'])
print df
</code>```

I would like to transponse in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column. That is the resulting Dataframe should look like this:

```<code>import numpy as np
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['Series_Date','Value','Desc'])
print df
</code>```

Could someone please help how I can flip and transpose my DataFrame this way?

答:
Use pd.melt to transform DF from a wide format to a long one:

```<code>idx = "Series_Date"              # identifier variable
pd.melt(df, id_vars=idx, var_name="Desc").sort_values(idx).reset_index(drop=True)
</code>```

Body:
I have a dataframe that currently looks like this:

import numpy as np
raw_data = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['Series_Date','SP','1M','3M'])
print df

I would like to transponse in a way such that all the value fields get transposed to the Value Column and the date is appended as a row item. The column name of the value field becomes a row for the Description column. That is the resulting Dataframe should look like this:

import numpy as np
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['Series_Date','Value','Desc'])
print df

Could someone please help how I can flip and transpose my DataFrame this way?

Body:
Use pd.melt to transform DF from a wide format to a long one:

idx = "Series_Date"              # identifier variable
pd.melt(df, id_vars=idx, var_name="Desc").sort_values(idx).reset_index(drop=True)


问:
XA error: XAResource.XAER_NOTA start() failed on resource 'SOADataSource_idm_domain': The XID is not valid
I came across "

Internal Exception: java.sql.SQLException: Unexpected exception  while
  enlisting XAConnection java.sql.SQLException:  XA error:
  XAResource.XAER_NOTA start() failed on resource
  'SOADataSource_idm_domain': The XID is not valid

" exception while analysing the soa request through em console.
Any idea about this exception,how do i fix it?

答:
Here is the Fix.

I had faced the issue twice.
For the first time when i encountered this issue,i had to increase the JTA timeout for the failing Data-source from default value to 1200(some greater value),i followed below steps,

```<code>1. Login to weblogic console
2. Goto Services > JTA
3. Open Configuration > JTA
4. Increase the "Timeout Seconds" value
</code>```

On restarting the managed servers,the issue was solved.
But,Second time(scenarios were different related to soa workflows/composite),the issue was very similar and its resolution was same as above,and that I have already tried.But below solution have saved my time :

```<code>1. Click DataSources under Service
2. Select the Datasource(you can pick the name from exception),in my case SOADataSource.
3. Go to Configuration > Transaction.
4. Check the checkbox "Set XA Transaction Timeout".
</code>```

Restart the servers targeted to run on this Datasource.

Body:
Here is the Fix.

I had faced the issue twice.
For the first time when i encountered this issue,i had to increase the JTA timeout for the failing Data-source from default value to 1200(some greater value),i followed below steps,

1. Login to weblogic console
2. Goto Services > JTA
3. Open Configuration > JTA
4. Increase the "Timeout Seconds" value

On restarting the managed servers,the issue was solved.
But,Second time(scenarios were different related to soa workflows/composite),the issue was very similar and its resolution was same as above,and that I have already tried.But below solution have saved my time :

1. Click DataSources under Service
2. Select the Datasource(you can pick the name from exception),in my case SOADataSource.
3. Go to Configuration > Transaction.
4. Check the checkbox "Set XA Transaction Timeout".

Restart the servers targeted to run on this Datasource.


问:
How to use swift in xamarin iOS
I am trying to make use of an swift based iOS Framework in xamarin.iOS

But after some research, I found that xamarin doesn't support swift language using Embedding Mono too.

How can I make use of Framework in Xamarin.iOS ?

答:
Binding Objective C based static library is officially supported in Xamarin.

But there is no official support for Swift based framework in Xamarin.iOS

You can import Swift based framework in Objective C based project and

you can expose the APIs using Objective C and you can convert that into .a static library then you can turn that static library into a binding library in xamarin studio and make use of that in xamarin

Try porting the Swift to C# and it should be faster as well

Title: How to use swift in xamarin iOS


问:
Java SecretKeyFactory not availale
I am trying to generate a private key with a password using a SecretKeyFactory and when I start the program I have a runtime exception that says algorithm not available. But in others PCs it works fine! Any help ?

```<code>private static void generatePrivateKey(String pwd) {

    try {
        PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
        SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
        PRIVATE_KEY = kf.generateSecret(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
}
</code>```

Runtime exception:

答:
There are multiple possibilities:

May be the JRE has been modified

An additional crypto provider has been installed. As you don't specify the provider in your ScretKeyFactory creation you don't know which provider is used. In Oracle JRE the algorithm you want is provided by the SunJCE. hence the following should work: SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128", "SunJCE");

Title: Java SecretKeyFactory not availale

Body:
I am trying to generate a private key with a password using a SecretKeyFactory and when I start the program I have a runtime exception that says algorithm not available. But in others PCs it works fine! Any help ?

private static void generatePrivateKey(String pwd) {

    try {
        PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
        SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
        PRIVATE_KEY = kf.generateSecret(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
}

Runtime exception:


问:
C# backgroundworker advice
I am having a backgroundworker issue - I am new to threading so I am trying to get this done as painlessly as possible.

My main issue is the end users will only have .NET 4.0 so I cannot use await / async and been told BGW is the best thing for the framework I am using.

I have a "Please Wait" form with a gif animation that I would like to load while the datagridview is being populated. I need to somehow do a check to make sure it has finished populating to close the "Please Wait" down but am a bit stuck on how to achieve this.

```<code>    public void btnSearch_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
        Application.DoEvents();
        try
        {
            this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));
            int RowC = TestDataTableDataGridView.RowCount;
            if (RowC == 0)
            {
                MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
        catch (System.Exception exc)
        {
            MessageBox.Show
                (
                "Problem" +
                exc.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Warning
                );
        }
        finally
        {
            //pleaseWait.Close();
        }
</code>```

This is my button to load the data in to my DataGridView. And so far this is my DoWork event

```<code>    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        pleaseWait.ShowDialog();
    }
</code>```

The finally will not work due to cross threading ( so comment out currently ) but I need to do a loop/check to find out if the DataGridView has been filled and action is complete to then close the DoWork. Or some how force it to jump to RunWorkerCompleted then I can just put a pleaseWait.Close(); in there instead.

Any suggestions please?

答:
You must show your pleaseWait dialog in your main ui thread,not in the backgroundWorker1.DoWork, and hide it in the RunWorkerCompleted event of the backgroundWorker1. Is the this.TestDataTableAdapter.Fill part the one that should go in the backgroundWorker1.DoWork, so your code should look more or less like this:

```<code>public void btnSearch_Click(object sender, EventArgs e)
{
    pleaseWait.ShowDialog();
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));

    }
    catch (System.Exception exc)
    {
        //You can't show a messagebox here,as it is not in the UI thread
    }
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    pleaseWait.Close();
    int RowC = TestDataTableDataGridView.RowCount;
    if (RowC == 0)
    {
            MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
}
</code>```

Of course, in this code you have a problem, as the TestDataTableAdapter.Fill code won't work because you are trying to access some TextBoxes and you can't from another thread.

You have several solutions to this. You could use some variables to read the values before calling the backgroundworker, and accessing this variables instead of the TextBoxes. Or you could call the backgroundworker with parameters.

I recommend you to read more about BackGroundWorker, for example in MSDN. Or this question about sending parameters to a BackgroundWorker.

Title: C# backgroundworker advice

Body:
I am having a backgroundworker issue - I am new to threading so I am trying to get this done as painlessly as possible.

My main issue is the end users will only have .NET 4.0 so I cannot use await / async and been told BGW is the best thing for the framework I am using.

I have a "Please Wait" form with a gif animation that I would like to load while the datagridview is being populated. I need to somehow do a check to make sure it has finished populating to close the "Please Wait" down but am a bit stuck on how to achieve this.

    public void btnSearch_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
        Application.DoEvents();
        try
        {
            this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));
            int RowC = TestDataTableDataGridView.RowCount;
            if (RowC == 0)
            {
                MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
        catch (System.Exception exc)
        {
            MessageBox.Show
                (
                "Problem" +
                exc.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Warning
                );
        }
        finally
        {
            //pleaseWait.Close();
        }

This is my button to load the data in to my DataGridView. And so far this is my DoWork event

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        pleaseWait.ShowDialog();
    }

The finally will not work due to cross threading ( so comment out currently ) but I need to do a loop/check to find out if the DataGridView has been filled and action is complete to then close the DoWork. Or some how force it to jump to RunWorkerCompleted then I can just put a pleaseWait.Close(); in there instead.

Any suggestions please?

Body:
You must show your pleaseWait dialog in your main ui thread,not in the backgroundWorker1.DoWork, and hide it in the RunWorkerCompleted event of the backgroundWorker1. Is the this.TestDataTableAdapter.Fill part the one that should go in the backgroundWorker1.DoWork, so your code should look more or less like this:

public void btnSearch_Click(object sender, EventArgs e)
{
    pleaseWait.ShowDialog();
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));

    }
    catch (System.Exception exc)
    {
        //You can't show a messagebox here,as it is not in the UI thread
    }
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    pleaseWait.Close();
    int RowC = TestDataTableDataGridView.RowCount;
    if (RowC == 0)
    {
            MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
}

Of course, in this code you have a problem, as the TestDataTableAdapter.Fill code won't work because you are trying to access some TextBoxes and you can't from another thread.

You have several solutions to this. You could use some variables to read the values before calling the backgroundworker, and accessing this variables instead of the TextBoxes. Or you could call the backgroundworker with parameters.

I recommend you to read more about BackGroundWorker, for example in MSDN. Or this question about sending parameters to a BackgroundWorker.


问:
Different resource folders for separate tablet & mobile APKs
I am building an app that has two APKs: one for tablets and the other for mobiles.

The tablet version won't use the drawable of the mobile APK and vice versa.

I want to do this because of APK size.

Can anyone give me pointers how to achieve this?

I tried to use flavors for this but it can make the two APK.

答:
You can use Android Flavors for this purpose.

```<code>android {
   ...
   defaultConfig {...}
   buildTypes {...}
   productFlavors {
       tablet {
           applicationIdSuffix ".tablet"
           versionNameSuffix "-tablet"
       }
       phone {
           applicationIdSuffix ".phone "
           versionNameSuffix "-phone "
       }
   }
</code>```

}

Each flavor will create separate build folders,where you can place resource files you wish to override. Here is an excellent tutorial:
Mastering "Product Flavors" on Android

Body:
You can use Android Flavors for this purpose.

android {
   ...
   defaultConfig {...}
   buildTypes {...}
   productFlavors {
       tablet {
           applicationIdSuffix ".tablet"
           versionNameSuffix "-tablet"
       }
       phone {
           applicationIdSuffix ".phone "
           versionNameSuffix "-phone "
       }
   }

}

Each flavor will create separate build folders,where you can place resource files you wish to override. Here is an excellent tutorial:
Mastering "Product Flavors" on Android


问:
Android screen AND audio record library
I need some way to record android screen AND audio. I have seen some libraries that record screen, but I need audio too. Does such a thing exists? Anybody knows any library to do that? I know something similar is available for iOS (ReplayKit), but seems that is not available for Android. Any alternative for Android?</p>

答:
You can try looking into https://github.com/saki4510t/ScreenRecordingSample.

It  does record the screen's video and audio from the microphone.

Title: Android screen AND audio record library


问:
How to mock external module method?
I have this module with a function in it:

```<code>const utils = {
  redirectTo(url) {
    if (url) {
      window.location = url;
    }
  },
};

export default utils;
</code>```

It is used somewhere in a React component like this:

```<code>import utils from '../../lib/utils';

componentWillUpdate() {
  this.redirectTo('foo')
}
</code>```

Now I want to check that the value that redirectTo is called with equals foo.

```<code>  it('should redirect if no rights', () => {
    const mockRedirectFn = jest.fn();
    utils.redirectTo = mockRedirectFn;

    mount(
      <SomeComponent />,
    );

    expect(mockRedirectFn).toBeCalled();
    expect(mockRedirectFn).toBeCalledWith('foo');
    console.log(mockRedirectFn.mock);
    // { calls: [], instances: [] }
  });
</code>```

Thats what I've got and it does not work. How do I do this?

答:
You have to mock the lib/utils module like this:

```<code>import utils from '../../lib/utils';
jest.mock('../../lib/utils', () => ({
  redirect: jest.fn()
}))

it('should redirect if no rights', () => {
  mount(
    <SomeComponent />,
  );
  expect(utils.redirect).toHaveBeenCalledWith();
});
</code>```

This will replace the module with a mock that just returns {redirect:jest.fn()}. This module is also imported into you test where you then can access the spy for redirect and test on this that it was called with the correct parameter.

Title: How to mock external module method?

Body:
I have this module with a function in it:

const utils = {
  redirectTo(url) {
    if (url) {
      window.location = url;
    }
  },
};

export default utils;

It is used somewhere in a React component like this:

import utils from '../../lib/utils';

componentWillUpdate() {
  this.redirectTo('foo')
}

Now I want to check that the value that redirectTo is called with equals foo.

  it('should redirect if no rights', () => {
    const mockRedirectFn = jest.fn();
    utils.redirectTo = mockRedirectFn;

    mount(
      <SomeComponent />,
    );

    expect(mockRedirectFn).toBeCalled();
    expect(mockRedirectFn).toBeCalledWith('foo');
    console.log(mockRedirectFn.mock);
    // { calls: [], instances: [] }
  });

Thats what I've got and it does not work. How do I do this?

Body:
You have to mock the lib/utils module like this:

import utils from '../../lib/utils';
jest.mock('../../lib/utils', () => ({
  redirect: jest.fn()
}))

it('should redirect if no rights', () => {
  mount(
    <SomeComponent />,
  );
  expect(utils.redirect).toHaveBeenCalledWith();
});

This will replace the module with a mock that just returns {redirect:jest.fn()}. This module is also imported into you test where you then can access the spy for redirect and test on this that it was called with the correct parameter.


问:
angularjs select nth child in ng option
I use this Jquery to select nth child

```<code><select class="perf-select">
    <option selected>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
</code>```

jquery

```<code>jQuery('.perf-select>option:eq(2)').prop('selected', true);
</code>```

How i achive this in angularjs ng-option

```<code><select class="perf-select" ng-model="viewProfileCtrl.graphsForm.institution"
                        ng-options="inst.institution.institution_id as inst.institution.name for inst in viewProfileCtrl.perfiosAnalysisData.institutions"
                        ng-change="viewProfileCtrl.setGraphInsti(viewProfileCtrl.graphsForm.institution)">
                        <option value=""  selected>Select a Bank </option>
                     </select>
</code>```

答:
If you want to set nth child as default option in dropdown you have to set your ng-model as per your nth child in the controller like--

$scope.graphsForm.institution=3;

Here "graphsForm.institution" is your dropdown model and "3" is the key (like your example "institution_id") of your nth child that you want to set as default.

You can check this for better understanding--

<!DOCTYPE html>

        <select class="perf-select" ng-model="graphsForm.institution"
   ng-options="inst.institution_id as inst.name for inst in institutions"
   ng-change="setGraphInsti(graphsForm.institution)">
   <option value="">Select Option </option>
  </select>

```

Title: angularjs select nth child in ng option

Body:
I use this Jquery to select nth child

<select class="perf-select">
    <option selected>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

jquery

jQuery('.perf-select>option:eq(2)').prop('selected', true);

How i achive this in angularjs ng-option

<select class="perf-select" ng-model="viewProfileCtrl.graphsForm.institution"
                        ng-options="inst.institution.institution_id as inst.institution.name for inst in viewProfileCtrl.perfiosAnalysisData.institutions"
                        ng-change="viewProfileCtrl.setGraphInsti(viewProfileCtrl.graphsForm.institution)">
                        <option value=""  selected>Select a Bank </option>
                     </select>

Body:
If you want to set nth child as default option in dropdown you have to set your ng-model as per your nth child in the controller like--

$scope.graphsForm.institution=3;

Here "graphsForm.institution" is your dropdown model and "3" is the key (like your example "institution_id") of your nth child that you want to set as default.

You can check this for better understanding--

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="datCtrl">

        <select class="perf-select" ng-model="graphsForm.institution"
   ng-options="inst.institution_id as inst.name for inst in institutions"
   ng-change="setGraphInsti(graphsForm.institution)">
   <option value="">Select Option </option>
  </select>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('datCtrl', function ($scope) {
   $scope.graphsForm={};
   $scope.graphsForm.institution=3;
            $scope.institutions=[{institution_id:1,name:"oxford"},{institution_id:2,name:"havard"},{institution_id:3,name:"cambrige"}];
        });
    </script>

</body>

</html>


问:
UIImage as Representation but no file extension
I want to convert an image to either

```<code>UIImagePNGRepresentation
UIImageJPEGRepresentation
</code>```

however I do not know the file type. I've just got a URL with no extension. Is there anyway to save the image from the URL to the filesystem?

```<code>// got the data from the URL

let imageData = UIImage(data: data!)

// now I want to write to the filesystem but only way was with a representation as UIImage has no write

if let saveImageData = UIImageXXXXXXRepresentation(imageData!) {
try saveImageData.write(to: URL(fileURLWithPath: localFilename), options: [.atomic])
}
</code>```

答:
Use that method to check the extension of your image by using the NSData of your image.</p>

```<code>func contentTypeForImageData(data: NSData) -> String {
    var c: UInt8
    data.getBytes(c, length: 1)
    switch c {
        case 0xFF:
            return "image/jpeg"
        case 0x89:
            return "image/png"
        case 0x47:
            return "image/gif"
        case 0x49, 0x4D:
            return "image/tiff"
    }

    return nil
}
</code>```

Body:
I want to convert an image to either

UIImagePNGRepresentation
UIImageJPEGRepresentation

however I do not know the file type. I've just got a URL with no extension. Is there anyway to save the image from the URL to the filesystem?

// got the data from the URL

let imageData = UIImage(data: data!)

// now I want to write to the filesystem but only way was with a representation as UIImage has no write

if let saveImageData = UIImageXXXXXXRepresentation(imageData!) {
try saveImageData.write(to: URL(fileURLWithPath: localFilename), options: [.atomic])
}

Body:
Use that method to check the extension of your image by using the NSData of your image.

func contentTypeForImageData(data: NSData) -> String {
    var c: UInt8
    data.getBytes(c, length: 1)
    switch c {
        case 0xFF:
            return "image/jpeg"
        case 0x89:
            return "image/png"
        case 0x47:
            return "image/gif"
        case 0x49, 0x4D:
            return "image/tiff"
    }

    return nil
}