问:
Azure ADAL for Python - facing issue with acquire_token_with_username_password method
I am trying to retrieve access token using azure user id and password .
Initially I tried with the following python code block

```<code>import adal
context = adal.AuthenticationContext(AUTHORITY)
token = context.acquire_token_with_client_credentials(
    "https://management.azure.com/",
    CLIENT_ID,
    CLIENT_SECRET)
</code>```

This is returning the token without any issue .
I am following an example from https://github.com/AzureAD/azure-activedirectory-library-for-python for retrieving the token using username and password and the code block is the the following

```<code>token2 = context.acquire_token_with_username_password("https://management.azure.com/",USER_NAME,PASSWORD,CLIENT_ID)
</code>```

In this case ,no token is returned , instead following response is returned .

```<code>File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 145, in acquire_token_with_username_password
    return self._acquire_token(token_func)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 109, in _acquire_token
    return token_func(self)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 143, in token_func
    return token_request.get_token_with_username_password(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 286, in get_token_with_username_password
    token = self._get_token_username_password_federated(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 252, in _get_token_username_password_federated
    username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 211, in _perform_username_password_for_access_token_exchange
    username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 198, in _perform_wstrust_exchange
    result = wstrust.acquire_token(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\wstrust_request.py", line 160, in acquire_token
    raise AdalError(return_error_string, error_response)
adal.adal_error.AdalError: WS-Trust RST request returned http error: 500 and server response: <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><s:Header><a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/soap/fault</a:Action><o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><u:Timestamp u:Id="_0"><u:Created>2017-06-07T12:12:56.567Z</u:Created><u:Expires>2017-06-07T12:17:56.567Z</u:Expires></u:Timestamp></o:Security></s:Header><s:Body><s:Fault><s:Code><s:Value>s:Sender</s:Value><s:Subcode><s:Value xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:FailedAuthentication</s:Value></s:Subcode></s:Code><s:Reason><s:Text xml:lang="en-US">ID3242: The security token could not be authenticated or authorized.</s:Text></s:Reason></s:Fault></s:Body></s:Envelope>

Process finished with exit code 1
</code>```

If anybody has any idea on this, please let me know .

答:
According to the information of error stack, per my experience, due to the error comes from the method _get_token_username_password_federated and 500 error code for WS-Trust RST request, it seems that the user/password you used for acquiring token not created in the Azure AD of your app registed, but looks like that created in a federated AD.

Please try to do the two ways below for inspection the issue.

Create a new user in the Azure AD of your app registed on Azure portal with your admin accout, then use the new user/password for retrieving the token.

Inspect your Azure AD configuration to make sure whether deployed Active Directory Federation Services and the current use/password created in a federated AD instance.

Body:
I am trying to retrieve access token using azure user id and password .
Initially I tried with the following python code block

import adal
context = adal.AuthenticationContext(AUTHORITY)
token = context.acquire_token_with_client_credentials(
    "https://management.azure.com/",
    CLIENT_ID,
    CLIENT_SECRET)

This is returning the token without any issue .
I am following an example from https://github.com/AzureAD/azure-activedirectory-library-for-python for retrieving the token using username and password and the code block is the the following

token2 = context.acquire_token_with_username_password("https://management.azure.com/",USER_NAME,PASSWORD,CLIENT_ID)

In this case ,no token is returned , instead following response is returned .

File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 145, in acquire_token_with_username_password
    return self._acquire_token(token_func)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 109, in _acquire_token
    return token_func(self)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\authentication_context.py", line 143, in token_func
    return token_request.get_token_with_username_password(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 286, in get_token_with_username_password
    token = self._get_token_username_password_federated(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 252, in _get_token_username_password_federated
    username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 211, in _perform_username_password_for_access_token_exchange
    username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\token_request.py", line 198, in _perform_wstrust_exchange
    result = wstrust.acquire_token(username, password)
  File "F:\All_Python\Python_Setup\Python27\lib\site-packages\adal\wstrust_request.py", line 160, in acquire_token
    raise AdalError(return_error_string, error_response)
adal.adal_error.AdalError: WS-Trust RST request returned http error: 500 and server response: <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><s:Header>http://www.w3.org/2005/08/addressing/soap/fault<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">2017-06-07T12:12:56.567Z2017-06-07T12:17:56.567Z</o:Security></s:Header><s:Body><s:Fault><s:Code><s:Value>s:Sender</s:Value><s:Subcode><s:Value xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:FailedAuthentication</s:Value></s:Subcode></s:Code><s:Reason><s:Text xml:lang="en-US">ID3242: The security token could not be authenticated or authorized.</s:Text></s:Reason></s:Fault></s:Body></s:Envelope>

Process finished with exit code 1

If anybody has any idea on this, please let me know .


来源: stackexchange

问:
Dynamic formation of variable name in PHP?
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

```<code>foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));
</code>```

I think the logic is correct except that this portion of the code:

```<code>foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}
</code>```

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

答:
That is incorrect, you are right.
The variable name will always be $options_pool.
You can pass the keys as explode(':', $name) and later assign them.

By the way, your code at

```<code> foreach( $option_keys as $option_keys_value ) {
      $option_key_names[] = $option_keys_value;
 }
</code>```

Do you realize that it just copies $option_keys as $option_key_names just as if you had written $option_key_names = $option_keys; (in this code) ?

Maybe with a stack you could do this iteratively but with recursion it is just more natural, as you see here

```<code>function getVariableToWrite(&$reference, $nested_opts, $write) {
    if(empty($nested_ops)) // Base case
        return $reference = write;
    if(isset($reference[array_shift($nested_ops)]))
        return getVariableToWrite($reference, $nested_ops, $write);
    throw new Exception("The key does not exist..");
}
</code>```

And then just

```<code>foreach( $this->post_vars as $name => $value ) {
    // Your work over here until...
    $match_key = "fruit:mango:apple_mango";
    $option_keys = explode( ':', $match_key );

    getVariableToWrite($options_pool, $option_keys, $value);
}
</code>```

Will this do the work?

ContentLicense: CC BY-SA 2.5

Body:
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));

I think the logic is correct except that this portion of the code:

foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

Body:
That is incorrect, you are right.
The variable name will always be $options_pool.
You can pass the keys as explode(':', $name) and later assign them.

By the way, your code at

 foreach( $option_keys as $option_keys_value ) {
      $option_key_names[] = $option_keys_value;
 }

Do you realize that it just copies $option_keys as $option_key_names just as if you had written $option_key_names = $option_keys; (in this code) ?

Maybe with a stack you could do this iteratively but with recursion it is just more natural, as you see here

function getVariableToWrite(&$reference, $nested_opts, $write) {
    if(empty($nested_ops)) // Base case
        return $reference = write;
    if(isset($reference[array_shift($nested_ops)]))
        return getVariableToWrite($reference, $nested_ops, $write);
    throw new Exception("The key does not exist..");
}

And then just

foreach( $this->post_vars as $name => $value ) {
    // Your work over here until...
    $match_key = "fruit:mango:apple_mango";
    $option_keys = explode( ':', $match_key );

    getVariableToWrite($options_pool, $option_keys, $value);
}

Will this do the work?


问:
Is there any way to convert game assets into pixel art?
Now I am  learning game development with Unity Engine .. but the problem is .. I'm a programmer .. I have zero experience in art and how to create game assets .. I have these huge ideas and I really want to make games .. so I took a course to learn how to draw and design but it doesn't work for me .. there are a lot of assets and characters to buy .. but they are different from each other .. so I came up with this idea of buying the assets and change them into pixel form .. to make them similar .. so I can build a game with them ..

the question now .. Is there any way in Photoshop or any other programs to convert those assets to pixel art?

All this About 2D Game Assets .. and 2D Games

答:
Not really. I too am an indie game developer and suck at art. However now I have an Artist on my team. But when I didn't I did a few different things:

OpenGameArt.org
I love this place. People post art you can download and use. Lots of the work is also Free to use in commercial projects. Sometimes they even include the PSD file if you want to edit a little bit.

Simple games require simple art. A big part of the games I make are for mobile. In this I can make amazing games, and simple graphics. Like a colorful cube, or similar basic art.

People. I don't know if you're in school or are part of some community of sorts but often times there are many people who are good at these things but don't share it. Ask round and see if any one might wanna help on the side. Plus, more than one person means more that one brain.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Prevent Suggestion for Input Field in HTML in All browser
I have an HTML form Which Contains the Various Field.

