问:
Test Template with Robot Framework
I am attempting to utilize the Robot Framework Test Template function and have been experiencing a little difficulty.

My current Test consist of opening 5 different websites (declared as variables)

Here is my code:

```<code>*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
${URL1}
${URL2}
${URL3}
${URL4}
${URL5}

*** Keywords ***
Open URL
[Arguments]  ${URL}
Open Browser    $[URL]     Chrome
</code>```

When I run this code, 5 separate blank browser windows are opened.If there is a better way to do this, please let me know.
Thanks in advance for the help!

答:
you can use Execute Javascript Keyword like:</p>

```<code>*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
    Open URLs In New Tab   ${URL1}    ${URL2}    ${URL3}    ${URL4}    ${URL5}

*** Keywords ***
Open URLs In New Tab
    [Arguments]  @{URL}
    :FOR ${eachUrl}  IN  @{URL}
    \   Execute Javascript    window.open(${eachUrl},"_blank");
</code>```

Title: Test Template with Robot Framework

Body:
I am attempting to utilize the Robot Framework Test Template function and have been experiencing a little difficulty.

My current Test consist of opening 5 different websites (declared as variables)

Here is my code:

*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
${URL1}
${URL2}
${URL3}
${URL4}
${URL5}

*** Keywords ***
Open URL
[Arguments]  ${URL}
Open Browser    $[URL]     Chrome

When I run this code, 5 separate blank browser windows are opened.If there is a better way to do this, please let me know.
Thanks in advance for the help!

Body:
you can use Execute Javascript Keyword like:

*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
    Open URLs In New Tab   ${URL1}    ${URL2}    ${URL3}    ${URL4}    ${URL5}

*** Keywords ***
Open URLs In New Tab
    [Arguments]  @{URL}
    :FOR ${eachUrl}  IN  @{URL}
    \   Execute Javascript    window.open(${eachUrl},"_blank");


来源: stackexchange

问:
Parsing JSON for use with Highcharts using jquery .parseJSON or JSON.parse: how to remove quotes from function calls for formatters?
So I have a JSON string that contains the following piece for formatting an axis label in highcharts:

"labels":{"formatter":" function() { return Math.abs(this.value) + \u0027%\u0027; }"

When the string is converted to a javascript object using a json parser, the object property for label.formatter is a quoted string with the function call.  Highcharts then complains because the formatter is not a function, it's a string.  Trying to figure out how to remove the quotes so that it is an actual function call, not a string.  Hope this makes sense. Thanks in advance.

This is the entire string for reference:

```<code>"{"chart":{"animation":false,"backgroundColor":"rgba(255, 255, 255, 0.0)","type":"bar"},"credits":{"enabled":false},"xAxis":{"categories":["\u0027Alta \u0027","\u0027Gratr\u0027","\u0027IDV\u0027","\u0027BSV\u0027","\u0027Adhes\u0027"]},"yAxis":{"title":{"enabled":true},"labels":{"formatter":" function() { return Math.abs(this.value) + \u0027%\u0027; }"}},"legend":{"enabled":false},"exporting":{"enabled":false},"plotOptions":{"scatter":{"marker":{"radius":6}}},"series":[{"name":"\u0027Product\u0027","data":[{"y":69,"name":"\u0027() Alta All Cap Quality Growth\u0027"},{"y":17,"name":"\u0027() Gratry International Growth\u0027"},{"y":6,"name":"\u0027(IDV) iShares International Select Div ETF\u0027"},{"y":6,"name":"\u0027(BSV) Vanguard Short-Term Bond ETF\u0027"},{"y":2,"name":"\u0027() Adhesion Cash Model\u0027"}]}],"title":{"text":"Top 20 Allocations"}}"
</code>```

答:
You can use eval(). Note that this is a security hole.

The problem is that you are passing a function via JSON. JSON does not support this.

Btw, jquery.parseJSON() is deprecated, use JSON.parse()

Here's an example:

```<code>data = JSON.parse(x);
data.yAxis.labels.formatter = eval(data.yAxis.labels.formatter);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a JSON string that contains the following piece for formatting an axis label in highcharts:

"labels":{"formatter":" function() { return Math.abs(this.value) + \u0027%\u0027; }"

When the string is converted to a javascript object using a json parser, the object property for label.formatter is a quoted string with the function call.  Highcharts then complains because the formatter is not a function, it's a string.  Trying to figure out how to remove the quotes so that it is an actual function call, not a string.  Hope this makes sense. Thanks in advance.

This is the entire string for reference:

"{"chart":{"animation":false,"backgroundColor":"rgba(255, 255, 255, 0.0)","type":"bar"},"credits":{"enabled":false},"xAxis":{"categories":["\u0027Alta \u0027","\u0027Gratr\u0027","\u0027IDV\u0027","\u0027BSV\u0027","\u0027Adhes\u0027"]},"yAxis":{"title":{"enabled":true},"labels":{"formatter":" function() { return Math.abs(this.value) + \u0027%\u0027; }"}},"legend":{"enabled":false},"exporting":{"enabled":false},"plotOptions":{"scatter":{"marker":{"radius":6}}},"series":[{"name":"\u0027Product\u0027","data":[{"y":69,"name":"\u0027() Alta All Cap Quality Growth\u0027"},{"y":17,"name":"\u0027() Gratry International Growth\u0027"},{"y":6,"name":"\u0027(IDV) iShares International Select Div ETF\u0027"},{"y":6,"name":"\u0027(BSV) Vanguard Short-Term Bond ETF\u0027"},{"y":2,"name":"\u0027() Adhesion Cash Model\u0027"}]}],"title":{"text":"Top 20 Allocations"}}"

Body:
You can use eval(). Note that this is a security hole.

The problem is that you are passing a function via JSON. JSON does not support this.

Btw, jquery.parseJSON() is deprecated, use JSON.parse()

Here's an example:

data = JSON.parse(x);
data.yAxis.labels.formatter = eval(data.yAxis.labels.formatter);


问:
Get the week start date and week end date from week number
I have a query that counts member's wedding dates in the database.

```<code>SELECT
  SUM(NumberOfBrides) AS [Wedding Count]
  , DATEPART( wk, WeddingDate) AS [Week Number]
  , DATEPART( year, WeddingDate) AS [Year]
FROM  MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC
</code>```

How do I work out when the start and end of each week represented in the result set?

```<code>SELECT
  SUM(NumberOfBrides) AS [Wedding Count]
  , DATEPART(wk, WeddingDate) AS [Week Number]
  , DATEPART(year, WeddingDate) AS [Year]
  , ??? AS WeekStart
  , ??? AS WeekEnd
FROM  MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC
</code>```

答:
Let us break the problem down to two parts:

1) Determine the day of week

The DATEPART(dw, ...) returns a number, 1...7, relative to DATEFIRST setting (docs). The following table summarizes the possible values:

                                                   @@DATEFIRST
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+
|                                    |  1  |  2  |  3  |  4  |  5  |  6  |  7  | DOW |
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+
|  DATEPART(dw, /*Mon*/ '20010101')  |  1  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |
|  DATEPART(dw, /*Tue*/ '20010102')  |  2  |  1  |  7  |  6  |  5  |  4  |  3  |  2  |
|  DATEPART(dw, /*Wed*/ '20010103')  |  3  |  2  |  1  |  7  |  6  |  5  |  4  |  3  |
|  DATEPART(dw, /*Thu*/ '20010104')  |  4  |  3  |  2  |  1  |  7  |  6  |  5  |  4  |
|  DATEPART(dw, /*Fri*/ '20010105')  |  5  |  4  |  3  |  2  |  1  |  7  |  6  |  5  |
|  DATEPART(dw, /*Sat*/ '20010106')  |  6  |  5  |  4  |  3  |  2  |  1  |  7  |  6  |
|  DATEPART(dw, /*Sun*/ '20010107')  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  7  |
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+
```

<p>The last column contains the <em>ideal</em> day-of-week value for Monday to Sunday weeks*. By just looking at the chart we come up with the following equation:</p>

```(@@DATEFIRST + DATEPART(dw, SomeDate) - 1 - 1) % 7 + 1
```

<p><strong>2) Calculate the Monday and Sunday for given date</strong></p>

<p>This is trivial thanks to the day-of-week value. Here is an example:</p>

```WITH TestData(SomeDate) AS (
    SELECT CAST('20001225' AS DATETIME) UNION ALL
    SELECT CAST('20001226' AS DATETIME) UNION ALL
    SELECT CAST('20001227' AS DATETIME) UNION ALL
    SELECT CAST('20001228' AS DATETIME) UNION ALL
    SELECT CAST('20001229' AS DATETIME) UNION ALL
    SELECT CAST('20001230' AS DATETIME) UNION ALL
    SELECT CAST('20001231' AS DATETIME) UNION ALL
    SELECT CAST('20010101' AS DATETIME) UNION ALL
    SELECT CAST('20010102' AS DATETIME) UNION ALL
    SELECT CAST('20010103' AS DATETIME) UNION ALL
    SELECT CAST('20010104' AS DATETIME) UNION ALL
    SELECT CAST('20010105' AS DATETIME) UNION ALL
    SELECT CAST('20010106' AS DATETIME) UNION ALL
    SELECT CAST('20010107' AS DATETIME) UNION ALL
    SELECT CAST('20010108' AS DATETIME) UNION ALL
    SELECT CAST('20010109' AS DATETIME) UNION ALL
    SELECT CAST('20010110' AS DATETIME) UNION ALL
    SELECT CAST('20010111' AS DATETIME) UNION ALL
    SELECT CAST('20010112' AS DATETIME) UNION ALL
    SELECT CAST('20010113' AS DATETIME) UNION ALL
    SELECT CAST('20010114' AS DATETIME)
), TestDataPlusDOW AS (
    SELECT SomeDate, (@@DATEFIRST + DATEPART(dw, SomeDate) - 1 - 1) % 7 + 1 AS DOW
    FROM TestData
)
SELECT
    FORMAT(SomeDate,                            'ddd yyyy-MM-dd') AS SomeDate,
    FORMAT(DATEADD(dd, -DOW + 1, SomeDate),     'ddd yyyy-MM-dd') AS [Monday],
    FORMAT(DATEADD(dd, -DOW + 1 + 6, SomeDate), 'ddd yyyy-MM-dd') AS [Sunday]
FROM TestDataPlusDOW
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>+------------------+------------------+------------------+
|  SomeDate        |  Monday          |    Sunday        |
+------------------+------------------+------------------+
|  Mon 2000-12-25  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Tue 2000-12-26  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Wed 2000-12-27  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Thu 2000-12-28  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Fri 2000-12-29  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Sat 2000-12-30  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Sun 2000-12-31  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Mon 2001-01-01  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Tue 2001-01-02  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Wed 2001-01-03  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Thu 2001-01-04  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Fri 2001-01-05  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Sat 2001-01-06  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Sun 2001-01-07  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Mon 2001-01-08  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Tue 2001-01-09  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Wed 2001-01-10  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Thu 2001-01-11  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Fri 2001-01-12  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Sat 2001-01-13  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Sun 2001-01-14  |  Mon 2001-01-08  |  Sun 2001-01-14  |
+------------------+------------------+------------------+
</code>```