Simply We all Know that every browser will show some suggestion for the input field.

Like an Email Input field. When you enter or click on that input it shows the previously entered email or any other values.
I have cleared and done all procedures for stopping that behavior.  But still, I get previously entered data in the input field. (as in shown in image)

So how do I remove that suggestion or previously entered data?
Or How do I prevent that automatic suggestion for the input field?

This is my HTML Sample Code for Input Field.

```<code><div class="form-group ">
    <div class="col-xs-12">
        <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email">
    </div>
</div>
</code>```

答:
See this

I have added the

autocomplete="off"

In  Your code. Try it.

```<code><div class="form-group ">
<div class="col-xs-12">
    <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email" autocomplete="off">
</div>
</div>
</code>```

Body:
I have an HTML form Which Contains the Various Field.

Simply We all Know that every browser will show some suggestion for the input field.

Like an Email Input field. When you enter or click on that input it shows the previously entered email or any other values.
I have cleared and done all procedures for stopping that behavior.  But still, I get previously entered data in the input field. (as in shown in image)

So how do I remove that suggestion or previously entered data?
Or How do I prevent that automatic suggestion for the input field?

This is my HTML Sample Code for Input Field.

        <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email">

Body:
See this

I have added the

autocomplete="off"

In  Your code. Try it.

<div class="form-group ">
<div class="col-xs-12">
    <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email" autocomplete="off">
</div>
</div>


问:
Unexpected End of Expression when used with @Html.Raw(Model)
I am trying to use AngularJs with ASP.NET MVC - this is my first attempt.

Index.html

```<code>@model string
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container" ng-init="courses = [{'name':'first'},{'name':'second'},{'name':'third'}]">
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="course in courses">
            <td>{{ course.name }}</td>
        </tr>
    </tbody>
</table>
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>

<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<script src="~/Scripts/angular.min.js"></script>
<title></title>
</head>
<body>
@RenderBody()
</body>
</html>
</code>```

Above works fine and grid is displayed with Name as header and first, second and third as 3 rows. So my next step is to use

```<code>courses = @Html.Raw(Json.Encode(Model))
</code>```

instead of

```<code>courses = [{'name':'first'},{'name':'second'},{'name':'third'}]
</code>```

CourseController.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace AngularJsMvc.Controllers
{
    public class CoursesController : Controller
    {
        // GET: Courses
        public ActionResult Index()
        {
            return View("Index", "", "[{'name':'first'},{'name':'second'},    {'name':'third'}]"); //This works fine when used with @Html.Raw(Model) in index.html
            //return View("Index", "", GetCourses()); //This doesn't work when used with with @Html.Raw(Model) in index.html
        }

        public string GetCourses()
        {
            var courses = new[]
            {
                new Course { Name = "First" },
                new Course { Name = "Second" },
                new Course { Name = "Third" }
            };
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            return JsonConvert.SerializeObject(courses, Formatting.None, settings);
        }
    }

    public class Course
    {
        public string Name { get; set; }
    }
}
</code>```

This works fine if I use

```<code>return View("Index", "", "[{'name':'first'},{'name':'second'},{'name':'third'}]");
</code>```

But if I use

```<code>return View("Index", "", GetCourses());
</code>```

Then, below is the error I get. Please help - I have been struggling for almost entire day yesterday. I tried with or without Json.Encode

```<code>angular.min.js:123 Error: [$parse:ueoe]
http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=courses%20%3D
at angular.min.js:6

"<div class="container" ng-init="courses = " [{\"name\":\"first\"},{\"name\":\"second\"},{\"name\":\"third\"}]""="">"
</code>```

答:
The following worked for me:

```<code><div class="container" ng-init="courses = @Newtonsoft.Json.JsonConvert.DeserializeObject(Model)">
</code>```

This also works:

```<code><div class="container" ng-init="courses = @HttpUtility.HtmlDecode(Model)">
</code>```

It's all about how angular treats the object it tries to parse and since you're passing an HTML decoded string it will treat as a string and therefore it won't be able to iterate threw it.

Body:
I am trying to use AngularJs with ASP.NET MVC - this is my first attempt.

Index.html

@model string
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

            Name

            {{ course.name }}

_Layout.cshtml

<!DOCTYPE html>

<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<title></title>

@RenderBody()

Above works fine and grid is displayed with Name as header and first, second and third as 3 rows. So my next step is to use

courses = @Html.Raw(Json.Encode(Model))

instead of

courses = [{'name':'first'},{'name':'second'},{'name':'third'}]

CourseController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace AngularJsMvc.Controllers
{
    public class CoursesController : Controller
    {
        // GET: Courses
        public ActionResult Index()
        {
            return View("Index", "", "[{'name':'first'},{'name':'second'},    {'name':'third'}]"); //This works fine when used with @Html.Raw(Model) in index.html
            //return View("Index", "", GetCourses()); //This doesn't work when used with with @Html.Raw(Model) in index.html
        }

        public string GetCourses()
        {
            var courses = new[]
            {
                new Course { Name = "First" },
                new Course { Name = "Second" },
                new Course { Name = "Third" }
            };
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            return JsonConvert.SerializeObject(courses, Formatting.None, settings);
        }
    }

    public class Course
    {
        public string Name { get; set; }
    }
}

This works fine if I use

return View("Index", "", "[{'name':'first'},{'name':'second'},{'name':'third'}]");

But if I use

return View("Index", "", GetCourses());

Then, below is the error I get. Please help - I have been struggling for almost entire day yesterday. I tried with or without Json.Encode

angular.min.js:123 Error: [$parse:ueoe]
http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=courses%20%3D
at angular.min.js:6

"
"

Body:
The following worked for me:

<div class="container" ng-init="courses = @Newtonsoft.Json.JsonConvert.DeserializeObject(Model)">

This also works:

<div class="container" ng-init="courses = @HttpUtility.HtmlDecode(Model)">

It's all about how angular treats the object it tries to parse and since you're passing an HTML decoded string it will treat as a string and therefore it won't be able to iterate threw it.


问:
validation does not work in popup form values in magento
I am using Ajax for sending data on controller. Here I use TinyMCE editer in my popup form and I need to validate it. But here validation does not work properly in Magento.</p>

答:
Yes you should clarify more on this.

By the way wherever you have put your form in popup give it an ID like  and in your form if you have text boxes then put class 'required-entry' in all required textboxes and you should have one submit button.

Then finally put this script after form :

```<code><script type="text/javascript">
//<![CDATA[
    var popupForm = new VarienForm('popupform', true);
//]]>
</script>
</code>```

See how it goes.

Body:
Yes you should clarify more on this.

By the way wherever you have put your form in popup give it an ID like  and in your form if you have text boxes then put class 'required-entry' in all required textboxes and you should have one submit button.

Then finally put this script after form :

<script type="text/javascript">
//<![CDATA[
    var popupForm = new VarienForm('popupform', true);
//]]>
</script>

See how it goes.


问:
ComboBox displays duplicate values
I want to the add the item of ComboBox. I has been successful in adding items but the ComboBox has duplicate items. Why?

This is my code:

```<code>Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub
</code>```

This is the result:

In my table:

答:
The first thing I would check is to make sure that you do not added two times

The second thing I would recomened to do it to:

```<code>cmbCode.Items.Clear()
</code>```

in the beginning of the function before adding the items

Title: ComboBox displays duplicate values

Body:
I want to the add the item of ComboBox. I has been successful in adding items but the ComboBox has duplicate items. Why?

This is my code:

Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub

This is the result:

In my table:

Body:
The first thing I would check is to make sure that you do not added two times

The second thing I would recomened to do it to:

cmbCode.Items.Clear()

in the beginning of the function before adding the items


问:
WPF: Equals(Control.background, SolidColorBrush) constantly false
I have a List<SolidColorBrush> lColorBrushes and want to compare the Background of some Buttons with it's content. The Buttons are saved in List<Button> lClickedButtons.

```<code>            foreach (var oBtn in lClickedButtons)
            {
                for (var i = 0; i < lColorBrushes.Count; i++)
                {
                    if (Equals(oBtn.Background, lColorBrushes[i]))
                    {
                        //oBtn gets cool stuff
                    }
                }
            }
</code>```

I did the exact same thing earlier and it worked tottaly fine. But for whatever reason (I dont see any difference to earlier circumstances of my Code) now the if condition is constantly false. Also if for example oBtn.Background and lColorBrushes[i] both are #FFFF0000.

答:
The reason for Equals() returning false, is that these are two entirely different references, that just happen to have the same Color property.

If you want to compare the two SolidColorBrushes, I suggest you use the IEqualityComparer interface, as such: (source).

```<code>public class SolidColorBrushComparer : IEqualityComparer<SolidColorBrush>
{
    public bool Equals(SolidColorBrush x, SolidColorBrush y)
    {
        // If you do not care about opacity, disregard it.
        return x.Color == y.Color &&
            x.Opacity == y.Opacity;
    }

    public int GetHashCode(SolidColorBrush obj)
    {
        return new { C = obj.Color, O = obj.Opacity }.GetHashCode();
    }
}
</code>```

Then, you can use it inside your loop as follows:

```<code>foreach (var oBtn in lClickedButtons)
            {
                for (var i = 0; i < lColorBrushes.Count; i++)
                {
                    if (new SoldiColorBrushComparer().Equals(oBtn.Background, lColorBrushes[i]))
                    {
                        //oBtn gets cool stuff
                    }
                }
            }
</code>```

Body:
I have a List<SolidColorBrush> lColorBrushes and want to compare the Background of some Buttons with it's content. The Buttons are saved in List<Button> lClickedButtons.

            foreach (var oBtn in lClickedButtons)
            {
                for (var i = 0; i < lColorBrushes.Count; i++)
                {
                    if (Equals(oBtn.Background, lColorBrushes[i]))
                    {
                        //oBtn gets cool stuff
                    }
                }
            }

I did the exact same thing earlier and it worked tottaly fine. But for whatever reason (I dont see any difference to earlier circumstances of my Code) now the if condition is constantly false. Also if for example oBtn.Background and lColorBrushes[i] both are #FFFF0000.

Body:
The reason for Equals() returning false, is that these are two entirely different references, that just happen to have the same Color property.

If you want to compare the two SolidColorBrushes, I suggest you use the IEqualityComparer interface, as such: (source).

public class SolidColorBrushComparer : IEqualityComparer<SolidColorBrush>
{
    public bool Equals(SolidColorBrush x, SolidColorBrush y)
    {
        // If you do not care about opacity, disregard it.
        return x.Color == y.Color &&
            x.Opacity == y.Opacity;
    }

    public int GetHashCode(SolidColorBrush obj)
    {
        return new { C = obj.Color, O = obj.Opacity }.GetHashCode();
    }
}

Then, you can use it inside your loop as follows:

foreach (var oBtn in lClickedButtons)
            {
                for (var i = 0; i < lColorBrushes.Count; i++)
                {
                    if (new SoldiColorBrushComparer().Equals(oBtn.Background, lColorBrushes[i]))
                    {
                        //oBtn gets cool stuff
                    }
                }
            }


问:
Iterate over an array of Objects and get the key Angular 2
Hi I have a data structure as below:

```<code>list = [{id: "test", name: "name1"}, {id: "test1", name: "name2"}, ..]
</code>```

I want to display the keys (id and name) as th in my table. Since i didnt find any buitin pipes i created a custom one.

```<code>@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}
</code>```

But in my html, am getting only 0, 1 , 2, ... as keys. Any idea whats happening wrong here?

答:
Try something like this, I didn't tried but it should work. The problem is that u are iterating over the array, not over the object. And then, where u say "key" it is the index of the array so, that's why u are getting, "0, 1, 2".
Is your table like this?:

```<code>ID    NAME
id1   name1
id2   name2
...   ...
</code>```

Body:
Hi I have a data structure as below:

list = [{id: "test", name: "name1"}, {id: "test1", name: "name2"}, ..]

I want to display the keys (id and name) as th in my table. Since i didnt find any buitin pipes i created a custom one.

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

But in my html, am getting only 0, 1 , 2, ... as keys. Any idea whats happening wrong here?

Body:
Try something like this, I didn't tried but it should work. The problem is that u are iterating over the array, not over the object. And then, where u say "key" it is the index of the array so, that's why u are getting, "0, 1, 2".
Is your table like this?:

ID    NAME
id1   name1
id2   name2
...   ...


问:
jQuery update input field multiple times
I'm currently using the following to update an input field without reloading the entire page:

```<code><input type="number" name="voorraad" id="5258" class="voorraad 5258" value="129">

<script>
(function($) {
jQuery(document).ready(function(){
jQuery('.voorraad').blur(function(){

var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});
});
})(jQuery);
</script>
</code>```

However, after the second replace, the input field no longer works, and I need to refresh the entire page. What I am looking for, is that the script runs on each change I make to the input field. Any ideas?

答:
It seems this did the trick

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

jQuery( document ).on("blur", ".voorraad", function() {

var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});

})(jQuery);
</script>
</code>```

Found here: Calling a jQuery function multiple times

Body:
I'm currently using the following to update an input field without reloading the entire page:

<input type="number" name="voorraad" id="5258" class="voorraad 5258" value="129">

However, after the second replace, the input field no longer works, and I need to refresh the entire page. What I am looking for, is that the script runs on each change I make to the input field. Any ideas?

Body:
It seems this did the trick

<script>
(function($) {

jQuery( document ).on("blur", ".voorraad", function() {

var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});

})(jQuery);
</script>

Found here: Calling a jQuery function multiple times


问:
Need to generate a 2D python list with each column having 2 possibilities, for each row
I need to generate a two-dimensional python list. It would consist of 10 columns, with each column value being either '1' or '0'. Given these conditions, my list needs to be an exhaustive list of all the combinations that can be formed in this way. It'd naturally end up being 1024 rows long (2^10). However, I have no clue where to get started on this. Can anyone help?</p>

答:
You can use combinations from itertools module, that can create a list of tuples, not a list of lists:

```<code>from itertools import combinations
# Generate all the combinations of 0 and 1
# in a list of tuples where each tuple is formed by 10 elements
# Which leads to 184756 combinations
gen_list = combinations([0,1]*10, 10)
# remove duplicates
unique_elements = list(set(gen_list))
# len(unique_elements)
# >>> 1024
</code>```

An overview of the created list:

```<code>>>> unique_elements
[
(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
(0, 1, 0, 1, 0, 1, 0, 1, 0, 0)
...
(1, 1, 1, 0, 1, 0, 0, 1, 1, 1)
]
</code>```

Body:
You can use combinations from itertools module, that can create a list of tuples, not a list of lists:

from itertools import combinations
# Generate all the combinations of 0 and 1
# in a list of tuples where each tuple is formed by 10 elements
# Which leads to 184756 combinations
gen_list = combinations([0,1]*10, 10)
# remove duplicates
unique_elements = list(set(gen_list))
# len(unique_elements)
# >>> 1024

An overview of the created list:

>>> unique_elements
[
(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
(0, 1, 0, 1, 0, 1, 0, 1, 0, 0)
...
(1, 1, 1, 0, 1, 0, 0, 1, 1, 1)
]


问:
ngx-bootstrap typeahead with FormControl angular 2
here is a simple problem I can't find a solution to. I have a typeahead directive in input which lets a user to choose a category ( category array example -> [{ id: 1as1d, name: 'some category'},...]

How to set the id value to the FormControl field (which will appear in the submitted form) and display the name on the input (which will be showed in on the input while user is choosing)? Is there a way to separate what will be in the sent form and what is being showed while using FormControl?

I could only find a way to display and set the same variable either only id or only name.

```<code><input
    formControlName="category"
    [formControl]="userForm.controls['category']"
    [typeahead]="categoriesObservable"
    (typeaheadLoading)="toggleLoadingCategories($event)"
    (typeaheadNoResults)="toggleNoCategoriesFound($event)"
    (typeaheadOnBlur)="categoryFieldSelected($event)"
    (typeaheadOnSelect)="categoryFieldSelected($event)"
    typeaheadOptionsLimit="7"
    typeaheadOptionField="name"
    placeholder="Choose a category"
    class="form-control"/>
</code>```

答:
What you want to do is use a template for the options.

Taken from the documentation at http://valor-software.com/ngx-bootstrap/#/typeahead:

```<code><ng-template #customItemTemplate let-model="item" let-index="index">
   <h5>This is: {{model | json}} Index: {{ index }}</h5>
</ng-template>

<pre class="card card-block card-header">Model: {{selected | json}}```
<input [(ngModel)]="selected"
   [typeahead]="states"
   [typeaheadItemTemplate]="customItemTemplate"
   class="form-control">
```

In this example the customItemTemplate is used to display the model and index but any property of the model can be used. On selection the whole object of your selection can be sent, then in the function it is sent to you can take the id out of the object and use it for anything you need.

Body:
here is a simple problem I can't find a solution to. I have a typeahead directive in input which lets a user to choose a category ( category array example -> [{ id: 1as1d, name: 'some category'},...]

How to set the id value to the FormControl field (which will appear in the submitted form) and display the name on the input (which will be showed in on the input while user is choosing)? Is there a way to separate what will be in the sent form and what is being showed while using FormControl?

I could only find a way to display and set the same variable either only id or only name.

<input
    formControlName="category"
    [formControl]="userForm.controls['category']"
    [typeahead]="categoriesObservable"
    (typeaheadLoading)="toggleLoadingCategories($event)"
    (typeaheadNoResults)="toggleNoCategoriesFound($event)"
    (typeaheadOnBlur)="categoryFieldSelected($event)"
    (typeaheadOnSelect)="categoryFieldSelected($event)"
    typeaheadOptionsLimit="7"
    typeaheadOptionField="name"
    placeholder="Choose a category"
    class="form-control"/>

Body:
What you want to do is use a template for the options.

Taken from the documentation at http://valor-software.com/ngx-bootstrap/#/typeahead:

<ng-template #customItemTemplate let-model="item" let-index="index">
   <h5>This is: {{model | json}} Index: {{ index }}</h5>
</ng-template>

<pre class="card card-block card-header">Model: {{selected | json}}</pre>
<input [(ngModel)]="selected"
   [typeahead]="states"
   [typeaheadItemTemplate]="customItemTemplate"
   class="form-control">

In this example the customItemTemplate is used to display the model and index but any property of the model can be used. On selection the whole object of your selection can be sent, then in the function it is sent to you can take the id out of the object and use it for anything you need.


问:
Prevent a user from closing a browser window using "X"?
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

```<code>window.onunload = function() { alert("unloading"); }
</code>```

答:
If I understood correctly, your question is about a browser dialog, not the main browser window.

To answer your question, you probably cannot distinguish between the Cancel button and the X button of a browser dialog. They'll both end up just returning a false. If you need this level of control, you should consider writing your own simulated dialog (lightbox) instead of a real JavaScript dialog. Or perhaps look at existing frameworks/plugins with modal dialogs that give you the amount of control you need.

OwnerDisplayName: Pwninstein

Body:
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

window.onunload = function() { alert("unloading"); }

OwnerDisplayName: Ates Goral


问:
Mock device location on release mode
Is it possible to mock the device locatio in release mode?
When I am trying to put the permission:

```<code><uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
</code>```

It writes me an error:

```<code>Mock locations should only be requested in  test or a debug-specific manifest file.
</code>```

And I can't run the project.

Is it possible to do it in release mode?

答:
In AndroidManifest.xml you have to add:

xmlns:tools="http://schemas.android.com/tools" in header, then in tag permission MOCK_LCATION add tools:ignore="MockLocation"

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" >

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
        tools:ignore="MockLocation" />

//....
/>
</code>```

Title: Mock device location on release mode

Body:
Is it possible to mock the device locatio in release mode?
When I am trying to put the permission:

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

It writes me an error:

Mock locations should only be requested in  test or a debug-specific manifest file.

And I can't run the project.

Is it possible to do it in release mode?

Body:
In AndroidManifest.xml you have to add:

xmlns:tools="http://schemas.android.com/tools" in header, then in tag permission MOCK_LCATION add tools:ignore="MockLocation"

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" >

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
        tools:ignore="MockLocation" />

//....
/>


问:
Arduino format integer into 4 bytes for send to I2C
I have 2 arduinos that communicate as master / slave using I2C. The slave one have to send to the master one a value that is changing like a rpm value.
This rpm value can be from 0 to 9999 rpm.
I want to send this value from slave to master as 4 bytes message

```<code> Wire.write(rpm); // respond with message of 4 bytes
</code>```

How can i make sure that rpm will be always 4 bytes?

答:
You can use an array of chars to send a sequence of bytes. In Arduino int is 16 bit large. If you need to send always 4 bytes, a possible solution is to use masks to get the first 2 bytes and fill up the rest with zeros.</p>

```<code>void SendInt(int value)
{
    char values[4];
    values[0] = value & 0xff;
    values[1] = (value & 0xff00) >> 8;
    values[2] = 0;
    values[3] = 0;

    Wire.write(values, 4);
}
</code>```

Body:
I have 2 arduinos that communicate as master / slave using I2C. The slave one have to send to the master one a value that is changing like a rpm value.
This rpm value can be from 0 to 9999 rpm.
I want to send this value from slave to master as 4 bytes message

 Wire.write(rpm); // respond with message of 4 bytes

How can i make sure that rpm will be always 4 bytes?

Body:
You can use an array of chars to send a sequence of bytes. In Arduino int is 16 bit large. If you need to send always 4 bytes, a possible solution is to use masks to get the first 2 bytes and fill up the rest with zeros.

void SendInt(int value)
{
    char values[4];
    values[0] = value & 0xff;
    values[1] = (value & 0xff00) >> 8;
    values[2] = 0;
    values[3] = 0;

    Wire.write(values, 4);
}


问:
childViewController.view.frame in UIView present different value
I use childViewController to separate view in project, but some strange issue happened, here is my code.

```<code>class ViewController: UIViewController {

    var container = UIView()
    var childVC = ChildViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        addChildViewController(childVC)
        childVC.didMove(toParentViewController: self)

        addChildView()

        setContainerFrame()
    }

    func setContainerFrame() {
        container.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 100)
        container.backgroundColor = .red
        view.addSubview(container)
    }

    func addChildView() {
        let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        childVC.view.frame = frame
        childVC.view.backgroundColor = .green
        container.addSubview(childVC.view)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("childVC.view.frame: \(childVC.view.frame)")
    }
}

class ChildViewController: UIViewController {
}
</code>```

when I exchange the order invoking func addChildView() and func setContainerFrame() in ViewController's viewDidLoad(), xcode'console prints different frame log.

答:
This is due to the autoresizingMask of the childVC.view.  By default this is set to have flexible width and height.  So if you set the frame of the container and then the frame of the childVC.view then you get the actual value you set but if you reverse it and set the frame of the childVC.view and then the container the frame of the childVC.view is automatically updated to have the same relative width and height.

For example if the frame size for the container was 100 x 100 and then you change it to 200 x 200 the frame size for childVC.view will be doubled.

To remove this set the childVC.view.autoresizingMask = [] so it remains as you set it.

Body:
I use childViewController to separate view in project, but some strange issue happened, here is my code.

class ViewController: UIViewController {

    var container = UIView()
    var childVC = ChildViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        addChildViewController(childVC)
        childVC.didMove(toParentViewController: self)

        addChildView()

        setContainerFrame()
    }

    func setContainerFrame() {
        container.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 100)
        container.backgroundColor = .red
        view.addSubview(container)
    }

    func addChildView() {
        let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        childVC.view.frame = frame
        childVC.view.backgroundColor = .green
        container.addSubview(childVC.view)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("childVC.view.frame: \(childVC.view.frame)")
    }
}

class ChildViewController: UIViewController {
}

when I exchange the order invoking func addChildView() and func setContainerFrame() in ViewController's viewDidLoad(), xcode'console prints different frame log.


问:
How to create datasource with JNDI link (Wildfly)?
How I can connect to database with JTA and without persistence.xml, use only annotations?
And how create datasource with JNDI link ?

I have JNDI link from Wildfly_10 java:jboss/datasources/PostgreDataSource

persistence.xml snippet

```<code>    `<persistence-unit name="Unit1" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/PostgreDataSource</jta-data-source>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>`
</code>```

My config file:

```<code>@Configuration
@EnableTransactionManagement
@ComponentScan({ "net.myProg" })
@PropertySource(value = { "classpath:application.properties" })
@EnableJpaRepositories("net.myProg.repository")
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("net.myProg.model");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        //Lazy load initializayion. Hibernate сам открывает сессию для получения lazy объекта, если это нужно
        properties.put("hibernate.enable_lazy_load_no_trans", environment.getRequiredProperty("hibernate.enable_lazy_load_no_trans"));
//        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource());
        return db;
    }

}
</code>```