* For Sunday to Saturday weeks you need to adjust the equation just a little, like add 1 somewhere.

ContentLicense: CC BY-SA 4.0

Body:
I have a query that counts member's wedding dates in the database.

SELECT
  SUM(NumberOfBrides) AS [Wedding Count]
  , DATEPART( wk, WeddingDate) AS [Week Number]
  , DATEPART( year, WeddingDate) AS [Year]
FROM  MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC

How do I work out when the start and end of each week represented in the result set?

SELECT
  SUM(NumberOfBrides) AS [Wedding Count]
  , DATEPART(wk, WeddingDate) AS [Week Number]
  , DATEPART(year, WeddingDate) AS [Year]
  , ??? AS WeekStart
  , ??? AS WeekEnd
FROM  MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC

Body:
Let us break the problem down to two parts:

1) Determine the day of week

The DATEPART(dw, ...) returns a number, 1...7, relative to DATEFIRST setting (docs). The following table summarizes the possible values:

                                                   @@DATEFIRST
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+
|                                    |  1  |  2  |  3  |  4  |  5  |  6  |  7  | DOW |
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+
|  DATEPART(dw, /*Mon*/ '20010101')  |  1  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |
|  DATEPART(dw, /*Tue*/ '20010102')  |  2  |  1  |  7  |  6  |  5  |  4  |  3  |  2  |
|  DATEPART(dw, /*Wed*/ '20010103')  |  3  |  2  |  1  |  7  |  6  |  5  |  4  |  3  |
|  DATEPART(dw, /*Thu*/ '20010104')  |  4  |  3  |  2  |  1  |  7  |  6  |  5  |  4  |
|  DATEPART(dw, /*Fri*/ '20010105')  |  5  |  4  |  3  |  2  |  1  |  7  |  6  |  5  |
|  DATEPART(dw, /*Sat*/ '20010106')  |  6  |  5  |  4  |  3  |  2  |  1  |  7  |  6  |
|  DATEPART(dw, /*Sun*/ '20010107')  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  7  |
+------------------------------------+-----+-----+-----+-----+-----+-----+-----+-----+

The last column contains the ideal day-of-week value for Monday to Sunday weeks*. By just looking at the chart we come up with the following equation:

(@@DATEFIRST + DATEPART(dw, SomeDate) - 1 - 1) % 7 + 1

2) Calculate the Monday and Sunday for given date

This is trivial thanks to the day-of-week value. Here is an example:

WITH TestData(SomeDate) AS (
    SELECT CAST('20001225' AS DATETIME) UNION ALL
    SELECT CAST('20001226' AS DATETIME) UNION ALL
    SELECT CAST('20001227' AS DATETIME) UNION ALL
    SELECT CAST('20001228' AS DATETIME) UNION ALL
    SELECT CAST('20001229' AS DATETIME) UNION ALL
    SELECT CAST('20001230' AS DATETIME) UNION ALL
    SELECT CAST('20001231' AS DATETIME) UNION ALL
    SELECT CAST('20010101' AS DATETIME) UNION ALL
    SELECT CAST('20010102' AS DATETIME) UNION ALL
    SELECT CAST('20010103' AS DATETIME) UNION ALL
    SELECT CAST('20010104' AS DATETIME) UNION ALL
    SELECT CAST('20010105' AS DATETIME) UNION ALL
    SELECT CAST('20010106' AS DATETIME) UNION ALL
    SELECT CAST('20010107' AS DATETIME) UNION ALL
    SELECT CAST('20010108' AS DATETIME) UNION ALL
    SELECT CAST('20010109' AS DATETIME) UNION ALL
    SELECT CAST('20010110' AS DATETIME) UNION ALL
    SELECT CAST('20010111' AS DATETIME) UNION ALL
    SELECT CAST('20010112' AS DATETIME) UNION ALL
    SELECT CAST('20010113' AS DATETIME) UNION ALL
    SELECT CAST('20010114' AS DATETIME)
), TestDataPlusDOW AS (
    SELECT SomeDate, (@@DATEFIRST + DATEPART(dw, SomeDate) - 1 - 1) % 7 + 1 AS DOW
    FROM TestData
)
SELECT
    FORMAT(SomeDate,                            'ddd yyyy-MM-dd') AS SomeDate,
    FORMAT(DATEADD(dd, -DOW + 1, SomeDate),     'ddd yyyy-MM-dd') AS [Monday],
    FORMAT(DATEADD(dd, -DOW + 1 + 6, SomeDate), 'ddd yyyy-MM-dd') AS [Sunday]
FROM TestDataPlusDOW

Output:

+------------------+------------------+------------------+
|  SomeDate        |  Monday          |    Sunday        |
+------------------+------------------+------------------+
|  Mon 2000-12-25  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Tue 2000-12-26  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Wed 2000-12-27  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Thu 2000-12-28  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Fri 2000-12-29  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Sat 2000-12-30  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Sun 2000-12-31  |  Mon 2000-12-25  |  Sun 2000-12-31  |
|  Mon 2001-01-01  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Tue 2001-01-02  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Wed 2001-01-03  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Thu 2001-01-04  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Fri 2001-01-05  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Sat 2001-01-06  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Sun 2001-01-07  |  Mon 2001-01-01  |  Sun 2001-01-07  |
|  Mon 2001-01-08  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Tue 2001-01-09  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Wed 2001-01-10  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Thu 2001-01-11  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Fri 2001-01-12  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Sat 2001-01-13  |  Mon 2001-01-08  |  Sun 2001-01-14  |
|  Sun 2001-01-14  |  Mon 2001-01-08  |  Sun 2001-01-14  |
+------------------+------------------+------------------+

* For Sunday to Saturday weeks you need to adjust the equation just a little, like add 1 somewhere.


问:
Count Number of Instances of string using FORMULATEXT
I have data that extends from column A1 to F1. All the cells contain VLOOKUP formulas looking up data from an external Excel file.

I want to be able to insert a formula in column G1 to count the number of times a certain filename is used in columns A1 to F1.

I know that if the data in cells A1 to F1 were NOT formulas I could use something like the below in G1 if I was searching for the string "filename.xlsx" using wildcards:

```<code>=COUNTIF(A1:F1, "*filename.xlsx*")
</code>```

However, as A1 to F1 contain formulas, I assume I would need to use FORMULATEXT, in order to look within the VLOOKUPs. I have tried the below, but it doesn't work:

```<code>=COUNTIF(FORMULATEXT(A1:F1),"*filename.xlsx*")
</code>```

Does anyone know if there is a way to do this? it would also be good if the criteria within the COUNTIF was a cell reference. However, that isn't essential.

Thanks

答:
Try using this array formula

=COUNT(SEARCH("filename.xlsx",FORMULATEXT(A1:F1)))

confirm with CTRL+SHIFT+ENTER

or a non array version.....

=SUMPRODUCT(ISNUMBER(SEARCH("filename.xlsx",FORMULATEXT(A1:F1)))+0)

Body:
I have data that extends from column A1 to F1. All the cells contain VLOOKUP formulas looking up data from an external Excel file.

I want to be able to insert a formula in column G1 to count the number of times a certain filename is used in columns A1 to F1.

I know that if the data in cells A1 to F1 were NOT formulas I could use something like the below in G1 if I was searching for the string "filename.xlsx" using wildcards:

=COUNTIF(A1:F1, "*filename.xlsx*")

However, as A1 to F1 contain formulas, I assume I would need to use FORMULATEXT, in order to look within the VLOOKUPs. I have tried the below, but it doesn't work:

=COUNTIF(FORMULATEXT(A1:F1),"*filename.xlsx*")

Does anyone know if there is a way to do this? it would also be good if the criteria within the COUNTIF was a cell reference. However, that isn't essential.

Thanks


问:
How to get values of custom Azure AD B2C user profiles properties
I have an Azure AD B2C tenant and app within it with enabled authentication using Facebook, other AAD and local accounts. Users in B2C have some custom fields which are populated on registration and used as claims in JWT token.

But I cannot see this fields value's anywhere in the Azure portal nor using Microsoft Graph API.

Where they are stored and how to get access to them?

答:
You can access custom claims by including them in the token sent to the app or by querying the Azure AD Graph API (not the Microsoft Graph yet).

Including custom claims in the token: In the Azure portal's B2C blade, select the policy you are using, click on Edit, Application claims and select the custom attribute. Full documentation

Querying the Azure AD Graph API: Register an Azure AD application, query the Azure AD Graph API. Full documentation

Here's some C# code for #2

// The client_id, client_secret, and tenant are pulled in from the App.config file
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
var tenant = "yourtenant.onmicrosoft.com";

var userObjectID = "OID_OF_THE_USER"
var query = "/users/" + userObjectId

this.authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);

// The ClientCredential is where you pass in your client_id and client_secret, which are
// provided to Azure AD in order to receive an access_token using the app's identity.
this.credential = new ClientCredential(clientId, clientSecret);

// First, use ADAL to acquire a token using the app's identity (the credential)
// The first parameter is the resource we want an access_token for; in this case, the Graph API.
AuthenticationResult result = authContext.AcquireToken("https://graph.windows.net", credential);

// For B2C user managment, be sure to use the Azure AD Graph API for now.
HttpClient http = new HttpClient();
string url = "https://graph.windows.net/" + tenant + api + "?" + Globals.aadGraphVersion;
url += "&" + query;

// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);

if (!response.IsSuccessStatusCode)
{
    string error = await response.Content.ReadAsStringAsync();
    object formatted = JsonConvert.DeserializeObject(error);
    throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}