答:
Find answer here How to use JNDI DataSource provided by Tomcat in Spring?

@Configuration
public class MainConfig {

```<code>...

@Bean
DataSource dataSource() {
    DataSource dataSource = null;
    JndiTemplate jndi = new JndiTemplate();
    try {
        dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
    } catch (NamingException e) {
        logger.error("NamingException for java:comp/env/jdbc/yourname", e);
    }
    return dataSource;
}
</code>```

}

Body:
How I can connect to database with JTA and without persistence.xml, use only annotations?
And how create datasource with JNDI link ?

I have JNDI link from Wildfly_10 java:jboss/datasources/PostgreDataSource

persistence.xml snippet

    `<persistence-unit name="Unit1" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/PostgreDataSource</jta-data-source>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>`

My config file:

@Configuration
@EnableTransactionManagement
@ComponentScan({ "net.myProg" })
@PropertySource(value = { "classpath:application.properties" })
@EnableJpaRepositories("net.myProg.repository")
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("net.myProg.model");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        //Lazy load initializayion. Hibernate сам открывает сессию для получения lazy объекта, если это нужно
        properties.put("hibernate.enable_lazy_load_no_trans", environment.getRequiredProperty("hibernate.enable_lazy_load_no_trans"));
//        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource());
        return db;
    }

}

Body:
Find answer here How to use JNDI DataSource provided by Tomcat in Spring?

@Configuration
public class MainConfig {

...

@Bean
DataSource dataSource() {
    DataSource dataSource = null;
    JndiTemplate jndi = new JndiTemplate();
    try {
        dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
    } catch (NamingException e) {
        logger.error("NamingException for java:comp/env/jdbc/yourname", e);
    }
    return dataSource;
}

}


问:
pause and restart buttons are not work
I am using a javascript to start and stop a timer (stopwatch).  I want is that when the user press the stop button,
the data (the time at that moment) will be stored in my MySQL database.but my pause buttons are not work..

```<code>function stopwatch(text) {
   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();
   var s = d.getSeconds();
   var ms = d.getMilliseconds();
   document.stopwatchclock.stpwtch.value = +h + " : " + m + " : " + s + " : " + ms;

   SD = window.setTimeout("stopwatch();", 100);
   theResult = document.stopwatchclock.stpwtch.value;
 }

 function resetIt() {

   if (document.stopwatchclock.stopreset.value == "Pause") {
     stopResult = document.stopwatchclock.stpwtch.value;
     window.clearTimeout(stopResult);
   }
   if (document.stopwatchclock.stopreset.value == "Pause") {
     document.stopwatchclock.stopreset.value = "Restart";
   }
 }

center {
  width: 50%;
  margin-left: 25%;
}

.mainblock {
  background-color: #07c1cc;
}

.stopWatchClass {
  background-color: #07c1cc;
  display: block;
}

#stopwatchclock input {
  margin-bottom: 10px;
  width: 120px;
}
</code>```

    <title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>

Stopwatch Application

            <form name="stopwatchclock" id="stopwatchclock">
                <input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
                <input type="button" name="theButton" id="start" onClick="stopwatch();" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." />

                    <input type="button" name="stopreset" value="Pause" id="Pause" onClick="resetIt(this.value);" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />

            </form>

```

答:
Switch to:

```<code>window.clearTimeout(SD);
</code>```

instead of:

```<code>window.clearTimeout(stopResult);
</code>```

Title: pause and restart buttons are not work

Body:
I am using a javascript to start and stop a timer (stopwatch).  I want is that when the user press the stop button,
the data (the time at that moment) will be stored in my MySQL database.but my pause buttons are not work..

function stopwatch(text) {
   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();
   var s = d.getSeconds();
   var ms = d.getMilliseconds();
   document.stopwatchclock.stpwtch.value = +h + " : " + m + " : " + s + " : " + ms;

   SD = window.setTimeout("stopwatch();", 100);
   theResult = document.stopwatchclock.stpwtch.value;
 }

 function resetIt() {

   if (document.stopwatchclock.stopreset.value == "Pause") {
     stopResult = document.stopwatchclock.stpwtch.value;
     window.clearTimeout(stopResult);
   }
   if (document.stopwatchclock.stopreset.value == "Pause") {
     document.stopwatchclock.stopreset.value = "Restart";
   }
 }

center {
  width: 50%;
  margin-left: 25%;
}

.mainblock {
  background-color: #07c1cc;
}

.stopWatchClass {
  background-color: #07c1cc;
  display: block;
}

#stopwatchclock input {
  margin-bottom: 10px;
  width: 120px;
}

    <title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>

Stopwatch Application

            <form name="stopwatchclock" id="stopwatchclock">
                <input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
                <input type="button" name="theButton" id="start" onClick="stopwatch();" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." />

                    <input type="button" name="stopreset" value="Pause" id="Pause" onClick="resetIt(this.value);" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />

            </form>

Body:
Switch to:

window.clearTimeout(SD);

instead of:

window.clearTimeout(stopResult);


问:
Dynamically create and setup scenarios
I'd like to dynamically create and setUp gatling scenarios in a for loop to load test a webservice.

Therefore I tried the following (shortened):

```<code>class RecordedSimulation extends Simulation {

  val httpProtocol = http
    .baseURL("http://127.0.0.1")

  val overallUsers = 1000

  val methods: Map[String, Double] = Map(
    "FindContact" -> 0.6,
    "FindAddress" -> 0.3,
    "FindNumber" -> 0.1
  )

  for ((methodname, probability) <- methods) {
    val scen = scenario(methodname)
      .exec(http(methodname)
        .get("/contactservice")
        .queryParam("method", methodname))

    setUp(scen.inject(constantUsersPerSec(overallUsers * probability) during (60 seconds))).protocols(httpProtocol)
  }
}
</code>```

If I try running this simulation nothing happens: No simulation is started, also no error appears.

So my question is if it is even possible to dynamically create and setUp gatling scenarios. Am I missing something or doing something wrong?

Why do I want to do it dynamically anyway?

Well I have a lot of pretty similar methods to test and I'd like to avoid copy/pasting the same scenario over and over again.

答:
I found the problem myself. This gist got me in the right direction.

It seems you can call the setUp method only once. So I'm  putting my scenarios in an ArraySeq and calling setUp with this ArraySeq as a parameter:

```<code>import scala.collection.mutable.ArraySeq
import io.gatling.core.structure.PopulationBuilder

class RecordedSimulation extends Simulation {

  val httpProtocol = http
    .baseURL("http://127.0.0.1")

  val overallUsers = 1000

  val methods: Map[String, Double] = Map(
    "FindContact" -> 0.6,
    "FindAddress" -> 0.3,
    "FindNumber" -> 0.1
  )

  def scnList() = {
    var scnList = new ArraySeq[PopulationBuilder](methods.size)
    var i = 0
    for ((methodname, probability) <- methods) {
      var scen = scenario(methodname)
        .exec(http(methodname)
          .get("/contactservice")
          .queryParam("method", methodname))
        .inject(constantUsersPerSec(overallUsers * probability) during (60 seconds) randomized)

      scnList(i) = scen
      i = i + 1
    }
    scnList
  }