return await response.Content.ReadAsStringAsync();
```


问:
Creating pdf file using native js?
A have a project on angularjs and I need to create and download a document for print(no needed to save it on server). It can be .docx, but .pdf is preferable(so simple user won't able to change file). So, I know that there is a framework called PHPWord, but I don't like php at all. And there is another framework called docx.js(but it jquery required).

There is one more problem that I need to add values of variables to the docx template(which located on server, so admin can change it, of course he won't touch variables in this file) and then download fulfilled pdf document. It is not necessary to use docx template, nevertheless this variant is preferable.

Can you give me some recommendation in which way I need to look? Maybe you know some good framework based on native JS?

答:
I haven't personally used this, but it looks like a contender.

It runs atop Node, so you can leverage your JavaScript skills.

http://pdfkit.org/

https://github.com/devongovett/pdfkit

Title: Creating pdf file using native js?


问:
How to setup a script that automatically clones the DB every 2 hours?
I'm planning to build a system that will have 30+ tables and 100+ million rows in a few of those. Going to use MySQL - InnoDB (any better alternative for this?)

My scripts are going to add a couple of hundreds of thousands of clicks to the database every day. On the other hand, I'd like to do heavy database queries during the day as well.

What I came us with is to have two different servers. Server A would take all the clicks and store them and Server B would work on retrieving the results.

Question A: Is this the right approach to do? Question B: Is it possible to set up a script that's cloning the database over from Server A to Server B - so the data is semi-up to date?

Edit: LEMP stack

答:
You should not do this via a batch process that runs a large update every so often. Instead, use MySQL’s built-in replication features.

In particular, use a master-slave configuration. This allows you to keep multiple servers current in (essentially) real-time, while splitting reads (fast) from writes (slow) to get maximum performance.


问:
Angular Observable: modify data before resolve
I tried to transform data before resolve by such way, but subscriber gets non-transformed data.

```<code>@Injectable()
export class OrderService {
    getAll(): Observable< Array<Order> > {
        let url = 'http://fakeapi.com';
        return this.http.get( url )
          .pipe(
            tap( (data: any) => {
                /*
                * MAKE DATA TRANSFORMATIONS HERE
                */
            }),
            catchError( (err: any, caught: Observable<{}>) => {
              console.log('error while GET : ' + url);
              console.warn(err);
              return caught;
            })
          );
    }
}
</code>```

here is a subscriber:

```<code>this._orderService.getAll().subscribe( data => {
  this.orders = data;
  console.log('\nplanning-overview-page : _orderService.getAll : data ', data);
});
</code>```

答:
map is the operator for transforming a value in an observable stream, and you have to make sure it returns a value.</p>

```<code>map(data => {
    // do your transformations
    return data;
});
</code>```

Body:
I tried to transform data before resolve by such way, but subscriber gets non-transformed data.

@Injectable()
export class OrderService {
    getAll(): Observable< Array<Order> > {
        let url = 'http://fakeapi.com';
        return this.http.get( url )
          .pipe(
            tap( (data: any) => {
                /*
                * MAKE DATA TRANSFORMATIONS HERE
                */
            }),
            catchError( (err: any, caught: Observable<{}>) => {
              console.log('error while GET : ' + url);
              console.warn(err);
              return caught;
            })
          );
    }
}

here is a subscriber:

this._orderService.getAll().subscribe( data => {
  this.orders = data;
  console.log('\nplanning-overview-page : _orderService.getAll : data ', data);
});

Body:
map is the operator for transforming a value in an observable stream, and you have to make sure it returns a value.

map(data => {
    // do your transformations
    return data;
});


答:
The only part you need to change is the * Keywords * section

```<code>*** Keywords ***
Open URL
    [Arguments]  ${URL}
    Open Browser    ${URL}     Chrome
</code>```

Instead of square brackets use braces

Title: Test Template with Robot Framework

Body:
The only part you need to change is the * Keywords * section

*** Keywords ***
Open URL
    [Arguments]  ${URL}
    Open Browser    ${URL}     Chrome

Instead of square brackets use braces


问:
Django/WeasyPrint: Bangla Font Rendering Issue
My Python Version 3.6+, Django version 1.11.6 and OS: Windows-10 64bit.

I am creating the PDF file with weasyprint within Django project. But the problem is Bengali font is not rendering. Please check this screenshot.

Now this is my views.py file

```<code>def get_pdf_file(request, customer_id, sys_type):
    sys_type = customer_id
    area = "pdf"
    site_credit = site_credit1
    time_now = timezone.now()
    customers = get_object_or_404(CustomerInfo, pk=customer_id)

    due_taka_track = customers.duetaka_set.all()

    if due_taka_track == None:
        due_taka_track = 0

    unpaid_taka = int(customers.customer_price -
                      customers.customer_due_taka_info)
    due_taka_track = customers.duetaka_set.all()

    sum_cost_taka = due_taka_track.aggregate(
        sp=Sum('customer_due')).get('sp', 0)

    if sum_cost_taka == None:
        sum_cost_taka = 0
    total_paid_taka = sum_cost_taka + customers.customer_due_taka_info

    payment_status = 'complete'
    payment_message = ' '
    remain_taka='Full Paid '
    remain_msg=''

    if customers.customer_due_taka_info < customers.customer_price:
        payment_status = 'incomplete'
        payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি'
        remain_msg='টাকা বাকী আছে'
        baki_ase="পাওনা আছে "

        remain_taka = customers.customer_price - customers.customer_due_taka_info

    context = {'customers': customers,
    'sys_type': sys_type,
    'area': area,
    'site_credit': site_credit,
    'site_name': 'Moon Telecom',
    'sys_type': sys_type,
    'due_taka_track': due_taka_track,
    'total_paid_taka': total_paid_taka,
    'payment_message': payment_message,
    'time_now': time_now,
    'unpaid_taka': unpaid_taka,
    'payment_message': payment_message,
    'remain_taka': remain_taka,
    'sum_cost_taka': sum_cost_taka,
    'remain_msg': remain_msg}

    html_string = render_to_string('shop/pdf_invoice.html', context).encode(encoding="UTF-8")
    response = HttpResponse(content_type='application/pdf')

    response['Content-Disposition'] = 'inline; filename=invoice' + \
        str(customers.id)+customers.customer_uid + customers.customer_name + '.pdf'

    HTML(string=html_string).write_pdf(response)
    return response
</code>```

and this is my html file

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-16">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>invoice copy {% if customers.customer_name %}Customer Name:{{customers.customer_name}}{% else %}
    Name: দেওয়া হয়নি{% endif %} | {{customers.customer_uid}}</title>

<head>
    <style>
        @import url('https://fonts.maateen.me/siyam-rupali/font.css');
        table,
        th,
        td {
            border: 1px solid black;
        }

        th,
        td {
            padding: 5px;
            text-align: left;
        }
        p,th,td,th,tr{
            font-size:10px;line-height:12px
            font-family: 'SiyamRupali', sans-serif;
        }
        .border_sx {
            border-style: solid;
            border-width: 1px;
            padding: 5px;
            border-radius: 5px;
            display:block;
            width: 100%;
            margin-right:-100px;
            padding: 10px;

}

        #background{
    position:absolute;
    z-index:0;
    background:white;
    display:block;
    min-height:50%;
    min-width:50%;
    color:yellow;
}

#content{
    position:absolute;
    z-index:0.1;
}

#bg-text
{
    color:lightgrey;
    font-size:70px;
    margin-top: 160px;

    margin-right: 40px;
    transform:rotate(320deg);
    -webkit-transform:rotate(300deg);
}

#bg-text-one
{
    color:lightgrey;
    font-size:20px;
    line-height: 25px;
    margin-right: 100px;
    margin-bottom: 800px;
    margin-top: -10px;
    transform:rotate(320deg);
    -webkit-transform:rotate(300deg);
}
    #fix_font
    {
        font-size: 13.5px;
    }

    table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {

    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {

}
    </style>
</head>

<body>
    <div id="background">
        <p id="bg-text">Moon Telecom</p>
        <p id="bg-text-one">Fulhata Bazar জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ। 01717-051200(সুকান্ত বসু) 01828-163858(দোকান)</p>
    </div>

    <div id="content" class="border_sx">
        <div class="invoice_intro">
            <div class="site_title" style="text-align:center; margin:0 auto">
                <h1 style="font-size:10px;line-height:12px">ওঁ</h1>
                <p style="font-size:8px;line-height:10px">মা কালী সহায়</p>
                <h2 style="font-size:19px;line-height:13px;">মুন টেলিকম</h2>

                <div class="invoice_info_one" style="width:70%;margin:0 auto; text-align:center">
                    <p style=";">সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার,
                        ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p>
                </div>
                <div class="invoice_location">
                    <p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p>
                </div>
                <div class="invoice_contact">
                    <p>01717-051200(সুকান্ত বসু) 01828-163858(দোকান)
                        <b>Email:</b> moontelecom2008@gmail.com</p>
                </div>

                <hr>
            </div>
        </div>

        <div class="customer_part" style="width:40%;margin:0px left;display:block">

            <div class="customer_info">
                {% if customers.customer_name %}
                <p style="font-size:">Customer Name:
                    <b> {{customers.customer_name}}</b>

                </p>
                {% else %}
                <p> Name: দেওয়া হয়নি</p> {% endif %}

                <p style="font-size:x">Phone Number: {% if customers.customer_mobile_no %} {{customers.customer_mobile_no}} {% else %} No Mobile Number
                    {% endif%}
                </p>
                <p style="font-size:">Purchase Time: {{customers.customer_sell_date}}</p>
                <p style="font-size:">invoice id:
                    <b>{{customers.customer_uid}}</b>
                </p>
                <p>{{customers.product_warrenty}}</p>
            </div>
        </div>

        <div class="">
            <table style="border-style: solid;border-width: 0px;">

                <tr>
                    <th>Product Name</th>
                    <th colspan="">Price</th>
                    <th>Product Price (MRP)</th>
                    <th>ID or IME</th>
                    <th>Warrenty</th>
                    <th>QN</th>

                </tr>

                <tr>
                    <td>
                        <b>{{customers.customer_product_name}}</b>
                    </td>
                    <td>
                        <b>Customer Price: {{customers.customer_price}}</b> TK
                        <i>{% if customers.customer_discount_taka %}
                        ( Discount added {{customers.customer_discount_taka}} TK )
                        {% else%}
                        {%endif%}</i>
                    </td>
                    <td>{{customers.customer_product_mrp}} Taka * {{customers.customer_product_quantity}} (QN) </td>
                    <td>{{customers.customer_product_id}}</td>

                    <td>
                        {% if customers.customer_product_warrenty %} {{customers.customer_product_warrenty}} Months {% else %} No {% endif %}
                    </td>
                    <td>{{customers.customer_product_quantity}}</td>
                </tr>

                <th>
                    First Time Payment
                </th>

                <th>

                    {{customers.customer_first_time_payment}} TK
                    <span style="color:red">{{customers.customer_first_due_info}}</span>
                </th>

                <td>
                    {{customers.customer_sell_date}}
                </td>

                {% if due_taka_track %}

                <tr>
                    <th>SL</th>
                    <th>Taka</th>
                    <th>Paid Date</th>
                    <th>Due Info</th>

                </tr>

                <hr> {% for track in due_taka_track %}
                <tr>
                    <td>{{forloop.counter}}</td>
                    <td>
                        <i>{{track.customer_due}}</i> TK</td>
                    <td>{{track.customer_due_date}}</td>
                    <td>{{track.customer_due_info}}</td>
                </tr>
                {% endfor %} {% else %} {% endif %} {% if sum_cost_taka %}
                <tr>

                    <td>Total Due Complete </td>

                    <th>{{sum_cost_taka}} TK</th>

                </tr>
                {% else %} {% endif %}

                <tr>
                    <td>
                        <b>Total Paid</b>
                    </td>

                    <th>

                        {% if payment_message %}
                        {{customers.customer_due_taka_info}} TK

                        <span style="color:red">{{payment_message}}</span>
                        <br>

                        <button type="button" class="btn btn-danger">{{remain_msg}} {{remain_taka}}TK</button>
                        {%else %} {{customers.customer_due_taka_info}} TK
                        <button type="button" class="btn btn-success">Payment Completed</button>

                        {% endif %}
                    </th>
                </tr>
            </table>
            <table border="none!important" style="margin-top:10px;border:none!important">
                <tr>
                    <th style="text-align:left">Customer signature</th>
                    <th  style="text-align:right">Authorized signature</th>
                </tr>
            </table>
        </div>

        <div class="customer_notifications">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">

                        {% if customers.customer_conditions %}
                        <div class="warning">
                            <p>
                                <i>{{customers.customer_product_name}} {{customers.customer_conditions}}</i>
                            </p>
                        </div>

                        {% else %} {% endif %}

                        <div class="col-lg-12">
                            <div class="footer_info">
                                <p id="fix_font"><b>বিঃদ্রঃ ডেলিভারির সময় মাল বুঝিয়া নিবেন। পরে কোন আপত্তী গ্রহনযোগ্য নয়। (বিক্রিত মাল ফেরত হয় না) </h6>
                                <p>Print date: {{time_now}}</b></p>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer" style="display:block">
            <div class="footer_info">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="footer_info">
                                <div class="copy_right">
                                    {% if site_credit %}
                                    <p>{{site_credit}}</p>
                                    {% else %} {% endif %}

                                </div>

                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>

</html>
</code>```

I changed UTF-8/UTF but this issue did not fix.

答:
I installed(Kalpurush) font on my PC. Then I added that font write_pdf variable.</p>

```<code>HTML(string=html_string).write_pdf(response,stylesheets=[CSS(string='body,p,h1,h2,h3,h4,h5,tr,td { font-family: Kalpurush !important }')])
</code>```

Body:
My Python Version 3.6+, Django version 1.11.6 and OS: Windows-10 64bit.

I am creating the PDF file with weasyprint within Django project. But the problem is Bengali font is not rendering. Please check this screenshot.

Now this is my views.py file

def get_pdf_file(request, customer_id, sys_type):
    sys_type = customer_id
    area = "pdf"
    site_credit = site_credit1
    time_now = timezone.now()
    customers = get_object_or_404(CustomerInfo, pk=customer_id)

    due_taka_track = customers.duetaka_set.all()

    if due_taka_track == None:
        due_taka_track = 0

    unpaid_taka = int(customers.customer_price -
                      customers.customer_due_taka_info)
    due_taka_track = customers.duetaka_set.all()

    sum_cost_taka = due_taka_track.aggregate(
        sp=Sum('customer_due')).get('sp', 0)

    if sum_cost_taka == None:
        sum_cost_taka = 0
    total_paid_taka = sum_cost_taka + customers.customer_due_taka_info

    payment_status = 'complete'
    payment_message = ' '
    remain_taka='Full Paid '
    remain_msg=''

    if customers.customer_due_taka_info < customers.customer_price:
        payment_status = 'incomplete'
        payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি'
        remain_msg='টাকা বাকী আছে'
        baki_ase="পাওনা আছে "

        remain_taka = customers.customer_price - customers.customer_due_taka_info

    context = {'customers': customers,
    'sys_type': sys_type,
    'area': area,
    'site_credit': site_credit,
    'site_name': 'Moon Telecom',
    'sys_type': sys_type,
    'due_taka_track': due_taka_track,
    'total_paid_taka': total_paid_taka,
    'payment_message': payment_message,
    'time_now': time_now,
    'unpaid_taka': unpaid_taka,
    'payment_message': payment_message,
    'remain_taka': remain_taka,
    'sum_cost_taka': sum_cost_taka,
    'remain_msg': remain_msg}

    html_string = render_to_string('shop/pdf_invoice.html', context).encode(encoding="UTF-8")
    response = HttpResponse(content_type='application/pdf')

    response['Content-Disposition'] = 'inline; filename=invoice' + \
        str(customers.id)+customers.customer_uid + customers.customer_name + '.pdf'

    HTML(string=html_string).write_pdf(response)
    return response

and this is my html file

<!DOCTYPE html>

    <meta charset="UTF-16">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>invoice copy {% if customers.customer_name %}Customer Name:{{customers.customer_name}}{% else %}
    Name: দেওয়া হয়নি{% endif %} | {{customers.customer_uid}}</title>

Moon Telecom

Fulhata Bazar জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ। 01717-051200(সুকান্ত বসু) 01828-163858(দোকান)

ওঁ

মা কালী সহায়

মুন টেলিকম

সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার,
                        ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা

জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।

01717-051200(সুকান্ত বসু) 01828-163858(দোকান)
                        Email: moontelecom2008@gmail.com

                {% if customers.customer_name %}

Customer Name:
                     {{customers.customer_name}}

                {% else %}

 Name: দেওয়া হয়নি
 {% endif %}

Phone Number: {% if customers.customer_mobile_no %} {{customers.customer_mobile_no}} {% else %} No Mobile Number
                    {% endif%}

Purchase Time: {{customers.customer_sell_date}}

invoice id:
                    {{customers.customer_uid}}

{{customers.product_warrenty}}

                    Product Name
                    Price
                    Product Price (MRP)
                    ID or IME
                    Warrenty
                    QN

                        {{customers.customer_product_name}}

                        Customer Price: {{customers.customer_price}} TK
                        {% if customers.customer_discount_taka %}
                        ( Discount added {{customers.customer_discount_taka}} TK )
                        {% else%}
                        {%endif%}

                    {{customers.customer_product_mrp}} Taka * {{customers.customer_product_quantity}} (QN)
                    {{customers.customer_product_id}}

                        {% if customers.customer_product_warrenty %} {{customers.customer_product_warrenty}} Months {% else %} No {% endif %}

                    {{customers.customer_product_quantity}}

                    First Time Payment

                    {{customers.customer_first_time_payment}} TK
                    {{customers.customer_first_due_info}}

                    {{customers.customer_sell_date}}

                {% if due_taka_track %}

                    SL
                    Taka
                    Paid Date
                    Due Info

 {% for track in due_taka_track %}

                    {{forloop.counter}}

                        {{track.customer_due}} TK
                    {{track.customer_due_date}}
                    {{track.customer_due_info}}

                {% endfor %} {% else %} {% endif %} {% if sum_cost_taka %}

                    Total Due Complete

                    {{sum_cost_taka}} TK

                {% else %} {% endif %}

                        Total Paid

                        {% if payment_message %}
                        {{customers.customer_due_taka_info}} TK

                        {{payment_message}}

                        <button type="button" class="btn btn-danger">{{remain_msg}} {{remain_taka}}TK</button>
                        {%else %} {{customers.customer_due_taka_info}} TK
                        <button type="button" class="btn btn-success">Payment Completed</button>

                        {% endif %}

                    Customer signature
                    Authorized signature

                        {% if customers.customer_conditions %}

                                {{customers.customer_product_name}} {{customers.customer_conditions}}

                        {% else %} {% endif %}

বিঃদ্রঃ ডেলিভারির সময় মাল বুঝিয়া নিবেন। পরে কোন আপত্তী গ্রহনযোগ্য নয়। (বিক্রিত মাল ফেরত হয় না)

Print date: {{time_now}}

                                    {% if site_credit %}

{{site_credit}}

                                    {% else %} {% endif %}

I changed UTF-8/UTF but this issue did not fix.

Body:
I installed(Kalpurush) font on my PC. Then I added that font write_pdf variable.

HTML(string=html_string).write_pdf(response,stylesheets=[CSS(string='body,p,h1,h2,h3,h4,h5,tr,td { font-family: Kalpurush !important }')])


问:
Apply an animation dynamically to an HTML element
My purpose is to apply a given animation to an html div, and the information about the name of this animation is based on the value contained in an Input variable in the angular component:

```<code>@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  animations: [
    myFirstAnimation(),
    mySecondAnimation(),
    myThirdAnimation(),
  ]
})
export class TestComponent implements OnInit {
  /*
   * The information about the name of the animation is containded in obj.animation
   * For example: obj.animation may contain '@myFirstAnimation',  '@mySecondAnimation' or '@myThirdAnimation'
   */
  @Input() obj: any;

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

How could I insert obj.animation as a div attribute in order to insert dynamically the animation into the div?

答:
I tried to solve my problem from a different approach by using animation states.

In my HTML element, I always refer to the same animation:

```<code><div [@myAnimation]="obj.animation">
</code>```

where obj.animation may contain different states of the animation (for example: state1, state2,...).

The animation is defined for example as follows:

```<code>trigger('myAnimation', [
  transition('void => state1', [
      style({ transform: 'translateX(-100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  transition('void => state2', [
      style({ transform: 'translateX(100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  //...
]);
</code>```

Body:
My purpose is to apply a given animation to an html div, and the information about the name of this animation is based on the value contained in an Input variable in the angular component:

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  animations: [
    myFirstAnimation(),
    mySecondAnimation(),
    myThirdAnimation(),
  ]
})
export class TestComponent implements OnInit {
  /*
   * The information about the name of the animation is containded in obj.animation
   * For example: obj.animation may contain '@myFirstAnimation',  '@mySecondAnimation' or '@myThirdAnimation'
   */
  @Input() obj: any;

  //...
}

How could I insert obj.animation as a div attribute in order to insert dynamically the animation into the div?

Body:
I tried to solve my problem from a different approach by using animation states.

In my HTML element, I always refer to the same animation:

<div [@myAnimation]="obj.animation">

where obj.animation may contain different states of the animation (for example: state1, state2,...).

The animation is defined for example as follows:

trigger('myAnimation', [
  transition('void => state1', [
      style({ transform: 'translateX(-100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  transition('void => state2', [
      style({ transform: 'translateX(100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  //...
]);


问:
How to make nginx passthrough on 443 and redirect 80 to 443?
I have a winstone server (Jenkins) listening on 8443.
Jenkins has a valid cert, and Jenkins is doing the cert termination successfully:

```<code>JENKINS_ARGS="--httpPort=-1 --httpsKeyStore=/secure/jenkins.keystore --httpsKeyStorePassword=MY_PASSWORD --httpsPort=8443"
</code>```

The only problem is that users now have to go:
https://example.com:8443

I don't want that port number in the URL.
I want:

```<code>https://example.com:8443 -> https://example.com
https://example.com      -> https://example.com
http://example.com       -> https://example.com
</code>```

So I figure I'll run nginx on the same instance that is running Jenkins.

So my question is:

Do I have to reconfigure jenkins to NOT do cert termination so that nginx does it only?

Can nginx redirect 80 and 443 to localhost:8443 without a cert (Since Jenkins is doing cert termination)?

Do BOTH nginx AND Jenkins need to do cert termination?

Sorry for those similar questions.

I'm pretty sure an AWS ELB cannot replace what nginx is doing here, but I thought I'd throw it out there, in case an ELB can solve this for me too.

答:
1) No, you can have Nginx Stream the connection directly to the Jenkins using the Stream Module.

Do note this was added in 1.9.0 but is not part of the default build so you might have to build it yourself.

It works a lot like an http server block but you have to set it up outside of the http block.

```<code>stream {
    upstream jenkins_server {
        server jenkins:443;
    }

    server {
        listen 443;
        proxy_pass jenkins_server;
    }
}
</code>```

2) You do not need a cert on nginx but you should have a http server block for port 80 that does a 301 to the 443 stream talked about in answer part 1.

```<code>server {
    listen 80;
    server_name your_server_name_here;
    return 301 https://$host$request_uri;
}
</code>```

3) No, you don't as you can use the nginx stream to passthru the ssl from the client to the Jenkins server.

Body:
I have a winstone server (Jenkins) listening on 8443.
Jenkins has a valid cert, and Jenkins is doing the cert termination successfully:

JENKINS_ARGS="--httpPort=-1 --httpsKeyStore=/secure/jenkins.keystore --httpsKeyStorePassword=MY_PASSWORD --httpsPort=8443"

The only problem is that users now have to go:
https://example.com:8443

I don't want that port number in the URL.
I want:

https://example.com:8443 -> https://example.com
https://example.com      -> https://example.com
http://example.com       -> https://example.com

So I figure I'll run nginx on the same instance that is running Jenkins.

So my question is:

Do I have to reconfigure jenkins to NOT do cert termination so that nginx does it only?

Can nginx redirect 80 and 443 to localhost:8443 without a cert (Since Jenkins is doing cert termination)?

Do BOTH nginx AND Jenkins need to do cert termination?

Sorry for those similar questions.

I'm pretty sure an AWS ELB cannot replace what nginx is doing here, but I thought I'd throw it out there, in case an ELB can solve this for me too.

Body:
1) No, you can have Nginx Stream the connection directly to the Jenkins using the Stream Module.

Do note this was added in 1.9.0 but is not part of the default build so you might have to build it yourself.

It works a lot like an http server block but you have to set it up outside of the http block.

stream {
    upstream jenkins_server {
        server jenkins:443;
    }

    server {
        listen 443;
        proxy_pass jenkins_server;
    }
}

2) You do not need a cert on nginx but you should have a http server block for port 80 that does a 301 to the 443 stream talked about in answer part 1.

server {
    listen 80;
    server_name your_server_name_here;
    return 301 https://$host$request_uri;
}

3) No, you don't as you can use the nginx stream to passthru the ssl from the client to the Jenkins server.


问:
How to get output to print out next to each other?
Im not sure if you would need the full code to be able to help, but I've included the code that I'm having the problem with.

So I need the output of the code to print next to each other like
12    23   56   89   45   78

But it prints out each number on a different line.
How would i do that?
I've tried using \t and it doesn't help. I dont know what else to try.

```<code>    System.out.println("------------------------------------------------------------------");

    for ( int i = 0; i < Temperature[0].length; i++ )
    {
        System.out.println();
        columnTotal =0;
       for ( int j = 0; j < Temperature.length; j++ )
        {
           columnTotal=columnTotal+Temperature[j][i];

        }

       System.out.print(columnTotal/4);
    }
}
</code>```

答:
Remove the System.out.println(); it is printing a new line in your loop. You should also append a space when printing columnTotal/4. So your code should be like:

```<code>for ( int i = 0; i < Temperature[0].length; i++ )
 {
   // System.out.println();
   columnTotal =0;
   for ( int j = 0; j < Temperature.length; j++ )
    {
       columnTotal=columnTotal+Temperature[j][i];

    }
   System.out.print((columnTotal/4) + " ");
}
</code>```

Body:
Im not sure if you would need the full code to be able to help, but I've included the code that I'm having the problem with.

So I need the output of the code to print next to each other like
12    23   56   89   45   78

But it prints out each number on a different line.
How would i do that?
I've tried using \t and it doesn't help. I dont know what else to try.

    System.out.println("------------------------------------------------------------------");

    for ( int i = 0; i < Temperature[0].length; i++ )
    {
        System.out.println();
        columnTotal =0;
       for ( int j = 0; j < Temperature.length; j++ )
        {
           columnTotal=columnTotal+Temperature[j][i];

        }

       System.out.print(columnTotal/4);
    }
}

Body:
Remove the System.out.println(); it is printing a new line in your loop. You should also append a space when printing columnTotal/4. So your code should be like:

for ( int i = 0; i < Temperature[0].length; i++ )
 {
   // System.out.println();
   columnTotal =0;
   for ( int j = 0; j < Temperature.length; j++ )
    {
       columnTotal=columnTotal+Temperature[j][i];

    }
   System.out.print((columnTotal/4) + " ");
}


答:
Modify your loop like</p>

```<code>for ( int i = 0; i < Temperature[0].length; i++ )
{
   columnTotal =0;
   for ( int j = 0; j < Temperature.length; j++ )
   {
       columnTotal=columnTotal+Temperature[j][i];

   }

   System.out.print(columnTotal/4 + " ");
}
</code>```

Title: How to get output to print out next to each other?

Body:
Modify your loop like

for ( int i = 0; i < Temperature[0].length; i++ )
{
   columnTotal =0;
   for ( int j = 0; j < Temperature.length; j++ )
   {
       columnTotal=columnTotal+Temperature[j][i];

   }

   System.out.print(columnTotal/4 + " ");
}


问:
when css position sticky stops sticking
I was wondering why position: sticky works for some x-axis-scrolling, but once you scroll past the initial width of the screen width, your 'sticky div', stops sticking.

In this example, I have a left-side-bar that sticks to the left (please note that I cannot use position: fixed or position: absolute, because in my actual project both the left-div and the right-div need to scroll up and down along the y-axis, hence we only want left-side-sticking)

is there an additional CSS parameter I can define, such as

```<code>left-sticky-distance=999999%
</code>```

or something like that?

some test code illustrating is below

```<code>    <html>

    <body>

    <div style='
    position:sticky;
    z-index:1;
    left:0;
    width:100px;
    height:200px;
    overflow: hidden;
    background-color:#ff0000;
    opacity:0.8;'
    >

    </div>

      <div style='position: absolute; top: 10; left: 10; width: 200; height:50px; background-color: blue'>B</div>
      <div style='position: absolute; top: 10; left: 110; width: 200; height:50px; background-color: blue'>C</div>
      <div style='position: absolute; top: 10; left: 210; width: 200; height:50px; background-color: blue'>D</div>
    </body>
    <html>
</code>```

答:
This question: https://stackoverflow.com/a/45530506 answers the problem.

Once the "sticky div" reaches the edge of the screen, it is at the end of the viewport of the parent element. This causes the sticky element to stop and stay at the end of parent's viewport. This code pen provides an example: https://codepen.io/anon/pen/JOOBxg

#parent{
      width: 1000px;
      height: 1000px;
      background-color: red;
}
#child{
      width: 200px;
      height: 200px;
      background-color: blue;
      position: sticky;
      top: 0px;
      left: 0px;
}
body{
      width: 3000px;
      height: 3000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <div id="parent">
    <div id="child">
    </div>
  </div>
</html>

   </code>```

Title: when css position sticky stops sticking

Body:
I was wondering why position: sticky works for some x-axis-scrolling, but once you scroll past the initial width of the screen width, your 'sticky div', stops sticking.

In this example, I have a left-side-bar that sticks to the left (please note that I cannot use position: fixed or position: absolute, because in my actual project both the left-div and the right-div need to scroll up and down along the y-axis, hence we only want left-side-sticking)

is there an additional CSS parameter I can define, such as

left-sticky-distance=999999%

or something like that?

some test code illustrating is below

B

C

D

Body:
This question: https://stackoverflow.com/a/45530506 answers the problem.

Once the "sticky div" reaches the edge of the screen, it is at the end of the viewport of the parent element. This causes the sticky element to stop and stay at the end of parent's viewport. This code pen provides an example: https://codepen.io/anon/pen/JOOBxg

#parent{
      width: 1000px;
      height: 1000px;
      background-color: red;
}
#child{
      width: 200px;
      height: 200px;
      background-color: blue;
      position: sticky;
      top: 0px;
      left: 0px;
}
body{
      width: 3000px;
      height: 3000px;
}

<html>
  <div id="parent">
    <div id="child">
    </div>
  </div>
</html>


问:
Permissions for truncating a table
What permission do I need to GRANT a user, in MSSQL, in order to be able to truncate a table?

I'm trying to grant the minimal set of permissions, but I can't use DELETE, because the table is very large, and I want the operation to be quick.

答:
You can create a stored procedure with execute as owner:

```<code>create procedure dbo.TruncTable
with execute as owner
as
truncate table TheTable
go
</code>```

Then grant execution permissions to whoever needs to truncate that table:

```<code>grant execute on TruncTable to TheUser
</code>```

Now TheUser can truncate the table like:

```<code>exec dbo.TruncTable
</code>```

ContentLicense: CC BY-SA 2.5

Title: Permissions for truncating a table

Body:
You can create a stored procedure with execute as owner:

create procedure dbo.TruncTable
with execute as owner
as
truncate table TheTable
go

Then grant execution permissions to whoever needs to truncate that table:

grant execute on TruncTable to TheUser

Now TheUser can truncate the table like:

exec dbo.TruncTable


问:
Why does visual studio give me Type is not defined for my App_Code classes?
"Type 'HR.Database' is not defined'

I get that error for several classes that are stored in the App_Code folder in the Error List panel when building my project.

It is a class I wrote with namespace HR

How can I reference it or alter the project to recognize those classes and remove the error?

I thought I should reference it but when trying to add a reference there are no items in the list of projects. Also, they are .vb files and not a .dll

答:
Since it's late and over 3 years old. I came across a similar issue. The solution above is perfect. </p>

<p>With newer VS IDE versions, go to App_Code file's properties and update the Build Action to 'Compile' if it's set as 'Content'. Using App_Code folder may be outdated in newer VS versions but some older developers still use the folder. </p>

Body:
Since it's late and over 3 years old. I came across a similar issue. The solution above is perfect.

With newer VS IDE versions, go to App_Code file's properties and update the Build Action to 'Compile' if it's set as 'Content'. Using App_Code folder may be outdated in newer VS versions but some older developers still use the folder.


答:
Why is it printing each number on a new line?

In your for-loop, you use System.out.println(); at the start of each loop. println() is short for print line, so you are essentially printing a new empty line at the start of each loop.

Proposed solution

To reduce the number of prints to the console, we first build what we want to print into a single String using StringBuilder. Please see the sample below:

```<code>StringBuilder result = new StringBuilder();

for (int i = 0; i < Temperature[0].length; i++) {
    columnTotal = 0;

    for (int j = 0; j < Temperature.length; j++) {
       columnTotal = columnTotal + Temperature[j][i];
    }

   result.append(columnTotal / 4).append(" ");
}

System.out.println(result);
</code>```

Body:
Why is it printing each number on a new line?

In your for-loop, you use System.out.println(); at the start of each loop. println() is short for print line, so you are essentially printing a new empty line at the start of each loop.

Proposed solution

To reduce the number of prints to the console, we first build what we want to print into a single String using StringBuilder. Please see the sample below:

StringBuilder result = new StringBuilder();

for (int i = 0; i < Temperature[0].length; i++) {
    columnTotal = 0;

    for (int j = 0; j < Temperature.length; j++) {
       columnTotal = columnTotal + Temperature[j][i];
    }

   result.append(columnTotal / 4).append(" ");
}

System.out.println(result);


问:
Way to execute Google Standalone Script directly from Drive
Well, I've been reading the documentation for a long time but, as per usual, it's really unclear...

I'm developing a Google Script with the Script Editor that is already working as expected (it have nothing to see with any G suite program but with Drive).

By now, the only way to execute it is opening the script editor and press on the "play" button or the "execute" bar and press on the function.

Obviously this is not a solution since anyone from the bussines could modify/see the code.

So the question is this: how can I make from this script something like an "exe" that I just have to double ckick (its obviously located at Drive) and it executes the script?

I saw this but seems it says no way to do it except from opening the code and execute from the google app script editor...

答:
A Web App is triggered by either an HTTPS GET or POST request.  You don't need to use Google Drive.

Ways to trigger a Web App:

Chrome Extension - You can create a Chrome Extension to make an HTTPS GET or POST request.  The user would need to install the Chrome extension, and the Chrome extension could put a button in the browser.

Link - Some HTML with a link in it.  An email with a link in it.  Click the link.

Address Bar - Browser's address bar - Every browser's address bar issues an HTTPS GET request, so you can run a Web App directly from the address bar.  Put the published Web App url into the browser address bar and click whatever the browser uses to load the page. (Only for a GET request)

Bookmark - The user could bookmark the link to your Web App. So, they would need to click the link in their bookmark.

Any program that can make an HTTPS GET or POST request.  For example, make a POST request from Python or C++.

For a GET request, you need a doGet() function in your script, and to react to a POST request you need a doPost() function.


问:
In OpenShift 3, how to run a docker image that requires root?
In OpenShift 3, how can deploy a docker image that requires root?</p>

答: You can run oc edit scc restricted and edit runAsUser.Type from MustRunAsNonRoot to RunAsAny. This is not recommended for security reasons.


问:
test for the file related function in python
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows. </p>

```<code>def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e
</code>```

<p>What should I do about testing above function? what should I assert (directory, file content, exceptions)? </p>

答:
Think about requirements you put on your method, like:

The method shall report an error in case source_dir does not exist or either source or destination director are not accessible

The method shall report create destination_dir if it does not exist and report an error if destination dir cannot be created

The method shall report an error if either source or destination dir have illegal values (null or illegal chars for directories)

The method shall copy all files from source to destination directory

check, if all files have been copied

The method shall replace existing files (maybe)

check, if existing files are replaced

Those are just some thoughts. Don't put any possible requirement and don't test too much, keep in mind what want to do with this method. If it's private or only used in your own code, you can reduce the scope, but if you provide a public API, then you have to make sure that any input has a defined result (which may be an error message).

Body:
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows.

def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e

What should I do about testing above function? what should I assert (directory, file content, exceptions)?


问:
Why I get data with not exist, if my 2 tables are the same? (Python,mysql)
I want to analogue 2 tables, these 2 tables are the same, but i get all data when i run my query. Why?</p>

```<code>connection = MySQLdb.connect(host='localhost',
    user='adam',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select `ACTUAL_TIME`, `ACTUAL_DAY`, `EXAMINED_AIRPORT_CODE`, `EXAMINED_AIRPORT_AIRPORT`,     `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`,`AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME`
from OSSZES as a
where not exists(select `ACTUAL_TIME`, `ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`, `EXAMINED_AIRPORT_AIRPORT`, `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`,`AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME`
from OSSZES_CLEAR as b
where `a`.`ACTUAL_DAY` = `b`.`ACTUAL_DAY` AND `a`.`EXAMINED_AIRPORT_CODE` = `b`.`EXAMINED_AIRPORT_CODE` AND `a`.`FLIGHT` = `b`.`FLIGHT` AND `a`.`SCHEDULED_TIME` = `b`.`SCHEDULED_TIME` AND `a`.`STATUS` = `b`.`STATUS`)
    into outfile '/tmp/proba.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()
</code>```

答:
It is a little unclear what you're trying to do. Assuming you want all records from table a where there is not a corresponding record in table b, and your logic in the subquery defines a proper join, here's how I'd do it.

```<code>    select
      `ACTUAL_TIME`,
      `ACTUAL_DAY`,
      `EXAMINED_AIRPORT_CODE`,
      `EXAMINED_AIRPORT_AIRPORT`,
      `EXAMINED_AIRPORT_COUNTRY`,
      `ARRIVALS/DEPARTURES`,
      `SCHEDULED_TIME`,
      `FLIGHT`,
      `FROM`,
      `AIRLANE`,
      `AIRCRAFT`,
      `STATUS`,
      `FLIGHT_ID_1`,
      `FLIGHT_ID_2`,
      `UPLOAD_TIME`
    from OSSZES as a
    left join (
      select
        `ACTUAL_TIME`
        `ACTUAL_DAY`,
        COALESCE(`EXAMINED_AIRPORT_CODE`, '') as EXAMINED_AIRPORT_CODE -- edit
        `EXAMINED_AIRPORT_AIRPORT`,
        `EXAMINED_AIRPORT_COUNTRY`,
        `ARRIVALS/DEPARTURES`,
        `SCHEDULED_TIME`,
        `FLIGHT`,
        `FROM`,
        `AIRLANE`,
        `AIRCRAFT`,
        `STATUS`,
        `FLIGHT_ID_1`,
        `FLIGHT_ID_2`,
        `UPLOAD_TIME`
      from OSSZES_CLEAR
    ) as b using (`ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`,`FLIGHT`,`SCHEDULED_TIME`,`STATUS`)
    where b.EXAMINED_AIRPORT_CODE is null
    into outfile '/tmp/proba.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
</code>```

If that doesn't work, please clarify what result you're getting and what result you expect.

Body:
I want to analogue 2 tables, these 2 tables are the same, but i get all data when i run my query. Why?

connection = MySQLdb.connect(host='localhost',
    user='adam',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select `ACTUAL_TIME`, `ACTUAL_DAY`, `EXAMINED_AIRPORT_CODE`, `EXAMINED_AIRPORT_AIRPORT`,     `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`,`AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME`
from OSSZES as a
where not exists(select `ACTUAL_TIME`, `ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`, `EXAMINED_AIRPORT_AIRPORT`, `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`,`AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME`
from OSSZES_CLEAR as b
where `a`.`ACTUAL_DAY` = `b`.`ACTUAL_DAY` AND `a`.`EXAMINED_AIRPORT_CODE` = `b`.`EXAMINED_AIRPORT_CODE` AND `a`.`FLIGHT` = `b`.`FLIGHT` AND `a`.`SCHEDULED_TIME` = `b`.`SCHEDULED_TIME` AND `a`.`STATUS` = `b`.`STATUS`)
    into outfile '/tmp/proba.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()

Body:
It is a little unclear what you're trying to do. Assuming you want all records from table a where there is not a corresponding record in table b, and your logic in the subquery defines a proper join, here's how I'd do it.

    select
      `ACTUAL_TIME`,
      `ACTUAL_DAY`,
      `EXAMINED_AIRPORT_CODE`,
      `EXAMINED_AIRPORT_AIRPORT`,
      `EXAMINED_AIRPORT_COUNTRY`,
      `ARRIVALS/DEPARTURES`,
      `SCHEDULED_TIME`,
      `FLIGHT`,
      `FROM`,
      `AIRLANE`,
      `AIRCRAFT`,
      `STATUS`,
      `FLIGHT_ID_1`,
      `FLIGHT_ID_2`,
      `UPLOAD_TIME`
    from OSSZES as a
    left join (
      select
        `ACTUAL_TIME`
        `ACTUAL_DAY`,
        COALESCE(`EXAMINED_AIRPORT_CODE`, '') as EXAMINED_AIRPORT_CODE -- edit
        `EXAMINED_AIRPORT_AIRPORT`,
        `EXAMINED_AIRPORT_COUNTRY`,
        `ARRIVALS/DEPARTURES`,
        `SCHEDULED_TIME`,
        `FLIGHT`,
        `FROM`,
        `AIRLANE`,
        `AIRCRAFT`,
        `STATUS`,
        `FLIGHT_ID_1`,
        `FLIGHT_ID_2`,
        `UPLOAD_TIME`
      from OSSZES_CLEAR
    ) as b using (`ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`,`FLIGHT`,`SCHEDULED_TIME`,`STATUS`)
    where b.EXAMINED_AIRPORT_CODE is null
    into outfile '/tmp/proba.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';

If that doesn't work, please clarify what result you're getting and what result you expect.


问:
Socket io handle two different user types
I have two socket servers running on separate machine.

```<code>// Customers
io.on('connection', function (socket) {

    socket.on(REQUEST, function (callback) {
        result = 'OK';
        callback(result);
    });
});

// Suppliers
// another socket server running on another instance

io.on('connection',function (socket) {

    socket.on(PRODUCTS, function (callback) {
        result = 'OK';
        callback(result);
    });
});
</code>```

As i know I cannot emit from one server to another if I don't have mapping between two.

How can I differentiate two types of users on single socket server. ? (then we have unique socket id and doesn't need mapping)

答:
Socket connection may take a parameter, assume its user_type. On the serverside you may get that parameter by:

```<code>io.sockets.on('connection', function (socket) {
    var user_type =socket.handshake.query.user_type;
}
</code>```

And on the client side you may initiate the connection like:

```<code>io.connect("<>"",{path:"/socket.io",query:"user_type=<your_user_type});
</code>```

And then you may do whatever you want for different types of users. You may connect them for different rooms, or keep an hashmap to get information about which socketid belongs to which usertype

Body:
I have two socket servers running on separate machine.

// Customers
io.on('connection', function (socket) {

    socket.on(REQUEST, function (callback) {
        result = 'OK';
        callback(result);
    });
});

// Suppliers
// another socket server running on another instance

io.on('connection',function (socket) {

    socket.on(PRODUCTS, function (callback) {
        result = 'OK';
        callback(result);
    });
});

As i know I cannot emit from one server to another if I don't have mapping between two.

How can I differentiate two types of users on single socket server. ? (then we have unique socket id and doesn't need mapping)

Body:
Socket connection may take a parameter, assume its user_type. On the serverside you may get that parameter by:

io.sockets.on('connection', function (socket) {
    var user_type =socket.handshake.query.user_type;
}

And on the client side you may initiate the connection like:

io.connect("<>"",{path:"/socket.io",query:"user_type=<your_user_type});

And then you may do whatever you want for different types of users. You may connect them for different rooms, or keep an hashmap to get information about which socketid belongs to which usertype


问:
alert box without ok button in jQuery
How to show alert box without "OK" button and close after 2 seconds</p>

```<code>setTimeout(function() {
  alert("$premium$");
}, 1);
</code>```

答: You cannot hide buttons from native JavaScript dialogs. Your options depends on frameworks you are using. You can create custom dialogs with jQuery UI, Bootstrap and many other frameworks.</p>

Title: alert box without ok button in jQuery

Body:
How to show alert box without "OK" button and close after 2 seconds

setTimeout(function() {
  alert("$premium$");
}, 1);


问:
How do I deal with event start time and end time?
I am having an Issue where I have to input Event start_date, start_time, end_date, and end_time in my development.

How do I deal with my database tables in such case? Am looking at outputting Date and Event Start Time as is in the picture below:

Here is what I have in my migration structure:

```<code>class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.datetime :start_date
      t.datetime :end_date

      t.timestamps
    end
  end
end
</code>```

How do I deal with event start time and end time?

答:
It's very straight forward. Create the table as per your migration. Then, store the date and time in start_date and end_date columns. Then when you want to display the values you have to use the strftime to format the values accordingly.

To get the date in dd/MM/YYYY format,

```<code>start_date.strftime('%d/%M/%YYYY')
</code>```

To get the time,

```<code>start_date.strftime("at %I:%M%p")
</code>```

Body:
I am having an Issue where I have to input Event start_date, start_time, end_date, and end_time in my development.

How do I deal with my database tables in such case? Am looking at outputting Date and Event Start Time as is in the picture below:

Here is what I have in my migration structure:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.datetime :start_date
      t.datetime :end_date

      t.timestamps
    end
  end
end

How do I deal with event start time and end time?

Body:
It's very straight forward. Create the table as per your migration. Then, store the date and time in start_date and end_date columns. Then when you want to display the values you have to use the strftime to format the values accordingly.

To get the date in dd/MM/YYYY format,

start_date.strftime('%d/%M/%YYYY')

To get the time,

start_date.strftime("at %I:%M%p")


问:
iOS | Can I use SiriKit to authenticate user with his/her voice?
I am brainstorming and came up with an idea of authenticating user with his/her voice. Googling around didn't give me anything I need. I've found some resources about voice authentication but can I do it with SiriKit? That's the question. So I'm here. Thank you.</p>

答:
After my googling and the help from @inspector_60 here are my conclusions for now:

To voice authentication you have to record voices and compare 2 recordings.

You cannot record voice and pass it to your app via SiriKit. So you cannot do voice authentication via SiriKit.

But you can record voice with a button click or something like that. Here is a SOQ : Compare audio files for "Voice Authentication"

Instead of voice authentication, you can make Siri ask for TouchID or FaceID authentication. The main problem here is (at least in my project) you cannot select which fingerprint / faceprint on the phone has permission. Ex: My phone has my and my GF's fingerprints. But I want to let the application authenticate with my fingerprints only. This is not achievable for now.


问:
How to handle external service failure in Open-Uri?
In my Rails app I am trying to fetch a number of currency exchange rates from an external service and store them in the cache:

```<code>require 'open-uri'

module ExchangeRate

  def self.all
    Rails.cache.fetch("exchange_rates", :expires_in => 24.hours) { load_all }
  end

  private

    def self.load_all
      hashes = {}
      CURRENCIES.each do |currency|
        begin
          hash = JSON.parse(open(URI("http://api.fixer.io/latest?base=#{currency}")).read) #what if not available?
          hashes[currency] = hash["rates"]
        rescue Timeout::Error
          puts "Timeout"
        rescue OpenURI::Error => e
          puts e.message
        end
      end
      hashes
    end

end
</code>```

This works great in development but I am worried about the production environment. How can I prevent the whole thing from being cached if the external service is not available? How can I ensure ExchangeRate.all always contains data, even if it's old and can't be updated due to an external service failure?

I tried to add some basic error handling but I'm afraid it's not enough.

答:
If you're worried about your external service not being reliable enough to keep up with caching every 24 hours, then you should disable the auto cache expiration, let users work with old data, and set up some kind of notification system to tell you if the load_all fails.

Here's what I'd do:

Assume ExchangeRate.all always returns a cached copy, with no expiration (this will return nil if no cache is found):

```<code>module ExchangeRate
  def self.all
    rates = Rails.cache.fetch("exchange_rates")
    UpdateCurrenciesJob.perform_later if rates.nil?
    rates
  end
end
</code>```

Create an ActiveJob that handles the updates on a regular basis:

```<code>class UpdateCurrenciesJob < ApplicationJob
  queue_as :default

  def perform(*_args)
    hashes = {}
    CURRENCIES.each do |currency|
      begin
        hash = JSON.parse(open(URI("http://api.fixer.io/latest?base=#{currency}")).read) # what if not available?
        hashes[currency] = hash['rates'].merge('updated_at' => Time.current)
      rescue Timeout::Error
        puts 'Timeout'
      rescue OpenURI::Error => e
        puts e.message
      end

      if hashes[currency].blank? || hashes[currency]['updated_at'] < Time.current - 24.hours
        # send a mail saying "this currency hasn't been updated"
      end
    end

    Rails.cache.write('exchange_rates', hashes)
  end
end
</code>```

Set the job up to run every few hours (4, 8, 12, less than 24). This way, the currencies will load in the background, the clients will always have data, and you will always know if currencies aren't working.

Body:
In my Rails app I am trying to fetch a number of currency exchange rates from an external service and store them in the cache:

require 'open-uri'

module ExchangeRate

  def self.all
    Rails.cache.fetch("exchange_rates", :expires_in => 24.hours) { load_all }
  end

  private

    def self.load_all
      hashes = {}
      CURRENCIES.each do |currency|
        begin
          hash = JSON.parse(open(URI("http://api.fixer.io/latest?base=#{currency}")).read) #what if not available?
          hashes[currency] = hash["rates"]
        rescue Timeout::Error
          puts "Timeout"
        rescue OpenURI::Error => e
          puts e.message
        end
      end
      hashes
    end

end

This works great in development but I am worried about the production environment. How can I prevent the whole thing from being cached if the external service is not available? How can I ensure ExchangeRate.all always contains data, even if it's old and can't be updated due to an external service failure?

I tried to add some basic error handling but I'm afraid it's not enough.

Body:
If you're worried about your external service not being reliable enough to keep up with caching every 24 hours, then you should disable the auto cache expiration, let users work with old data, and set up some kind of notification system to tell you if the load_all fails.

Here's what I'd do:

Assume ExchangeRate.all always returns a cached copy, with no expiration (this will return nil if no cache is found):

module ExchangeRate
  def self.all
    rates = Rails.cache.fetch("exchange_rates")
    UpdateCurrenciesJob.perform_later if rates.nil?
    rates
  end
end

Create an ActiveJob that handles the updates on a regular basis:

class UpdateCurrenciesJob < ApplicationJob
  queue_as :default

  def perform(*_args)
    hashes = {}
    CURRENCIES.each do |currency|
      begin
        hash = JSON.parse(open(URI("http://api.fixer.io/latest?base=#{currency}")).read) # what if not available?
        hashes[currency] = hash['rates'].merge('updated_at' => Time.current)
      rescue Timeout::Error
        puts 'Timeout'
      rescue OpenURI::Error => e
        puts e.message
      end

      if hashes[currency].blank? || hashes[currency]['updated_at'] < Time.current - 24.hours
        # send a mail saying "this currency hasn't been updated"
      end
    end

    Rails.cache.write('exchange_rates', hashes)
  end
end

Set the job up to run every few hours (4, 8, 12, less than 24). This way, the currencies will load in the background, the clients will always have data, and you will always know if currencies aren't working.


问:
Connecting to SAP Web Service from C# .NET application
I've written a Windows Application to test a connection to a clients SAP web services.  The web service call requires X509 certificate security.

After reading various articles on the internet I've come up with three ways to attach the X509 certificate to the web service call. Unfortunately all of these attempts return a '401 Unauthorised Access'. However, I can connect to the web service via the URL in IE.

Does anybody have any sugestions as to what I may be doing wrong?  I am using WSE 3.0 and the three methods I am using to attach the certificate are as follows:-

Certificate

```<code>X509Certificate2 oCert = GetSecurityCertificate(oCertificate);
svc.ClientCertificates.Add(oCert);
</code>```

Token

```<code>X509SecurityToken oToken = GetSecurityToken(oCertificate);
svc.RequestSoapContext.Security.Tokens.Add(oToken);
</code>```

Policy

```<code>SAPX509Assertion sapX509Assertion = new SAPX509Assertion(oCertificate, oStoreLocation, oStoreName, oFindType);
svc.SetPolicy(sapX509Assertion.Policy());
</code>```

GetSecurityToken() and GetSecuirtyCertificate both search the certificate store. The SAPX509Assertion does this:-

```<code>public SAPX509Assertion(String certSubject, StoreLocation oStoreLocation, StoreName oStoreName, X509FindType oFindType)
{
    ClientX509TokenProvider = new X509TokenProvider(oStoreLocation,
                                                     oStoreName, certSubject, oFindType);
    ServiceX509TokenProvider = new X509TokenProvider(oStoreLocation,
                                                     oStoreName, certSubject, oFindType);

    Protection.Request.EncryptBody = false;
    Protection.Response.EncryptBody = false;
}
</code>```

Update
OK, I have a WCF call now in place. I couldn't use the BasicHttpBinding method shown by Eugarps as it complained that I was connecting to a https address and expected http...which made sense. The code I now have is:-

```<code>var binding = new WSHttpBinding();
binding.MaxReceivedMessageSize = int.MaxValue;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Mode = SecurityMode.Transport;

WCFConnection.CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient client;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse response;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs data;
//Assign address
var address = new EndpointAddress(sUrl);

//Create service client
client = new CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient(binding, address);

//Assign credentials
client.ClientCredentials.UserName.UserName = sUserName;
client.ClientCredentials.UserName.Password = sPassword;

response = new CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse();
data = new WCFConnection.CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs();

response = client.ZfhhrGbbapiZgeeamsCreateabs(data);
</code>```

It's still failing to connect to the SAP web service. The error I am receiving is "The HTTP request is unauthorized with client authentication scheme 'Negotiate'". I've also tried using

```<code>binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
</code>```

which returned a similar error.

Does anybody have any further suggestions or ideas of where I am going wrong?

答:
I've faced the same problem and it seems I've found the sollution here: http://ddkonline.blogspot.com/2009/08/calling-sap-pi-web-service-using-wcf.html.

```<code>        CustomBinding binding = new CustomBinding();
        binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
        HttpsTransportBindingElement transport = new HttpsTransportBindingElement();
        transport.AuthenticationScheme = AuthenticationSchemes.Basic;
        //transport.ProxyAuthenticationScheme = AuthenticationSchemes.Basic;
        transport.Realm = "XISOAPApps";
        binding.Elements.Add(transport);
        var address = new EndpointAddress("https://foooo");
        ........ create client proxy class

        service.ClientCredentials.UserName.UserName = "<login>";
        service.ClientCredentials.UserName.Password = "<password>";
</code>```

Unfortunatelly I'm not able to use WCF in my application, I have to stick with .NET 2.0 and WSE 3.0, and I wounder if anybody was able to find sollution to that?

Body:
I've written a Windows Application to test a connection to a clients SAP web services.  The web service call requires X509 certificate security.

After reading various articles on the internet I've come up with three ways to attach the X509 certificate to the web service call. Unfortunately all of these attempts return a '401 Unauthorised Access'. However, I can connect to the web service via the URL in IE.

Does anybody have any sugestions as to what I may be doing wrong?  I am using WSE 3.0 and the three methods I am using to attach the certificate are as follows:-

Certificate

X509Certificate2 oCert = GetSecurityCertificate(oCertificate);
svc.ClientCertificates.Add(oCert);

Token

X509SecurityToken oToken = GetSecurityToken(oCertificate);
svc.RequestSoapContext.Security.Tokens.Add(oToken);

Policy

SAPX509Assertion sapX509Assertion = new SAPX509Assertion(oCertificate, oStoreLocation, oStoreName, oFindType);
svc.SetPolicy(sapX509Assertion.Policy());

GetSecurityToken() and GetSecuirtyCertificate both search the certificate store. The SAPX509Assertion does this:-

public SAPX509Assertion(String certSubject, StoreLocation oStoreLocation, StoreName oStoreName, X509FindType oFindType)
{
    ClientX509TokenProvider = new X509TokenProvider(oStoreLocation,
                                                     oStoreName, certSubject, oFindType);
    ServiceX509TokenProvider = new X509TokenProvider(oStoreLocation,
                                                     oStoreName, certSubject, oFindType);

    Protection.Request.EncryptBody = false;
    Protection.Response.EncryptBody = false;
}

Update
OK, I have a WCF call now in place. I couldn't use the BasicHttpBinding method shown by Eugarps as it complained that I was connecting to a https address and expected http...which made sense. The code I now have is:-

var binding = new WSHttpBinding();
binding.MaxReceivedMessageSize = int.MaxValue;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Mode = SecurityMode.Transport;

WCFConnection.CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient client;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse response;
CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs data;
//Assign address
var address = new EndpointAddress(sUrl);

//Create service client
client = new CreateAbsenceWSlow.ZWSDHTM_GB_AMS_CREATEABS_lowClient(binding, address);

//Assign credentials
client.ClientCredentials.UserName.UserName = sUserName;
client.ClientCredentials.UserName.Password = sPassword;

response = new CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabsResponse();
data = new WCFConnection.CreateAbsenceWSlow.ZfhhrGbbapiZgeeamsCreateabs();

response = client.ZfhhrGbbapiZgeeamsCreateabs(data);

It's still failing to connect to the SAP web service. The error I am receiving is "The HTTP request is unauthorized with client authentication scheme 'Negotiate'". I've also tried using

binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

which returned a similar error.

Does anybody have any further suggestions or ideas of where I am going wrong?

Body:
I've faced the same problem and it seems I've found the sollution here: http://ddkonline.blogspot.com/2009/08/calling-sap-pi-web-service-using-wcf.html.

        CustomBinding binding = new CustomBinding();
        binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
        HttpsTransportBindingElement transport = new HttpsTransportBindingElement();
        transport.AuthenticationScheme = AuthenticationSchemes.Basic;
        //transport.ProxyAuthenticationScheme = AuthenticationSchemes.Basic;
        transport.Realm = "XISOAPApps";
        binding.Elements.Add(transport);
        var address = new EndpointAddress("https://foooo");
        ........ create client proxy class

        service.ClientCredentials.UserName.UserName = "<login>";
        service.ClientCredentials.UserName.Password = "<password>";

Unfortunatelly I'm not able to use WCF in my application, I have to stick with .NET 2.0 and WSE 3.0, and I wounder if anybody was able to find sollution to that?


问:
Can Override an observableCollection property in c#?
How can I override an ObservableCollection property of a parent ?

I have a base class

```<code>abstract class Base
{
    public virtual ObservableCollection<AnotherBaseClass> items
    {
        get { throw new NotImplementedException(); }
    }
}
</code>```

and a child class

```<code>class Derived : Base
{
     public override ObservableCollection<AnotherDerivedFromAnotherBaseClass> items
     {
         get { //some stuff }
     }
}
</code>```

If I do it like that compiler will say : Items must be ObservableCollection<AnotherBaseClass> to match overriden member Base.Items

My AnotherDerivedFromAnotherBaseClass class is herited from AnotherBaseClass so why I can't do that ?

How can I override this property and keep the constraint of the good item type in the child ?

答:
My AnotherDerivedFromAnotherBaseClass class is inherited from AnotherBaseClass so why I can't do that ?

Because a List<Sheep> isn't a List<Animal>. It might seem so if you read from them, but you forgot half their power: inserting. Just imagine it were:

```<code>List<Sheep> sheep = new List<Sheep>();

// this does not work and for a good reason:
List<Animal> animals = sheep;

// whoopsie... a wolf is an animal, but it should never
// be able to be inserted into a list of sheep like this:
animals.Insert(new Wolf());
</code>```

So no, your ObservableCollection<Derived> simply isn't a ObservableCollection<Base> and you cannot use it as a replacement in inheritance/overriding.

So what can you do?

Well, first, what is wrong with keeping the base class signature? It's still valid. The only problem is that one could insert another derived class. Maybe have an IEnumerable<Base> instead of a real list?

Or you could have a second property with the first making a copy of it... not exactly elegant, but it works:

```<code>class Derived : Base
{
     public override ObservableCollection<ItemBase> items
     {
         get { return new ObservableCollection<ItemBase>(SpecificItems); }
     }

     public ObservableCollection<ItemDerived> SpecificItems
     {
         get { //some stuff }
     }
}
</code>```

Body:
How can I override an ObservableCollection property of a parent ?

I have a base class

abstract class Base
{
    public virtual ObservableCollection<AnotherBaseClass> items
    {
        get { throw new NotImplementedException(); }
    }
}

and a child class

class Derived : Base
{
     public override ObservableCollection<AnotherDerivedFromAnotherBaseClass> items
     {
         get { //some stuff }
     }
}

If I do it like that compiler will say : Items must be ObservableCollection<AnotherBaseClass> to match overriden member Base.Items

My AnotherDerivedFromAnotherBaseClass class is herited from AnotherBaseClass so why I can't do that ?

How can I override this property and keep the constraint of the good item type in the child ?

Body:
My AnotherDerivedFromAnotherBaseClass class is inherited from AnotherBaseClass so why I can't do that ?

Because a List<Sheep> isn't a List<Animal>. It might seem so if you read from them, but you forgot half their power: inserting. Just imagine it were:

List<Sheep> sheep = new List<Sheep>();

// this does not work and for a good reason:
List<Animal> animals = sheep;

// whoopsie... a wolf is an animal, but it should never
// be able to be inserted into a list of sheep like this:
animals.Insert(new Wolf());

So no, your ObservableCollection<Derived> simply isn't a ObservableCollection<Base> and you cannot use it as a replacement in inheritance/overriding.

So what can you do?

Well, first, what is wrong with keeping the base class signature? It's still valid. The only problem is that one could insert another derived class. Maybe have an IEnumerable<Base> instead of a real list?

Or you could have a second property with the first making a copy of it... not exactly elegant, but it works:

class Derived : Base
{
     public override ObservableCollection<ItemBase> items
     {
         get { return new ObservableCollection<ItemBase>(SpecificItems); }
     }

     public ObservableCollection<ItemDerived> SpecificItems
     {
         get { //some stuff }
     }
}


问:
EJB and the Web Tier
I am learning EJB and to do that I bought a book name EJB 3 Developer Guides.  I got some understanding on how EJB architecture is and how it works.  The book does well in explaining this.

But the examples in the book are all run through ant task.  I basically wanted to learn how EJB's are being used in conjunction with Servlets and JSP.  Some sort of a web client accessing a JSP page and a servlet getting the service of an EJB bean?

Any idea how can I move forward learning how to use EJB with the Web Tier?  Tutorials or links would be better or is there any other book that I could read?

Thanks.

答:
Important note: if you try running the "Simple EJB3 Servlet Application" from the link about be sure you are using an appropriate version of Glassfish. It might work on JBoss 5.x - but I've never tested it (according to JBoss).
You won't be able to run on the sample application on older versions of JBoss (like 4.2.x) without some workarounds - like ones I described in one of my posts: sample application

The Netbeans tutorial seems fine - but stick to the environment and platform they are describing - otherwise you might quickly discourage and give up.

--Jakub

Title: EJB and the Web Tier