  setUp(scnList: _*).protocols(httpProtocol)
}
</code>```

Note: As discussed in the comments, ArraySeq is abstract in recent versions of Scala. As keylogger suggests, use an Array instead.

Title: Dynamically create and setup scenarios

Body:
I'd like to dynamically create and setUp gatling scenarios in a for loop to load test a webservice.

Therefore I tried the following (shortened):

class RecordedSimulation extends Simulation {

  val httpProtocol = http
    .baseURL("http://127.0.0.1")

  val overallUsers = 1000

  val methods: Map[String, Double] = Map(
    "FindContact" -> 0.6,
    "FindAddress" -> 0.3,
    "FindNumber" -> 0.1
  )

  for ((methodname, probability) <- methods) {
    val scen = scenario(methodname)
      .exec(http(methodname)
        .get("/contactservice")
        .queryParam("method", methodname))

    setUp(scen.inject(constantUsersPerSec(overallUsers * probability) during (60 seconds))).protocols(httpProtocol)
  }
}

If I try running this simulation nothing happens: No simulation is started, also no error appears.

So my question is if it is even possible to dynamically create and setUp gatling scenarios. Am I missing something or doing something wrong?

Why do I want to do it dynamically anyway?

Well I have a lot of pretty similar methods to test and I'd like to avoid copy/pasting the same scenario over and over again.

Body:
I found the problem myself. This gist got me in the right direction.

It seems you can call the setUp method only once. So I'm  putting my scenarios in an ArraySeq and calling setUp with this ArraySeq as a parameter:

import scala.collection.mutable.ArraySeq
import io.gatling.core.structure.PopulationBuilder

class RecordedSimulation extends Simulation {

  val httpProtocol = http
    .baseURL("http://127.0.0.1")

  val overallUsers = 1000

  val methods: Map[String, Double] = Map(
    "FindContact" -> 0.6,
    "FindAddress" -> 0.3,
    "FindNumber" -> 0.1
  )

  def scnList() = {
    var scnList = new ArraySeq[PopulationBuilder](methods.size)
    var i = 0
    for ((methodname, probability) <- methods) {
      var scen = scenario(methodname)
        .exec(http(methodname)
          .get("/contactservice")
          .queryParam("method", methodname))
        .inject(constantUsersPerSec(overallUsers * probability) during (60 seconds) randomized)

      scnList(i) = scen
      i = i + 1
    }
    scnList
  }

  setUp(scnList: _*).protocols(httpProtocol)
}

Note: As discussed in the comments, ArraySeq is abstract in recent versions of Scala. As keylogger suggests, use an Array instead.


问:
Entity Framework – Inserting into multiple tables using foreign key
I am a relative newby to EF and have created a simple model (see below) using EF4.

I am having a problem inserting a new record into the UserRecord entity and subsequently adding the UserDetail entity which uses the newly created UserRecordId as its primary key. The code shown below used to work when my database had a one-to-many relationship but when I change this to a one-to-one relationship I get the error highlighted in the image below.

I believe its not working as there is now no UserDetails property associated with the UserRecord because it’s  now a one-to-one relationship. My question is how do I now insert new UserRecord and corresponding UserDetail entities with a one-to-one relationship?

Any help on this one is much appreciated as have been on searching the web and trying a variety of different things without success.

Cheers

Cragly

答:
Your UserDetail object should have a property that links back to the UserRecord object. (It is maybe called User? If I'm reading the navigation section below correctly.) If you set that property to your new, uncommitted UserRecord object, it will automatically fill in the key when it commits both objects.

```<code>UserRecord userRecord = new UserRecord();
// whatever

UserDetail userDetail = new UserDetail();
userDetail.User = userRecord; // This will auto-fill the FK during commit.
// whatever

// Add both userRecord and userDetail to the context and commit.
</code>```

Body:
Your UserDetail object should have a property that links back to the UserRecord object. (It is maybe called User? If I'm reading the navigation section below correctly.) If you set that property to your new, uncommitted UserRecord object, it will automatically fill in the key when it commits both objects.

UserRecord userRecord = new UserRecord();
// whatever

UserDetail userDetail = new UserDetail();
userDetail.User = userRecord; // This will auto-fill the FK during commit.
// whatever

// Add both userRecord and userDetail to the context and commit.


问:
Trying to efficiently parallel process some data from a File Stream in .NET (read -and- write)
I'm trying to see how to efficiently read in some data from a file, do some parallel work (per line) then write the new line back to the file system.

I know I can do this, one line at a time .. but I was hoping to do this a few lines at a time -or- .. if one line is 'busy' waiting for the async work to complete, then move on to the next line, etc.

Here's some sample data and logic...

```<code>Header
SomeId#1, SomeId#2, SomeId#3, Name, Has this line been processed and cleaned(true/false)

File Data
444,2,12,Leia Organa, true
121,33333,4,Han Solo, true
1,2,3,Jane Doe, false
1,4,11,John Doe, false
</code>```

So the first 2 lines have been processed and I will skip those lines.
The 3rd and 4th line need to be processed. When the data has been checked, I wish to save this back to the file like

```<code>1,33333,3,Jane Doe, true
</code>```

So this is the general logic...

read line

call DoWorkAsync() <-- which could take a second or 5

save this line back to the file again.

I was just hoping that I didn't have to wait for the DoWorkAsync() to complete before I can save then read the next line. I was hoping that I could start reading the next line ... and if the previous line finishes .. fine .. then save that line to the same line number in the file .. and move on again to the next line.

It's like I could have 5 or 10 lines all working at the same time .. waiting for the results to come back from the 3rd party api ... working in parallel or whatever.

Can this be done in .NET? I'm sure .NET has the functionality for this .. I just can't see the pattern to do this.

NOTE: I usually do async/await for I/O intensive operations (like hitting the filesystem or calling some 3rd party api endpoint) vs Parallel.ForEach which I use for cpu intensive work.

NOTE: Why the true/false at the end of the line? Because I can't process all the lines at once. I have api limits.

Other ideas were to have two files, one for PENDING and one for PROCESSED.

答:
Here it is a stub of a parallel processor which uses async/await while processing lines in batches.

This approach ensures that the same order is preserved when writing.

```<code>public async Task ProcessFile()
{
    const int parallelism = 5;

    using (var readStream = File.OpenRead(@"c:\myinputfile"))
    {
        // put HERE your logic for skipping to a specific line
        // e.g. readStream.Seek(lastPosition);

        using (var reader = new StreamReader(readStream))
        {
            while (!reader.EndOfStream)
            {
                var tasks = new List<Task<string>>();

                for (var i = 0; i < parallelism; i++)
                {
                    var line = await reader.ReadLineAsync();

                    tasks.Add(DoWorkAsync(line));

                    if (reader.EndOfStream)
                        break;
                }

                var results = await Task.WhenAll(tasks);

                using (var writeStream = File.Open(@"d:\myresultfile", FileMode.Append))
                using (var writer = new StreamWriter(writeStream))
                {
                    foreach (var line in results)
                        await writer.WriteLineAsync(line);
                }
            }
        }
    }
}

public async Task<string> DoWorkAsync(string line)
{
    await Task.Delay(new Random().Next(1000, 5000));
    // do some work and return line with last parameter = true
    return line.Replace("false", "true"); // e.g.
}
</code>```

It surely needs improvement, but it should give you a good base for writing your own.

Body:
I'm trying to see how to efficiently read in some data from a file, do some parallel work (per line) then write the new line back to the file system.

I know I can do this, one line at a time .. but I was hoping to do this a few lines at a time -or- .. if one line is 'busy' waiting for the async work to complete, then move on to the next line, etc.

Here's some sample data and logic...

Header
SomeId#1, SomeId#2, SomeId#3, Name, Has this line been processed and cleaned(true/false)

File Data
444,2,12,Leia Organa, true
121,33333,4,Han Solo, true
1,2,3,Jane Doe, false
1,4,11,John Doe, false

So the first 2 lines have been processed and I will skip those lines.
The 3rd and 4th line need to be processed. When the data has been checked, I wish to save this back to the file like

1,33333,3,Jane Doe, true

So this is the general logic...

read line

call DoWorkAsync() <-- which could take a second or 5

save this line back to the file again.

I was just hoping that I didn't have to wait for the DoWorkAsync() to complete before I can save then read the next line. I was hoping that I could start reading the next line ... and if the previous line finishes .. fine .. then save that line to the same line number in the file .. and move on again to the next line.

It's like I could have 5 or 10 lines all working at the same time .. waiting for the results to come back from the 3rd party api ... working in parallel or whatever.

Can this be done in .NET? I'm sure .NET has the functionality for this .. I just can't see the pattern to do this.

NOTE: I usually do async/await for I/O intensive operations (like hitting the filesystem or calling some 3rd party api endpoint) vs Parallel.ForEach which I use for cpu intensive work.

NOTE: Why the true/false at the end of the line? Because I can't process all the lines at once. I have api limits.

Other ideas were to have two files, one for PENDING and one for PROCESSED.

Body:
Here it is a stub of a parallel processor which uses async/await while processing lines in batches.

This approach ensures that the same order is preserved when writing.

public async Task ProcessFile()
{
    const int parallelism = 5;

    using (var readStream = File.OpenRead(@"c:\myinputfile"))
    {
        // put HERE your logic for skipping to a specific line
        // e.g. readStream.Seek(lastPosition);

        using (var reader = new StreamReader(readStream))
        {
            while (!reader.EndOfStream)
            {
                var tasks = new List<Task<string>>();

                for (var i = 0; i < parallelism; i++)
                {
                    var line = await reader.ReadLineAsync();

                    tasks.Add(DoWorkAsync(line));

                    if (reader.EndOfStream)
                        break;
                }

                var results = await Task.WhenAll(tasks);

                using (var writeStream = File.Open(@"d:\myresultfile", FileMode.Append))
                using (var writer = new StreamWriter(writeStream))
                {
                    foreach (var line in results)
                        await writer.WriteLineAsync(line);
                }
            }
        }
    }
}

public async Task<string> DoWorkAsync(string line)
{
    await Task.Delay(new Random().Next(1000, 5000));
    // do some work and return line with last parameter = true
    return line.Replace("false", "true"); // e.g.
}

It surely needs improvement, but it should give you a good base for writing your own.


问:
What is the minimum version of Xcode required to test the app in test device (iOS 10.3.2)?
I am new to the iOS development world. I have an app in the app store and there is one issue in the app. The app was developed long ago (around 5 years ago) and some features of the app stopped running in the latest update (10.3.2). I need to fix the issue but I don't know what is the minimum Xcode and OS I have to install in my MacBook to move ahead. I expect some suggestions from you.</p>

答:
It would be better to use latest Xcode Version 8.3.2 and install the different iOS version simulators, which you want to test the app.

But first I would suggest you to test on device version(10.3.2).


问:
how to create a string like regex
i am new in C# language, i am trying to create a new desktop app.

but i am confuse to create a string like this..

```<code>private string getResult(int x){
    string results = "";

    return results
}
</code>```

so when i use getResult(1), it will return 0001

if i use getResults(111), it will return 0111

if i use getResults(10), it will return 0010.

something like this, i am confuse to create a string like this.

答:
An alternative to using a Regex and still get the same result: you can use PadLeft like this:

```<code>results.PadLeft(4, '0');
</code>```

So your entire method would look like:

```<code>private string getResult(int x)
{
    return x.ToString().PadLeft(4, '0');
}
</code>```

Title: how to create a string like regex

Body:
i am new in C# language, i am trying to create a new desktop app.

but i am confuse to create a string like this..

private string getResult(int x){
    string results = "";

    return results
}

so when i use getResult(1), it will return 0001

if i use getResults(111), it will return 0111

if i use getResults(10), it will return 0010.

something like this, i am confuse to create a string like this.

Body:
An alternative to using a Regex and still get the same result: you can use PadLeft like this:

results.PadLeft(4, '0');

So your entire method would look like:

private string getResult(int x)
{
    return x.ToString().PadLeft(4, '0');
}


问:
How to build a barcode reader in js with camera?
Im a beginer in js and jquery that's why i need your help . I would like to build a barcode reader in js thanks to the camera on my phone .
For the moment i do this :

  <video id="video" width="640" height="480" autoplay></video>
    <button id="snap">Snap Photo</button>
    <canvas id="canvas" width="640" height="480"></canvas>

答:
Why not using some libs, eg.

QuaggaJS

Some other reader


问:
ORA-01843 "not a valid month" and ORA-01861 "literal does not match format string"
```<code>SQL> select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dua
l;
select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dual
                    *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual;
select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual
               *
ERROR at line 1:
ORA-01861: literal does not match format string
</code>```

What is the correct way to do a

```<code>2010-12-14:09:56:53
minus
2010-12-14:09:56:46
</code>```

in Oracle SQL?

答:
Use to_timesatmp</p>

```<code>select TO_TIMESTAMP('2010-12-14:09:56:53',  'YYYY-MM-DD:HH24:MI:SS.FF')
 - TO_TIMESTAMP('2010-12-14:09:56:46',  'YYYY-MM-DD:HH24:MI:SS.FF')

from dual
</code>```

Body:
SQL> select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dua
l;
select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dual
                    *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual;
select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual
               *
ERROR at line 1:
ORA-01861: literal does not match format string

What is the correct way to do a

2010-12-14:09:56:53
minus
2010-12-14:09:56:46

in Oracle SQL?

Body:
Use to_timesatmp

select TO_TIMESTAMP('2010-12-14:09:56:53',  'YYYY-MM-DD:HH24:MI:SS.FF')
 - TO_TIMESTAMP('2010-12-14:09:56:46',  'YYYY-MM-DD:HH24:MI:SS.FF')

from dual


问:
Rider TFS integration
I'm attempting to setup an old project on a new computer using Rider with TFS. I'm already using TFS with the same repository on an old computer with Rider, however, I've noticed that on my new computer, TFS is no longer an option for version control. I have the plugin, I can go to version control under settings and view settings for TFS, but when I attempt to enable version control for the project, TFS is not an option. Similarly, I can't checkout from TFS.

Also, the settings screen for TFS is very different on my new computer's install, giving me only the options to delete and update configurations, but no way to add one (so I can't actually do anything). Any ideas about what's gone wrong here?

答:
Have tested installing riderRS-171.4456.199.exe (Windows), the TFS Integration plugin has been bundled with Rider and enabled VCS-TFVC successfully. Seems you are using TFVC version control(check out), please follow below requirements:

You must have the TF command line tool installed to be able to
  use TFVC features. The minimum version supported by the plugin is
  14.0.3. To install the tool, download the latest "TEE-CLC-14...zip" file and extract it to a known location. After extracting the files,
  you must accept the license agreement. To do so, open a Command
  Prompt/Terminal window, navigate to the extracted directory, and run
  tf eula. After reading the EULA, enter y enter code hereto accept
  it. NOTE: If you forget to do this, the plugin may fail to load
  with a RuntimeException.

For the tool to be detected by the plugin, you must set the location of the executable in the Settings/Preferences menu by following these instructions:

Go to RD Settings  Version Control -TFVC

In the Path to tf executable text field, navigate to the location of
    the tf executable.

Click Test to test that the executable has been found and is working
as expected.

Click Apply then OK to save and exit.

More details please refer this tutorial.

Also try to setup a new created project or select another project when you are  using Rider with TFS. To narrow down if the issue is related to that special project.

Title: Rider TFS integration


问:
Date format conversion issue PHP
See the below code returns the output as "Jun".

```<code>$date_removed =strtotime('2017-06-07 06:06:44');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
</code>```

But the below code returns "Dec" as output.

```<code>$date_removed =strtotime('0000-00-00 00:00:00');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
</code>```

Here the month value is null. So the return value should be null. Please let me know the issue in my code?

答:
```<code><?php

date_default_timezone_set("Canada/Central");
$date_removed = mktime(00, 00, 0000);

if($date_removed)
{
    $datev = date('Y/m/d',$date_removed);
    $nameOfMonth = date('M', strtotime($datev));
    echo $nameOfMonth;
}
else
    echo "invalid date"; //or whatever you want
?>
</code>```

Title: Date format conversion issue PHP

Body:
See the below code returns the output as "Jun".

$date_removed =strtotime('2017-06-07 06:06:44');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;

But the below code returns "Dec" as output.

$date_removed =strtotime('0000-00-00 00:00:00');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;

Here the month value is null. So the return value should be null. Please let me know the issue in my code?


问:
Scraping Google Patents with requests only returns style and scripts tags
I'm trying to scrape Google Patents using the following code.

```<code>    url = 'https://patents.google.com/?q=usb'
    r = requests.get(url)
    html_doc = r.text
    soup = BeautifulSoup(html_doc)
</code>```

But when I try to inspect the document, using

```<code>    print(soup.prettify)
</code>```

I cannot get anything other than this https://pastebin.com/Xu81LdfE .
I checked the requests status and it is returning 200. Where am I going wrong?

答:
The data is not in the HTML, but loaded with JavaScript.

Therefore, beautifulsoup cannot scrape it.

Consider using the official APIs, as other usage likely violates the Google terms of service, and they will likely block you then.

Body:
I'm trying to scrape Google Patents using the following code.

    url = 'https://patents.google.com/?q=usb'
    r = requests.get(url)
    html_doc = r.text
    soup = BeautifulSoup(html_doc)

But when I try to inspect the document, using

    print(soup.prettify)

I cannot get anything other than this https://pastebin.com/Xu81LdfE .
I checked the requests status and it is returning 200. Where am I going wrong?


问:
STM32F4 I2C without library
I have to wire a code for STM32F4 discovery and pcf8574 with I2C.

I can't use any library function. I try something I didn't do it. I did write after init code.

My init code

```<code>RCC->APB1ENR|=RCC_APB1ENR_I2C1EN ; // enable APB1 peripheral clock for I2C1
RCC->AHB1ENR|=RCC_AHB1ENR_GPIOBEN; // enable clock for SCL and SDA pins

//SCL on PB6 and SDA on PB7
GPIOB->MODER|=GPIO_MODER_MODER6; // set pin to alternate function
GPIOB->MODER|=GPIO_MODER_MODER7; // set pin to alternate function

GPIOB->OSPEEDR |=GPIO_OSPEEDER_OSPEEDR6; //set GPIO speed
GPIOB->OSPEEDR |=GPIO_OSPEEDER_OSPEEDR7; //set GPIO speed

GPIOB-> OTYPER |= GPIO_OTYPER_OT_6; // set output to open drain --> the line has to be only pulled low, not driven high
GPIOB-> OTYPER |= GPIO_OTYPER_OT_7; // set output to open drain --> the line has to be only pulled low, not driven high

GPIOB-> PUPDR  |=GPIO_PUPDR_PUPDR6_0; // enable pull up resistors
GPIOB-> PUPDR  |=GPIO_PUPDR_PUPDR7_0; // enable pull up resistors

GPIOB-> AFR[1] = 0x44000000; // Connect I2C1 pins to AF (af4)

// configure I2C1

I2C1-> CR2 = 8;  // set peripheral clock to 8mhz
I2C1-> CR2 = 40; // 100khz i2c clock
I2C1-> CR2 |= ~(I2C_CR1_SMBUS); // I2C mode
I2C1-> OAR2 = 0x00; // address not important
I2C1-> CR2 |= 1;    // i2c enable;
</code>```

答:
Hi I am having the same problem with setting an STM32F4 DISCO board to go

I noticed that you are setting

```<code>I2C1-> CR2 = 8;  // set peripheral clock to 8mhz
I2C1-> CR2 = 40; // 100khz i2c clock
</code>```

you are writing twice to the same register.
For the I2C clock you need to set I2C1->CCR to the calculated value

I hope this helps

Title: STM32F4 I2C without library

Body:
I have to wire a code for STM32F4 discovery and pcf8574 with I2C.

I can't use any library function. I try something I didn't do it. I did write after init code.

My init code

RCC->APB1ENR|=RCC_APB1ENR_I2C1EN ; // enable APB1 peripheral clock for I2C1
RCC->AHB1ENR|=RCC_AHB1ENR_GPIOBEN; // enable clock for SCL and SDA pins

//SCL on PB6 and SDA on PB7
GPIOB->MODER|=GPIO_MODER_MODER6; // set pin to alternate function
GPIOB->MODER|=GPIO_MODER_MODER7; // set pin to alternate function

GPIOB->OSPEEDR |=GPIO_OSPEEDER_OSPEEDR6; //set GPIO speed
GPIOB->OSPEEDR |=GPIO_OSPEEDER_OSPEEDR7; //set GPIO speed

GPIOB-> OTYPER |= GPIO_OTYPER_OT_6; // set output to open drain --> the line has to be only pulled low, not driven high
GPIOB-> OTYPER |= GPIO_OTYPER_OT_7; // set output to open drain --> the line has to be only pulled low, not driven high

GPIOB-> PUPDR  |=GPIO_PUPDR_PUPDR6_0; // enable pull up resistors
GPIOB-> PUPDR  |=GPIO_PUPDR_PUPDR7_0; // enable pull up resistors

GPIOB-> AFR[1] = 0x44000000; // Connect I2C1 pins to AF (af4)

// configure I2C1

I2C1-> CR2 = 8;  // set peripheral clock to 8mhz
I2C1-> CR2 = 40; // 100khz i2c clock
I2C1-> CR2 |= ~(I2C_CR1_SMBUS); // I2C mode
I2C1-> OAR2 = 0x00; // address not important
I2C1-> CR2 |= 1;    // i2c enable;

Body:
Hi I am having the same problem with setting an STM32F4 DISCO board to go

I noticed that you are setting

I2C1-> CR2 = 8;  // set peripheral clock to 8mhz
I2C1-> CR2 = 40; // 100khz i2c clock

you are writing twice to the same register.
For the I2C clock you need to set I2C1->CCR to the calculated value

I hope this helps


问:
Navigation bar odd behavior after giving it a fixed position in the css file
I made a navigation bar with a dropdown and was working fine until i added the "position: fixed;" statement in the css file. Once I did that the dropdown either isn't coming up when the mouse hovers over the designated button or is coming up off screen. Note the parent button reacts to the mouse hover fine in terms of color changes, that's why i think the dropdown is coming up off screen.

EDIT: i realized that the dropdown appears in the ul element and i can scroll within it to view the list. It's not appearing as an actual dropdown over the content on the page but within the navbar itself.

Here's my code:

ul.navbar {
  overflow-x: hidden;
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <ul class="navbar">
    <li id="navbar" style=" margin-left: 3%; width:22%">Home</li>
    <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
    <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; width: 21%; text-align: right">
      Jump to...
      <div class="dropdown-content">
        Item1
        Item2
      </div>
    </li>

  </ul>

</body></code>```

答:
Update css and remove the overflow to properties  ul.navbarfrom your css and add position:relative and remove width:21%; to below html

```<code><li id="navbar" class="dropdown" style="float: right; margin-right: 3%; text-align: right; position:relative;">
</code>```

css part

```<code>.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
  left:0px; /* Add this you can change it as your need */
}
</code>```

working fiddle

fiddle

ul.navbar {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: auto;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
  left:0px;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="navbar">
  <li id="navbar" style=" margin-left: 3%; width:22%">Home</li>
  <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
  <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; text-align: right; position:relative;">
    Jump to...
    <div class="dropdown-content">
      Item1
      Item2
    </div>
  </li>
</ul></code>```

Body:
I made a navigation bar with a dropdown and was working fine until i added the "position: fixed;" statement in the css file. Once I did that the dropdown either isn't coming up when the mouse hovers over the designated button or is coming up off screen. Note the parent button reacts to the mouse hover fine in terms of color changes, that's why i think the dropdown is coming up off screen.

EDIT: i realized that the dropdown appears in the ul element and i can scroll within it to view the list. It's not appearing as an actual dropdown over the content on the page but within the navbar itself.

Here's my code:

ul.navbar {
  overflow-x: hidden;
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

      Jump to...

        Item1
        Item2

Body:
Update css and remove the overflow to properties  ul.navbarfrom your css and add position:relative and remove width:21%; to below html

<li id="navbar" class="dropdown" style="float: right; margin-right: 3%; text-align: right; position:relative;">

css part

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
  left:0px; /* Add this you can change it as your need */
}

working fiddle

fiddle

ul.navbar {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: auto;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
  left:0px;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

<ul class="navbar">
  <li id="navbar" style=" margin-left: 3%; width:22%"><a href="homepage.php" class="dropbtn">Home</a></li>
  <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
  <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; text-align: right; position:relative;">
    <a href="javascript:void(0)" class="dropbtn">Jump to...</a>
    <div class="dropdown-content">
      <a href="#">Item1</a>
      <a href="#">Item2</a>
    </div>
  </li>
</ul>


问:
Java performance issue with Thread.sleep()
Inline Java IDE hint states, "Invoking Thread.sleep in loop can cause performance problems." I can find no elucidation elsewhere in the docs re. this statement.

Why? How? What other method might there be to delay execution of a thread?

答:
why? that is because of context switching (part of the OS CPU scheduling)

How? calling Thread.sleep(t) makes the current thread to be moved from the running queue to the waiting queue. After the time 't' reached the the current thread get moved from the waiting queue to the ready queue and then it takes some time to be picked by the CPU and be running.

Solution: call Thread.sleep(t*10); instead of calling Thread.Sleep(t) inside loop of 10 iterations ...


问:
Javascript variable checking: (null or undefined) vs boolean
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

```<code>(obj.x != null || obj.x != undefined)
</code>```

???

答:
I found an easy way in Underscore:

```<code>_.isBoolean(obj.x)
</code>```

Thanks to Rajesh I know now that obj.x != null returns the same if x is null or undefined.

I prefer the Underscore function because it's readable, but the null comparison is native JS and seems more efficient, and simpler.

Body:
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

(obj.x != null || obj.x != undefined)

???

Body:
I found an easy way in Underscore:

_.isBoolean(obj.x)

Thanks to Rajesh I know now that obj.x != null returns the same if x is null or undefined.

I prefer the Underscore function because it's readable, but the null comparison is native JS and seems more efficient, and simpler.