问:
Performance issue when using random generator inside a class
My aim is to create a wrapper around Boost uniform real distribution with Mersenne Twister in order to make it available in a library. So I created a basic class like this:

```<code>class mt19937
{
protected:
   boost::random::mt19937 gen_;
   boost::random::uniform_real_distribution<double> real_;
public:
   mt19937(unsigned long s = 5489UL) : gen_(s), real_(0., 1.) {};
   double get() { return real_(gen_); };
};
</code>```

Running a performance test though, I found out that my class is much slower than a direct call to Boost ojects. In fact, the following code which samples 10 billions of numbers, takes on my machine 30s:

```<code>constexpr unsigned long seed = 5489UL;
constexpr size_t iter = 100000;
double x = 0.;

boost::random::mt19937 gen(seed);
boost::random::uniform_real_distribution<double> real(0., 1.);

for (size_t i = 0; i < iter; ++i)
   for (size_t j = 0; j < iter; ++j)
      x = real(gen);
</code>```

The class mt19937 described above, with the following code, takes around 70s:

```<code>mt19937 stduniform(seed);

for (size_t i = 0; i < iter; ++i)
   for (size_t j = 0; j < iter; ++j)
      x = stduniform.get();
</code>```

Looking at assembler in Windows, in the first case the code executed for x = real(gen) is the following, which seems to me just the call to boost::random::detail::generate_uniform_real and the assignment to x:

```<code>00007FF6D14639F0  movzx       r9d,byte ptr [r15]
00007FF6D14639F4  lea         rcx,[gen]
00007FF6D14639F9  movaps      xmm2,xmm7
00007FF6D14639FC  movaps      xmm1,xmm8
00007FF6D1463A00  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D146141Ah)
</code>```

With the function get() I see the following istructions - it seems to perform some operations on registers that I cannot explain and a jump:

```<code>00007FF6D1463B61  movsd       xmm3,mmword ptr [rbp+900h]
00007FF6D1463B69  lea         rcx,[stduniform]
00007FF6D1463B6E  movsd       xmm4,mmword ptr [rbp+8F8h]
00007FF6D1463B76  movaps      xmm2,xmm3
00007FF6D1463B79  mulsd       xmm2,xmm6
00007FF6D1463B7D  movaps      xmm1,xmm4
00007FF6D1463B80  mulsd       xmm1,xmm6
00007FF6D1463B84  movaps      xmm0,xmm2
00007FF6D1463B87  subsd       xmm0,xmm1
00007FF6D1463B8B  comisd      xmm0,xmm7
00007FF6D1463B8F  jbe         main+2F8h (07FF6D1463B98h)
00007FF6D1463B91  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D14615D7h)
00007FF6D1463B96  jmp         main+307h (07FF6D1463BA7h)
00007FF6D1463B98  movzx       r9d,byte ptr [rbx]
00007FF6D1463B9C  movaps      xmm2,xmm3
00007FF6D1463B9F  movaps      xmm1,xmm4
00007FF6D1463BA2  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D146141Ah)
</code>```

Is it possible that a call to a function (that should be inlined) performed 10 billions of times can add this overhead? Do you have any suggestion about the code to increase performance?

I am working in Windows environment and using the compiler vc14 of VisualStudio2015, with Boost 1.7.1. I observed a similar behaviour with gcc4.9 on a Linux machine, where the direct call to Boost takes 30s and the new class takes 45s.

Thanks a lot for your time.

答:
The "some operations on registers I cannot explain" bit you highlighted:

```<code>00007FF6D1463B61  movsd       xmm3,mmword ptr [rbp+900h]
00007FF6D1463B69  lea         rcx,[stduniform]
00007FF6D1463B6E  movsd       xmm4,mmword ptr [rbp+8F8h]
00007FF6D1463B76  movaps      xmm2,xmm3
00007FF6D1463B79  mulsd       xmm2,xmm6
00007FF6D1463B7D  movaps      xmm1,xmm4
00007FF6D1463B80  mulsd       xmm1,xmm6
00007FF6D1463B84  movaps      xmm0,xmm2
00007FF6D1463B87  subsd       xmm0,xmm1
00007FF6D1463B8B  comisd      xmm0,xmm7
00007FF6D1463B8F  jbe         main+2F8h (07FF6D1463B98h)
</code>```

seems to match up with the following lines in generate_uniform_real:

```<code>T result = numerator / divisor * (max_value - min_value) + min_value;
if(result < max_value) return result;
</code>```

So it seems like the compiler is unable to inline the min_value and max_value arguments to this function.

For what it's worth, I could not reproduce a significant performance difference on:

Apple clang version 11.0.0 (clang-1100.0.33.17)

Boost 1.69.0_2

Body:
My aim is to create a wrapper around Boost uniform real distribution with Mersenne Twister in order to make it available in a library. So I created a basic class like this:

class mt19937
{
protected:
   boost::random::mt19937 gen_;
   boost::random::uniform_real_distribution<double> real_;
public:
   mt19937(unsigned long s = 5489UL) : gen_(s), real_(0., 1.) {};
   double get() { return real_(gen_); };
};

Running a performance test though, I found out that my class is much slower than a direct call to Boost ojects. In fact, the following code which samples 10 billions of numbers, takes on my machine 30s:

constexpr unsigned long seed = 5489UL;
constexpr size_t iter = 100000;
double x = 0.;

boost::random::mt19937 gen(seed);
boost::random::uniform_real_distribution<double> real(0., 1.);

for (size_t i = 0; i < iter; ++i)
   for (size_t j = 0; j < iter; ++j)
      x = real(gen);

The class mt19937 described above, with the following code, takes around 70s:

mt19937 stduniform(seed);

for (size_t i = 0; i < iter; ++i)
   for (size_t j = 0; j < iter; ++j)
      x = stduniform.get();

Looking at assembler in Windows, in the first case the code executed for x = real(gen) is the following, which seems to me just the call to boost::random::detail::generate_uniform_real and the assignment to x:

00007FF6D14639F0  movzx       r9d,byte ptr [r15]
00007FF6D14639F4  lea         rcx,[gen]
00007FF6D14639F9  movaps      xmm2,xmm7
00007FF6D14639FC  movaps      xmm1,xmm8
00007FF6D1463A00  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D146141Ah)

With the function get() I see the following istructions - it seems to perform some operations on registers that I cannot explain and a jump:

00007FF6D1463B61  movsd       xmm3,mmword ptr [rbp+900h]
00007FF6D1463B69  lea         rcx,[stduniform]
00007FF6D1463B6E  movsd       xmm4,mmword ptr [rbp+8F8h]
00007FF6D1463B76  movaps      xmm2,xmm3
00007FF6D1463B79  mulsd       xmm2,xmm6
00007FF6D1463B7D  movaps      xmm1,xmm4
00007FF6D1463B80  mulsd       xmm1,xmm6
00007FF6D1463B84  movaps      xmm0,xmm2
00007FF6D1463B87  subsd       xmm0,xmm1
00007FF6D1463B8B  comisd      xmm0,xmm7
00007FF6D1463B8F  jbe         main+2F8h (07FF6D1463B98h)
00007FF6D1463B91  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D14615D7h)
00007FF6D1463B96  jmp         main+307h (07FF6D1463BA7h)
00007FF6D1463B98  movzx       r9d,byte ptr [rbx]
00007FF6D1463B9C  movaps      xmm2,xmm3
00007FF6D1463B9F  movaps      xmm1,xmm4
00007FF6D1463BA2  call        boost::random::detail::generate_uniform_real<boost::random::mersenne_twister_engine<unsigned int,32,624,397,31,2567483615,11,4294967295,7,2636928640,15,4022730752,18,1812433253>,double> (07FF6D146141Ah)

Is it possible that a call to a function (that should be inlined) performed 10 billions of times can add this overhead? Do you have any suggestion about the code to increase performance?

I am working in Windows environment and using the compiler vc14 of VisualStudio2015, with Boost 1.7.1. I observed a similar behaviour with gcc4.9 on a Linux machine, where the direct call to Boost takes 30s and the new class takes 45s.

Thanks a lot for your time.

Body:
The "some operations on registers I cannot explain" bit you highlighted:

00007FF6D1463B61  movsd       xmm3,mmword ptr [rbp+900h]
00007FF6D1463B69  lea         rcx,[stduniform]
00007FF6D1463B6E  movsd       xmm4,mmword ptr [rbp+8F8h]
00007FF6D1463B76  movaps      xmm2,xmm3
00007FF6D1463B79  mulsd       xmm2,xmm6
00007FF6D1463B7D  movaps      xmm1,xmm4
00007FF6D1463B80  mulsd       xmm1,xmm6
00007FF6D1463B84  movaps      xmm0,xmm2
00007FF6D1463B87  subsd       xmm0,xmm1
00007FF6D1463B8B  comisd      xmm0,xmm7
00007FF6D1463B8F  jbe         main+2F8h (07FF6D1463B98h)

seems to match up with the following lines in generate_uniform_real:

T result = numerator / divisor * (max_value - min_value) + min_value;
if(result < max_value) return result;

So it seems like the compiler is unable to inline the min_value and max_value arguments to this function.

For what it's worth, I could not reproduce a significant performance difference on:

Apple clang version 11.0.0 (clang-1100.0.33.17)

Boost 1.69.0_2


来源: stackexchange

问:
Slow iteration through elements in WatiN
I'm writing an application with Watin. Its great, but running a performance analysis on my program, over 50% of execution time is spent looping through lists of elements.

For example:
    foreach (TextField bT in browser.TextFields)
    {

Is very slow.

I seem to remember seeing somewhere there is a faster way of doing this in WatiN, but unfortunately I can't find the page again.

Accessing the number of elements also seems to be slow, eg;
    browser.CheckBoxes.Count

Thanks for any tips,
Chris

答:
Thanks Dahv for a really detailed answer. In my case I've sped up my tests by about 10x using a number of tricks, some similar to yours:

Refining scope as you and prostynick (in my case using Form1.TextField  etc.)

First checking if browser.html matches my regex before seeing if
fields do

Using the GehSoft.PRCE RegEx wrapper - its native code regex
matching is far faster than .NET's for small haystacks. So to find a TextField I'd do:

```<code>    Gehtsoft.PCRE.Regex regexString = new Gehtsoft.PCRE.Regex("[Nn]ame");
      foreach (TextField bT in browser.TextFields)
                    {
                        //Skip if no match
                        if (!regexString.Execute(bT.Name).Success) continue;
</code>```

Before I was looping on a list of regexes, then inside that i was looping on TextFields. Making the TextFields loop the top loop improved speed about 3x.

ContentLicense: CC BY-SA 3.0

Body:
Thanks Dahv for a really detailed answer. In my case I've sped up my tests by about 10x using a number of tricks, some similar to yours:

Refining scope as you and prostynick (in my case using Form1.TextField  etc.)

First checking if browser.html matches my regex before seeing if
fields do

Using the GehSoft.PRCE RegEx wrapper - its native code regex
matching is far faster than .NET's for small haystacks. So to find a TextField I'd do:

    Gehtsoft.PCRE.Regex regexString = new Gehtsoft.PCRE.Regex("[Nn]ame");
      foreach (TextField bT in browser.TextFields)
                    {
                        //Skip if no match
                        if (!regexString.Execute(bT.Name).Success) continue;

Before I was looping on a list of regexes, then inside that i was looping on TextFields. Making the TextFields loop the top loop improved speed about 3x.


问:
Swift apply .uppercaseString to only the first letter of a string
I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use

```<code>nameOfString[0]
</code>```

but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?

Thanks for any help!

答:
Add this line in viewDidLoad() method.   </p>

```<code> txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words
</code>```

Body:
I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use

nameOfString[0]

but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?

Thanks for any help!

Body:
Add this line in viewDidLoad() method.

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words

ContentLicense: CC BY-SA 4.0


问:
jQuery - Compare data-attr to search term
I am trying to compare a data-attribute to a search term like so:

```<code>var searchArea = $('#indexContainer');
var searchVal = $('#search').val();
var items = $('.processLink');

var links;

$('#search').keyup(function() {
  // on search input key up

  //for each .processLink
  $.each(items, function(index, value) {
    //get the selector
    var selected = $(value);

    //get the keywords
    var keywords = selected.data('keywords');

    //console.log(selected.attr('id'));

    $("#" + selected.attr('id') + ":contains('" + searchVal + "')").css("text-decoration", "underline");
  });

});
</code>```

so if I have a few divs like these

```<code><div id="div1" class="processLink" data-keywords="div one cat dog"></div>
<div id="div2" class="processLink" data-keywords="div blade cow horse"></div>
<div id="div3" class="processLink" data-keywords="div camera bag"></div>
<div id="div4" class="processLink" data-keywords="div"></div>
</code>```

Then I just want to check on the key up whether the search term entered in to
search input matches any of the terms in data-keyword attribute and if they do then only show the .processLink divs which have the related words and hide the rest. I know I currently have it trying to underline, that was just a test

Hopefully that makes some kind of sense

答: $('.classname tagname[data-id=' + vlaue + ']').parent().addClass("addclassname");</p>

Body:
I am trying to compare a data-attribute to a search term like so:

var searchArea = $('#indexContainer');
var searchVal = $('#search').val();
var items = $('.processLink');

var links;

$('#search').keyup(function() {
  // on search input key up

  //for each .processLink
  $.each(items, function(index, value) {
    //get the selector
    var selected = $(value);

    //get the keywords
    var keywords = selected.data('keywords');

    //console.log(selected.attr('id'));

    $("#" + selected.attr('id') + ":contains('" + searchVal + "')").css("text-decoration", "underline");
  });

});

so if I have a few divs like these

Then I just want to check on the key up whether the search term entered in to
search input matches any of the terms in data-keyword attribute and if they do then only show the .processLink divs which have the related words and hide the rest. I know I currently have it trying to underline, that was just a test

Hopefully that makes some kind of sense


问:
Search into pandas dataframe column for which input value is smaller than the next index column value
I want to search a dataframe to find a value correspond to index row and column value. However, I am struggling because the column header values are the upper bound of a range where the previous column header value is the lower bound ( but the uppper bound of its other neightbor column value).

I cannot find a way to match my input with the column corresponding to the lower bound of the range.

with an example it is very easy to see:

```<code>data_frame_test = pd.DataFrame({'location' : [1, 2, 'S'],
                                '200' : [342, 690, 103],
                                '1000' : [322, 120, 193],
                                '2000' : [249, 990, 403]})

data_frame_test = data_frame_test.set_index('location')
</code>```

and what I want to do is this

```<code>location = 1
weight = 500

output = data_frame_test.iloc[1][??] #must be equal to 342
</code>```

see, the column where weight must look into is 200, because it is in the range between ]200;1000[. I don't know what else to try to translate that into python code. Any help would be greatly appreciated.

答:
You can make a custom function which will iterate over columns to check correct column and then return cell of that location:</p>

```<code>def get_val(location, weight, df):
    col = df.columns[0]
    for c in df.columns:
        if weight >= int(c):
            col = c
        else:
            break
    return df.loc[location, col]
get_val(1, 500, data_frame_test)
</code>```

Body:
I want to search a dataframe to find a value correspond to index row and column value. However, I am struggling because the column header values are the upper bound of a range where the previous column header value is the lower bound ( but the uppper bound of its other neightbor column value).

I cannot find a way to match my input with the column corresponding to the lower bound of the range.

with an example it is very easy to see:

data_frame_test = pd.DataFrame({'location' : [1, 2, 'S'],
                                '200' : [342, 690, 103],
                                '1000' : [322, 120, 193],
                                '2000' : [249, 990, 403]})

data_frame_test = data_frame_test.set_index('location')

and what I want to do is this

location = 1
weight = 500

output = data_frame_test.iloc[1][??] #must be equal to 342

see, the column where weight must look into is 200, because it is in the range between ]200;1000[. I don't know what else to try to translate that into python code. Any help would be greatly appreciated.

Body:
You can make a custom function which will iterate over columns to check correct column and then return cell of that location:

def get_val(location, weight, df):
    col = df.columns[0]
    for c in df.columns:
        if weight >= int(c):
            col = c
        else:
            break
    return df.loc[location, col]
get_val(1, 500, data_frame_test)


问:
Set SQL SERVER Express 2017 to allow remote connections
Just recovering my server from a major crash, which led to windows server 2016 being re-installed...

I have a desktop application which connects to the sql server database, trouble is now I have the database setup on the server I cant remember how to make it available to external sources (the application)

Can you help?

答:
Use the following steps to enable remote connections to your SQL Server,

Open SQL Server Management Studio.

Right-click your server's name and select Properties.

Select  Connections option

Tick the checkbox "Allow remote connections to this server."

Select OK.

Enable TCP/IP and Open 1433 port

Take SQL Server Configuration Manager.

Select SQLServer network Configuration->Protocols for MSSQLServer

In the right-hand pane,make sure that TCP/IP is Enabled.

Right click on TCP/IP and select the Properties option.

In the TCP/IP Properties dialog select the IP Addresses tab and scroll down to IPAII.

Make sure that the TCP Port is 1433.

Configure a Windows Firewall for Database Engine Access

Take Windows Administrative tools

From Administrative Tools select the Windows Firewall with Advanced Security option

In the Windows Firewall with Advanced Security dialog, click on the Inbound Rules option and select the New Rule command

In the New Inbound Rule wizard select the Port option and click Next

In the Protocols and Ports window specify the protocols and ports to which a rule applies. Select the TCP option, in the Specific local ports text box enter the 1433 port, and click Next

In the Action window select the Allow the connection to specify the action to be taken when a connection matches the conditions specified in the rule

Specify the profiles for which the rule applies in the Profile window, and click Next

In the last window specify the name of the created rule and click the Finish button

Configure remote access on a named instance of SQL Server

Take Windows Administrative tools

From Administrative Tools select Windows Firewall with Advanced Security option

In the Windows Firewall with Advanced Security dialog, click on the Inbound Rules option and select the New Rule command

In the New Inbound Rule wizard select the Port option and click Next

In the Protocols and Ports window specify the protocols and ports to which a rule applies. Select the TCP option, in the Specific local ports text box enter the 1433 port, and click Next

In the Action window select the Allow the connection to specify the action to be taken when a connection matches the conditions specified in the rule

Specify the profiles for which the rule applies in the Profile window, and click Next

In the last window specify the name of the created rule and click the Finish button


问:
Firebase admin SDK not working on Cloud Scheduler (PubSub)
I have an app and I want to update weather details on every 5 minutes. I build a PubSub function on Google cloud function to get weather details from weatherstack.com website and then I'm trying to save the result on FireStore using Admin SDK.
The weather API working perfectly but the function that writes the data to FireStore not triggered.

My code:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const requestApi = require('request');

admin.initializeApp();

exports.WeatherPubSub = (event, context) => {

    requestApi({
        url: 'http://api.weatherstack.com/current?access_key=XXXXXXXXXXXXXXXXXXXX&query=XXXXX',
        method: "POST"
    }, (error, response, body) => {
        //console.log(JSON.parse(body));
        if (error) {
            console.log('error:', error); // Print the error if one occurred
        } else {
            console.log("=> "+ response.statusCode);
            //Call firestore to update weather data
            return admin.firestore().collection('settings').doc('weather').update({
                temperature: body.current['temperature'],
                humidity: body.current['humidity'],
                weather_descriptions: body.current['weather_descriptions'][0]
            }).then(function() {
                console.log('Done!');
            });
        }

    });

  //return null;
};
</code>```

package.json

```<code>{
  "name": "functions",
  "version": "0.0.2",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "dependencies": {
    "@google-cloud/pubsub": "^1.5.0",
    "firebase-admin": "^8.9.2",
    "firebase-functions": "^3.3.0",
    "request": "^2.88.2"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.1.6"
  },
  "private": true
}

</code>```

答:
You must return a promise that resolves when all the asynchronous work in your Cloud Function is complete (i.e. call to the weatherstack API and Firestore update() method).

This is explained in the official Firebase video series here. In particular watch the three videos titled "Learn JavaScript Promises" (Parts 2 & 3 especially focus on background triggered Cloud Functions, but it really worth watching Part 1 before).

The request library you are using supports callback interfaces natively but does not return a promise.

You can use the request-promise library and the rp() method which "returns a regular Promises/A+ compliant promise" and then adapt your code as follows:

```<code> //.....
 var options = {
        method: 'POST',
        uri: 'http://api.weatherstack.com/current?access_key=XXXXXXXXXXXXXXXXXXXX&query=XXXXX'
 };

return rp(options)
.then(body => {
       return admin.firestore().collection('settings').doc('weather').update({
                temperature: body.current['temperature'],
                humidity: body.current['humidity'],
                weather_descriptions: body.current['weather_descriptions'][0]
            }
})
.catch(err => {
    console.log(err);
    return null;
});
 //.....
</code>```

Also, you should double-check that the way you declare you cloud Function (exports.WeatherPubSub = (event, context) => {...}) is correct. It does not seem to be the case, see the doc for more details.

Body:
I have an app and I want to update weather details on every 5 minutes. I build a PubSub function on Google cloud function to get weather details from weatherstack.com website and then I'm trying to save the result on FireStore using Admin SDK.
The weather API working perfectly but the function that writes the data to FireStore not triggered.

My code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const requestApi = require('request');

admin.initializeApp();

exports.WeatherPubSub = (event, context) => {

    requestApi({
        url: 'http://api.weatherstack.com/current?access_key=XXXXXXXXXXXXXXXXXXXX&query=XXXXX',
        method: "POST"
    }, (error, response, body) => {
        //console.log(JSON.parse(body));
        if (error) {
            console.log('error:', error); // Print the error if one occurred
        } else {
            console.log("=> "+ response.statusCode);
            //Call firestore to update weather data
            return admin.firestore().collection('settings').doc('weather').update({
                temperature: body.current['temperature'],
                humidity: body.current['humidity'],
                weather_descriptions: body.current['weather_descriptions'][0]
            }).then(function() {
                console.log('Done!');
            });
        }

    });

  //return null;
};

package.json

{
  "name": "functions",
  "version": "0.0.2",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "dependencies": {
    "@google-cloud/pubsub": "^1.5.0",
    "firebase-admin": "^8.9.2",
    "firebase-functions": "^3.3.0",
    "request": "^2.88.2"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.1.6"
  },
  "private": true
}

Body:
You must return a promise that resolves when all the asynchronous work in your Cloud Function is complete (i.e. call to the weatherstack API and Firestore update() method).

This is explained in the official Firebase video series here. In particular watch the three videos titled "Learn JavaScript Promises" (Parts 2 & 3 especially focus on background triggered Cloud Functions, but it really worth watching Part 1 before).

The request library you are using supports callback interfaces natively but does not return a promise.

You can use the request-promise library and the rp() method which "returns a regular Promises/A+ compliant promise" and then adapt your code as follows:

 //.....
 var options = {
        method: 'POST',
        uri: 'http://api.weatherstack.com/current?access_key=XXXXXXXXXXXXXXXXXXXX&query=XXXXX'
 };

return rp(options)
.then(body => {
       return admin.firestore().collection('settings').doc('weather').update({
                temperature: body.current['temperature'],
                humidity: body.current['humidity'],
                weather_descriptions: body.current['weather_descriptions'][0]
            }
})
.catch(err => {
    console.log(err);
    return null;
});
 //.....

Also, you should double-check that the way you declare you cloud Function (exports.WeatherPubSub = (event, context) => {...}) is correct. It does not seem to be the case, see the doc for more details.


问:
Python write both commands and their output to a file
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')
</code>```

Now if I want to capture its output only I know I can just do:

```<code>python3 outtest.py > outtest.txt
</code>```

However, this will only give me an outtest.txt file with e.g.:

```<code>mean: 0.34
median: 0.27
</code>```

What I'm looking for is a way to get an output file like:

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27
</code>```

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

Body:
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')

Now if I want to capture its output only I know I can just do:

python3 outtest.py > outtest.txt

However, this will only give me an outtest.txt file with e.g.:

mean: 0.34
median: 0.27

What I'm looking for is a way to get an output file like:

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

Body:
Here's a script I just wrote which quite comprehensively captures printed output and prints it alongside the code, no matter how it's printed or how much is printed in one go. It uses the ast module to parse the Python source, executes the program one statement at a time (kind of as if it was fed to the REPL), then prints the output from each statement. Python 3.6+ (but easily modified for e.g. Python 2.x):

import ast
import sys

if len(sys.argv) < 2:
    print(f"Usage: {sys.argv[0]} <script.py> [args...]")
    exit(1)

# Replace stdout so we can mix program output and source code cleanly
real_stdout = sys.stdout
class FakeStdout:
    ''' A replacement for stdout that prefixes # to every line of output, so it can be mixed with code. '''
    def __init__(self, file):
        self.file = file
        self.curline = ''

    def _writerow(self, row):
        self.file.write('# ')
        self.file.write(row)
        self.file.write('\n')

    def write(self, text):
        if not text:
            return
        rows = text.split('\n')
        self.curline += rows.pop(0)
        if not rows:
            return
        for row in rows:
            self._writerow(self.curline)
            self.curline = row

    def flush(self):
        if self.curline:
            self._writerow(self.curline)
            self.curline = ''

sys.stdout = FakeStdout(real_stdout)

class EndLineFinder(ast.NodeVisitor):
    ''' This class functions as a replacement for the somewhat unreliable end_lineno attribute.

    It simply finds the largest line number among all child nodes. '''

    def __init__(self):
        self.max_lineno = 0

    def generic_visit(self, node):
        if hasattr(node, 'lineno'):
            self.max_lineno = max(self.max_lineno, node.lineno)
        ast.NodeVisitor.generic_visit(self, node)

# Pretend the script was called directly
del sys.argv[0]

# We'll walk each statement of the file and execute it separately.
# This way, we can place the output for each statement right after the statement itself.
filename = sys.argv[0]
source = open(filename, 'r').read()
lines = source.split('\n')
module = ast.parse(source, filename)
env = {'__name__': '__main__'}

prevline = 0
endfinder = EndLineFinder()

for stmt in module.body:
    # note: end_lineno will be 1-indexed (but it's always used as an endpoint, so no off-by-one errors here)
    endfinder.visit(stmt)
    end_lineno = endfinder.max_lineno
    for line in range(prevline, end_lineno):
        print(lines[line], file=real_stdout)
    prevline = end_lineno
    # run a one-line "module" containing only this statement
    exec(compile(ast.Module([stmt]), filename, 'exec'), env)
    # flush any incomplete output (FakeStdout is "line-buffered")
    sys.stdout.flush()

Here's a test script:

print(3); print(4)
print(5)

if 1:
    print(6)

x = 3
for i in range(6):
    print(x + i)

import sys
sys.stdout.write('I love Python')

import pprint
pprint.pprint({'a': 'b', 'c': 'd'}, width=5)

and the result:

print(3); print(4)
# 3
# 4
print(5)
# 5

if 1:
    print(6)
# 6

x = 3
for i in range(6):
    print(x + i)
# 3
# 4
# 5
# 6
# 7
# 8

import sys
sys.stdout.write('I love Python')
# I love Python

import pprint
pprint.pprint({'a': 'b', 'c': 'd'}, width=5)
# {'a': 'b',
#  'c': 'd'}


问:
jQuery add class based on parent URL
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

```<code>var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});
</code>```

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

答:
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.

JS:

```<code>var url = window.location.href;
  var msg = document.getElementById('current-menu-item-arrow');
  if( url.search( 'my-word' ) > 0 ) {
      msg.style.display = "block";
  }
</code>```

CSS:

```<code>#current-menu-item-arrow {display:none;}
</code>```

Title: jQuery add class based on parent URL

Body:
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

Body:
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.

JS:

var url = window.location.href;
  var msg = document.getElementById('current-menu-item-arrow');
  if( url.search( 'my-word' ) > 0 ) {
      msg.style.display = "block";
  }

CSS:

#current-menu-item-arrow {display:none;}


问:
Adding library in BlueJ
I am wondering if there a way to add Referenced library in blueJ. In eclipse, you can add the referenced library by clicking Build Path>> add external jar. How can you do it in blueJ? It is because I would like to use other library such as javax.mail, hibernate, and also log4j in BlueJ.

答: Note: it seems that I can't find 'Preferences' in Mac. In case of that, press command+, to toggle the preferences window.

Title: Adding library in BlueJ


问:
NestJs can't resolve dependencies, why?
New to NestJs,after the configuration according to https://docs.nestjs.com/techniques/database
can't figure out the problem of my code .

Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Admin Module:

```<code>import { Module } from '@nestjs/common';
import {Admin} from "../entities/Admin";
import {TypeOrmModule} from '@nestjs/typeorm';
import {AdminService} from "./admin.service";
import {AdminController} from "./admin.controller";

@Module({
    imports:[TypeOrmModule.forFeature([Admin])],
    exports: [TypeOrmModule],
    providers: [AdminService],
    controllers: [AdminController]
})
export class AdminModule {}
</code>```

AdminController:

```<code>import { Controller } from '@nestjs/common';

@Controller('admin')
export class AdminController {}
</code>```

AdminService:

```<code>import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Admin } from '../entities/Admin';

@Injectable()
export class AdminService {
    constructor(
        @InjectRepository(Admin)
        private readonly adminRepository:Repository<Admin>
    ) {}
}
</code>```

App Module:

```<code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoginController } from './login/login.controller';
import { RegisterController } from './register/register.controller';
import { ContactController } from './contact/contact.controller';

import { AppService } from './app.service';
import { LoginService } from './login/login.service';
import { ContactService } from './contact/contact.service';
import { RegisterService } from './register/register.service';
import { AdminModule } from './admin/admin.module';

@Module({
  imports: [AdminModule],
  controllers: [AppController, LoginController, RegisterController, ContactController],
  providers: [AppService, LoginService, ContactService, RegisterService],
})
export class AppModule {}
</code>```

答:
You have to import typeorm config in the app module. Refer to the below code.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoginController } from './login/login.controller';
import { RegisterController } from './register/register.controller';
import { ContactController } from './contact/contact.controller';

import { AppService } from './app.service';
import { LoginService } from './login/login.service';
import { ContactService } from './contact/contact.service';
import { RegisterService } from './register/register.service';
import { AdminModule } from './admin/admin.module';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forRoot(),AdminModule],
  controllers: [AppController, LoginController, RegisterController, ContactController],
  providers: [AppService, LoginService, ContactService, RegisterService],
})
export class AppModule {}```

Title: NestJs can't resolve dependencies, why?

Body:
New to NestJs,after the configuration according to https://docs.nestjs.com/techniques/database
can't figure out the problem of my code .

Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Admin Module:

import { Module } from '@nestjs/common';
import {Admin} from "../entities/Admin";
import {TypeOrmModule} from '@nestjs/typeorm';
import {AdminService} from "./admin.service";
import {AdminController} from "./admin.controller";

@Module({
    imports:[TypeOrmModule.forFeature([Admin])],
    exports: [TypeOrmModule],
    providers: [AdminService],
    controllers: [AdminController]
})
export class AdminModule {}

AdminController:

import { Controller } from '@nestjs/common';

@Controller('admin')
export class AdminController {}

AdminService:

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Admin } from '../entities/Admin';

@Injectable()
export class AdminService {
    constructor(
        @InjectRepository(Admin)
        private readonly adminRepository:Repository<Admin>
    ) {}
}

App Module:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoginController } from './login/login.controller';
import { RegisterController } from './register/register.controller';
import { ContactController } from './contact/contact.controller';

import { AppService } from './app.service';
import { LoginService } from './login/login.service';
import { ContactService } from './contact/contact.service';
import { RegisterService } from './register/register.service';
import { AdminModule } from './admin/admin.module';

@Module({
  imports: [AdminModule],
  controllers: [AppController, LoginController, RegisterController, ContactController],
  providers: [AppService, LoginService, ContactService, RegisterService],
})
export class AppModule {}


问:
gRPC client: error in compiled file (io.grpc.protobuf does not exist)
I made a simple protobuf+gRPC server/client example with Python, and wanted now to complete it with an Android Java client. However, I struggled through the documentation and got it mostly working (.proto compiles in Android Studio), BUT now I get Errors in the output *Grpc.java file (i.e. if I fix it it will just be overwritten by the compiler):

```<code>error: package io.grpc.protobuf does not exist
error: package com.google.protobuf.Descriptors does not exist
</code>```

Since I get errors from io.gprc's and com.google's protobuf, I suspect a definition conflict in my gradle, but I cannot find/resolve it (went through several "tutorials" and it seemed common to use a mix of grpc and google sources).

Here is my build.gradle:

```<code>
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "***.grpcclient"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'io.grpc:grpc-okhttp:1.25.0'
    //implementation 'io.grpc:grpc-protobuf-lite:1.25.0'

    implementation 'com.google.protobuf:protobuf-javalite:3.8.0'
    implementation 'io.grpc:grpc-stub:1.25.0'
    implementation 'org.glassfish:javax.annotation:10.0-b28'
}

apply plugin: 'com.google.protobuf'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.8.0'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.25.0'
        }
    }
    generateProtoTasks {
        all().each { task ->

                task.builtins {
                    java {
                        option "lite"
                    }
                    python { }
                }
                task.plugins {
                    grpc {outputSubDir = 'java'}
                }

        }
    }
}
</code>```

Any help is appreciated!

答:
My working build.gradle:</p>

```<code>
dependencies {

   implementation 'com.squareup.okhttp:okhttp:2.7.5'
    implementation 'javax.annotation:javax.annotation-api:1.3.2'
    implementation 'io.grpc:grpc-core:1.27.1'
    implementation 'io.grpc:grpc-stub:1.27.1'
    implementation 'io.grpc:grpc-okhttp:1.27.1'
    implementation('io.grpc:grpc-protobuf-lite:1.27.1') {
        exclude module: "protobuf-lite"
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.11.4'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.27.1'
        }
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }

            task.plugins {
                grpc {
                    // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
}
</code>```

Body:
I made a simple protobuf+gRPC server/client example with Python, and wanted now to complete it with an Android Java client. However, I struggled through the documentation and got it mostly working (.proto compiles in Android Studio), BUT now I get Errors in the output *Grpc.java file (i.e. if I fix it it will just be overwritten by the compiler):

error: package io.grpc.protobuf does not exist
error: package com.google.protobuf.Descriptors does not exist

Since I get errors from io.gprc's and com.google's protobuf, I suspect a definition conflict in my gradle, but I cannot find/resolve it (went through several "tutorials" and it seemed common to use a mix of grpc and google sources).

Here is my build.gradle:

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "***.grpcclient"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'io.grpc:grpc-okhttp:1.25.0'
    //implementation 'io.grpc:grpc-protobuf-lite:1.25.0'

    implementation 'com.google.protobuf:protobuf-javalite:3.8.0'
    implementation 'io.grpc:grpc-stub:1.25.0'
    implementation 'org.glassfish:javax.annotation:10.0-b28'
}

apply plugin: 'com.google.protobuf'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.8.0'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.25.0'
        }
    }
    generateProtoTasks {
        all().each { task ->

                task.builtins {
                    java {
                        option "lite"
                    }
                    python { }
                }
                task.plugins {
                    grpc {outputSubDir = 'java'}
                }

        }
    }
}

Any help is appreciated!

Body:
My working build.gradle:

dependencies {

   implementation 'com.squareup.okhttp:okhttp:2.7.5'
    implementation 'javax.annotation:javax.annotation-api:1.3.2'
    implementation 'io.grpc:grpc-core:1.27.1'
    implementation 'io.grpc:grpc-stub:1.27.1'
    implementation 'io.grpc:grpc-okhttp:1.27.1'
    implementation('io.grpc:grpc-protobuf-lite:1.27.1') {
        exclude module: "protobuf-lite"
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.11.4'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.27.1'
        }
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }

            task.plugins {
                grpc {
                    // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
}


问:
How to get a list of users with specific role symfony controller
I'm new to symfony 2, working with FOSUserBundle along with PUGXMultiUserBundle and I have troubles retrieving the list of users with a specific role, for example : ROLE_ADMINISTRATEUR to notifiy them about something. Anyway, inspired by this this is my UserRepository class:

```<code><?php
namespace OC\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
 public function findByRoles($role)
{
 $qb = $this->_em->createQueryBuilder();
 $qb->select('u')
    ->from('OCUserBundle:User', 'u')
    ->where('u.roles LIKE :roles')
    ->setParameter('roles', '%"'.$role.'"%');

 return $qb->getQuery()->getResult();
 }
}
</code>```

and this is the code inside in the controller's action:

```<code>$em=$this->getDoctrine()->getManager();
$repository2=$em->getRepository('OCUserBundle:User');
$roles='ROLE_ADMINISTRATEUR';
$users=$repository2->findByRoles(array('roles'=>$roles));

Return $this->render('OCUserBundle:Default:test.html.twig',array(
        'users'=>$users));
</code>```

and my test.html.twig page:

```<code> {% for a in users %}
 {{a.username}}
 {% endfor %}
</code>```

All what I get is an empty page. Any help would be appreciated

答:
I try to do this also without PUGXMultiUserBundle with the function:

```<code>$users = $repositoryUser->findByRoles("ROLE_SUPER_ADMIN");
</code>```

But it's doesn't work i get an empty array, so i do it manually:

```<code>$qb = $em->createQueryBuilder();
$qb->select('u') ->from('AppBundle:User', 'u') ->where('u.roles LIKE :roles') ->setParameter('roles', '%"'."ROLE_SUPER_ADMIN".'"%');
$users = $qb->getQuery()->getResult();
</code>```

Maybe this can help people who are in the same case of me.

Body:
I'm new to symfony 2, working with FOSUserBundle along with PUGXMultiUserBundle and I have troubles retrieving the list of users with a specific role, for example : ROLE_ADMINISTRATEUR to notifiy them about something. Anyway, inspired by this this is my UserRepository class:

<?php
namespace OC\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
 public function findByRoles($role)
{
 $qb = $this->_em->createQueryBuilder();
 $qb->select('u')
    ->from('OCUserBundle:User', 'u')
    ->where('u.roles LIKE :roles')
    ->setParameter('roles', '%"'.$role.'"%');

 return $qb->getQuery()->getResult();
 }
}

and this is the code inside in the controller's action:

$em=$this->getDoctrine()->getManager();
$repository2=$em->getRepository('OCUserBundle:User');
$roles='ROLE_ADMINISTRATEUR';
$users=$repository2->findByRoles(array('roles'=>$roles));

Return $this->render('OCUserBundle:Default:test.html.twig',array(
        'users'=>$users));

and my test.html.twig page:

 {% for a in users %}
 {{a.username}}
 {% endfor %}

All what I get is an empty page. Any help would be appreciated

Body:
I try to do this also without PUGXMultiUserBundle with the function:

$users = $repositoryUser->findByRoles("ROLE_SUPER_ADMIN");

But it's doesn't work i get an empty array, so i do it manually:

$qb = $em->createQueryBuilder();
$qb->select('u') ->from('AppBundle:User', 'u') ->where('u.roles LIKE :roles') ->setParameter('roles', '%"'."ROLE_SUPER_ADMIN".'"%');
$users = $qb->getQuery()->getResult();

Maybe this can help people who are in the same case of me.


问:
Best approach to make a fullscreen WPF app
I'm creating a full-screen application in WPF and i need to choose how to actually resize the contents to use all the available space on the screen.

As far as i know, there are 2 solutions:

Grids with stars-dimensions

ViewBox wrapper

I think they both do the job but depending on the application one is better than the other: when should the grid approach be used? And when the viewbox method is acceptable?

答: You cannot zoom with Grids and star dimensions. ViewBox can scale its content.</p>


问:
HttpRequest: inconsistent Scheme & Host properties
My ASP.NET Core 3.1 application runs in Kubernetes. The ingress (load balancer) terminates SSL and talks to the pod over plain HTTP.

Let's say the ingress is reachable at https://my-app.com:443, and talks to the pod (where my app is running) at http://10.0.0.1:80.

When handling a request, the middleware pipeline sees an HttpRequest object with the following:

Scheme == "http"

Host.Value == "my-app.com"

IsHttps == False

This is weird:

Judging by the Scheme (and IsHttps), it seems the HttpRequest object describes the forwarded request from the ingress to the pod, the one that goes over plain HTTP. However, why isn't Host.Value equal to 10.0.0.1 in that case?

Or vice versa: if HttpRequest is trying to be clever and represent the original request, the one to the ingress, why doesn't it show "https" along with "my-app.com"?

At no point in handling the request is there a request coming to http://my-app.com. It's either https://my-app.com or http://10.0.0.1. The combination is inconsistent.

Other details

Digging deeper, the HttpRequest object has the following headers (among others) that show the reverse proxying in action:

```<code>Host: my-app.com
Referer: https://my-app.com/swagger/index.html
X-Real-IP: 10.0.0.1
X-Forwarded-For: 10.0.0.1
X-Forwarded-Host: my-app.com
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Scheme: https
</code>```

I'm guessing HttpRequest is using these to get hold of the original host (my-app.com rather than 10.0.0.1) but it doesn't do the same for the original scheme (https rather than http).

Q1: Is this expected, and if so, what is the rationale?

Q2: What's the best way to get at the original URL (https://my-app.com)? The best I've found so far was to check if the X-Scheme and X-Forwarded-Host headers were present (by inspecting HttpRequest.Headers) and if so, using those. However, it's a little weird having to go to the raw HTTP headers in the middleware pipeline.

答:
Q1: Is this expected, and if so, what is the rationale?

I would say yes, it's the expected behavior.

The 'Host.Value=my-app.com' of HttpRequest object is reflecting the request header field originated by client (web browser, curl, ...), e.g.:

```<code>curl --insecure -H 'Host: my-app.com' https://<FRONTEND_FOR_INGRESS-MOST_OFTEN_LB-IP>
</code>```

which is set*[1] in location block for that server 'my-app.com' inside generated nginx.conf file:

```<code>                    ...
                    set $best_http_host                     $http_host;
                    # [1] - Set Host value
                    proxy_set_header Host                   $best_http_host;
                    ...
                    # Pass the extracted client certificate to the backend
                    ...
                    proxy_set_header                        Connection        $connection_upgrade;
                    proxy_set_header X-Request-ID           $req_id;
                    proxy_set_header X-Real-IP              $remote_addr;
                    proxy_set_header X-Forwarded-For        $remote_addr;
                    proxy_set_header X-Forwarded-Host       $best_http_host;
                    ...
</code>```

whereas 'http_host' variable is created based on following "ngx_http_core_module" core functionality:

$http_name -
  arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores

So described behavior is not anyhow unique to ASP.NET Core 3.0, you see unknown Dictionary containing key/value pairs of custom headers set explicitly by nginx controller, accordingly to nginx ingress current configuration, that's it.

You can inspect current nginx controller's configuration by your self with following command:

```<code>kubectl exec -it po/<nginx-ingress-controller-pod-name> -n <ingress-controller-namespace> -- cat /etc/nginx/nginx.conf
</code>```

Q2: What's the best way to get at the original URL
  (https://my-app.com)?

I would try with constructing it using Configuration snippet, this is by introducing another custom header, where you concatenate values.

Body:
My ASP.NET Core 3.1 application runs in Kubernetes. The ingress (load balancer) terminates SSL and talks to the pod over plain HTTP.

Let's say the ingress is reachable at https://my-app.com:443, and talks to the pod (where my app is running) at http://10.0.0.1:80.

When handling a request, the middleware pipeline sees an HttpRequest object with the following:

Scheme == "http"

Host.Value == "my-app.com"

IsHttps == False

This is weird:

Judging by the Scheme (and IsHttps), it seems the HttpRequest object describes the forwarded request from the ingress to the pod, the one that goes over plain HTTP. However, why isn't Host.Value equal to 10.0.0.1 in that case?

Or vice versa: if HttpRequest is trying to be clever and represent the original request, the one to the ingress, why doesn't it show "https" along with "my-app.com"?

At no point in handling the request is there a request coming to http://my-app.com. It's either https://my-app.com or http://10.0.0.1. The combination is inconsistent.

Other details

Digging deeper, the HttpRequest object has the following headers (among others) that show the reverse proxying in action:

Host: my-app.com
Referer: https://my-app.com/swagger/index.html
X-Real-IP: 10.0.0.1
X-Forwarded-For: 10.0.0.1
X-Forwarded-Host: my-app.com
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Scheme: https

I'm guessing HttpRequest is using these to get hold of the original host (my-app.com rather than 10.0.0.1) but it doesn't do the same for the original scheme (https rather than http).

Q1: Is this expected, and if so, what is the rationale?

Q2: What's the best way to get at the original URL (https://my-app.com)? The best I've found so far was to check if the X-Scheme and X-Forwarded-Host headers were present (by inspecting HttpRequest.Headers) and if so, using those. However, it's a little weird having to go to the raw HTTP headers in the middleware pipeline.

Body:
Q1: Is this expected, and if so, what is the rationale?

I would say yes, it's the expected behavior.

The 'Host.Value=my-app.com' of HttpRequest object is reflecting the request header field originated by client (web browser, curl, ...), e.g.:

curl --insecure -H 'Host: my-app.com' https://<FRONTEND_FOR_INGRESS-MOST_OFTEN_LB-IP>

which is set*[1] in location block for that server 'my-app.com' inside generated nginx.conf file:

                    ...
                    set $best_http_host                     $http_host;
                    # [1] - Set Host value
                    proxy_set_header Host                   $best_http_host;
                    ...
                    # Pass the extracted client certificate to the backend
                    ...
                    proxy_set_header                        Connection        $connection_upgrade;
                    proxy_set_header X-Request-ID           $req_id;
                    proxy_set_header X-Real-IP              $remote_addr;
                    proxy_set_header X-Forwarded-For        $remote_addr;
                    proxy_set_header X-Forwarded-Host       $best_http_host;
                    ...

whereas 'http_host' variable is created based on following "ngx_http_core_module" core functionality:

$http_name -
  arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores

So described behavior is not anyhow unique to ASP.NET Core 3.0, you see unknown Dictionary containing key/value pairs of custom headers set explicitly by nginx controller, accordingly to nginx ingress current configuration, that's it.

You can inspect current nginx controller's configuration by your self with following command:

kubectl exec -it po/<nginx-ingress-controller-pod-name> -n <ingress-controller-namespace> -- cat /etc/nginx/nginx.conf

Q2: What's the best way to get at the original URL
  (https://my-app.com)?

I would try with constructing it using Configuration snippet, this is by introducing another custom header, where you concatenate values.


问:
How do I update an individual component using aurelia store?
I'm using the aurelia-store plugin. I have this list, and it's generally rendering correctly, except enabled/disabled which is what I'm working on.

```<code>export interface State {
  readonly availableGames: AvailableGame[];
  readonly myGames: Game[];
}

export const initialState: State = {
  availableGames: [
    { name: 'Foo', added: false },
    { name: 'Bar', added: false },
  ],
  myGames: [],
};
</code>```

AvailableGames.html

<template>
  <require from="./game-add-button.html"></require>

        <game-add-button game.bind="game" on-add.call="addGameToMyList(game)"></game-add-button>

</template>
```

<p><code>AvailableGames</code></p>

```import { autoinject } from 'aurelia-framework';
import { connectTo, Store } from 'aurelia-store';
import { Event } from '../Event';
import { State } from '../State';
import AvailableGame from './AvailableGame';
import Game from './Game';

@connectTo()
@autoinject()
export default class AvailableGames {

  readonly state!: State;

  constructor(private store: Store<State>) {
    this.store.registerAction(Event.ADD_GAME_TO_MY_LIST, (state, game) => this.onAddNewState(state, game));
  }

  async addGameToMyList(availableGame: AvailableGame): Promise<void> {
    const { added, ...game } = availableGame;
    return await this.store.dispatch(Event.ADD_GAME_TO_MY_LIST, game);
  }

  private onAddNewState(state: State, game: Game): State {
    return {
      ...state,
      myGames: [...state.myGames, game]
    };
  }
}
```

<p><code>game-add-button.html</code></p>

<pre class="lang-html prettyprint-override"><code><template bindable="game,onAdd" role="button">
  <button class="button ${game.added ? 'is-success' : ''}" click.trigger="onAdd(game)" disabled.bind="game.added">
    ${game.name}
  </button>
</template>
</code>```

GameAddButton.ts

```<code>@customElement('game-add-button')
export default class GameAddButton {
  @bindable game!: AvailableGame;
  @bindable onAdd!: (game: AvailableGame) => void
}
</code>```

everything seems to work, except when I click the button, the state update is not reflected in the UI. How do I change my code so that the buttons state is reflected?

答: I don't know what your intention with the myGames array was, which you're pushing the selected game to in your action. But in your AvailableGames.html you're still iterating on availableGames and haven't modified it in your new state to say added: true for the selected game.</p>

Body:
I'm using the aurelia-store plugin. I have this list, and it's generally rendering correctly, except enabled/disabled which is what I'm working on.

export interface State {
  readonly availableGames: AvailableGame[];
  readonly myGames: Game[];
}

export const initialState: State = {
  availableGames: [
    { name: 'Foo', added: false },
    { name: 'Bar', added: false },
  ],
  myGames: [],
};

AvailableGames.html

<template>
  <require from="./game-add-button.html"></require>

        <game-add-button game.bind="game" on-add.call="addGameToMyList(game)"></game-add-button>

</template>

AvailableGames

import { autoinject } from 'aurelia-framework';
import { connectTo, Store } from 'aurelia-store';
import { Event } from '../Event';
import { State } from '../State';
import AvailableGame from './AvailableGame';
import Game from './Game';

@connectTo()
@autoinject()
export default class AvailableGames {

  readonly state!: State;

  constructor(private store: Store<State>) {
    this.store.registerAction(Event.ADD_GAME_TO_MY_LIST, (state, game) => this.onAddNewState(state, game));
  }

  async addGameToMyList(availableGame: AvailableGame): Promise<void> {
    const { added, ...game } = availableGame;
    return await this.store.dispatch(Event.ADD_GAME_TO_MY_LIST, game);
  }

  private onAddNewState(state: State, game: Game): State {
    return {
      ...state,
      myGames: [...state.myGames, game]
    };
  }
}

game-add-button.html

<template bindable="game,onAdd" role="button">
  <button class="button ${game.added ? 'is-success' : ''}" click.trigger="onAdd(game)" disabled.bind="game.added">
    ${game.name}
  </button>
</template>

GameAddButton.ts

@customElement('game-add-button')
export default class GameAddButton {
  @bindable game!: AvailableGame;
  @bindable onAdd!: (game: AvailableGame) => void
}

everything seems to work, except when I click the button, the state update is not reflected in the UI. How do I change my code so that the buttons state is reflected?


问:
Modify Command Line Arguments
I have a Win32 C++ application and I need to modify the command line arguments in the application. Specifically, I want to edit the command line arguments in such a way that GetCommandLineW() returns my new arguments.

Believe it or not, this works (since we have a non-const pointer to the character array):

```<code>LPTSTR args = GetCommandLineW();
LPTSTR new_args = L"foo --bar=baz";
wmemcpy(args, new_args, lstrlenW(new_args));

// ...
LPTSTR args2 = GetGommentLineW(); // <- equals "foo --bar=baz"
</code>```

But I don't know how long much memory Windows allocates for the LPTSTR provided by GetCommandLineW().

Is there another way to do this? Or does anyone know if there is a predictable amount of memory allocated for the command line arguments?

答:
Use the following code to inspect on PEB structure, where the CommandLine (unicode) string lies.

On my machine, under both x86 and x64 CommandLine is right after ImagePathName, so I think there won't be more space for the former one either. Writing a longer string to that buffer does might cause an overflow.

```<code>#include <winnt.h>
#include <winternl.h>

int main()
{
    // Thread Environment Block (TEB)
#if defined(_M_X64) // x64
    PTEB tebPtr = (PTEB)__readgsqword((DWORD) & (*(NT_TIB*)NULL).Self);
#else // x86
    PTEB tebPtr = (PTEB)__readfsdword((DWORD) & (*(NT_TIB*)NULL).Self);
#endif
    // Process Environment Block (PEB)
    PPEB pebPtr = tebPtr->ProcessEnvironmentBlock;
    PRTL_USER_PROCESS_PARAMETERS ppPtr = pebPtr->ProcessParameters;

    printf("ImagePathName:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->ImagePathName.Length, ppPtr->ImagePathName.MaximumLength, ppPtr->ImagePathName.Buffer);
    printf("CommandLine:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->CommandLine.Length, ppPtr->CommandLine.MaximumLength, ppPtr->CommandLine.Buffer);
    printf("GetCommandLineA:\tptr=%p\n", GetCommandLineA());
    printf("GetCommandLineW:\tptr=%p\n", GetCommandLineW());
    printf("Addr Delta between CommandLine and ImagePathName: %d\n", (char*)ppPtr->CommandLine.Buffer - (char*)ppPtr->ImagePathName.Buffer);
}
</code>```

Title: Modify Command Line Arguments

Body:
I have a Win32 C++ application and I need to modify the command line arguments in the application. Specifically, I want to edit the command line arguments in such a way that GetCommandLineW() returns my new arguments.

Believe it or not, this works (since we have a non-const pointer to the character array):

LPTSTR args = GetCommandLineW();
LPTSTR new_args = L"foo --bar=baz";
wmemcpy(args, new_args, lstrlenW(new_args));

// ...
LPTSTR args2 = GetGommentLineW(); // <- equals "foo --bar=baz"

But I don't know how long much memory Windows allocates for the LPTSTR provided by GetCommandLineW().

Is there another way to do this? Or does anyone know if there is a predictable amount of memory allocated for the command line arguments?

Body:
Use the following code to inspect on PEB structure, where the CommandLine (unicode) string lies.

On my machine, under both x86 and x64 CommandLine is right after ImagePathName, so I think there won't be more space for the former one either. Writing a longer string to that buffer does might cause an overflow.

#include <winnt.h>
#include <winternl.h>

int main()
{
    // Thread Environment Block (TEB)
#if defined(_M_X64) // x64
    PTEB tebPtr = (PTEB)__readgsqword((DWORD) & (*(NT_TIB*)NULL).Self);
#else // x86
    PTEB tebPtr = (PTEB)__readfsdword((DWORD) & (*(NT_TIB*)NULL).Self);
#endif
    // Process Environment Block (PEB)
    PPEB pebPtr = tebPtr->ProcessEnvironmentBlock;
    PRTL_USER_PROCESS_PARAMETERS ppPtr = pebPtr->ProcessParameters;

    printf("ImagePathName:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->ImagePathName.Length, ppPtr->ImagePathName.MaximumLength, ppPtr->ImagePathName.Buffer);
    printf("CommandLine:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->CommandLine.Length, ppPtr->CommandLine.MaximumLength, ppPtr->CommandLine.Buffer);
    printf("GetCommandLineA:\tptr=%p\n", GetCommandLineA());
    printf("GetCommandLineW:\tptr=%p\n", GetCommandLineW());
    printf("Addr Delta between CommandLine and ImagePathName: %d\n", (char*)ppPtr->CommandLine.Buffer - (char*)ppPtr->ImagePathName.Buffer);
}


问:
create a Python script which connects to a range of IPs on a specific port (SMTP)
I need to create a script with Python which checks if a list of users exist on the SMTP server (the list of IPs of servers is in a file).

This is the script I have run but I have an error in the socket connect function:

```<code>#!/usr/bin/python

import socket
import sys
import os

with open("smtp_ip.txt", "r") as ip:
        for IpTested in ip :
                print IpTested
                s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                connect=s.connect(('IpTested', 25))
                banner=s.recv(1024)
                print "echec connect"
                with open("user.txt","r+") as username:
                        for user in username:
                                s.send('VRFY ' + user + '\r\n')
                                result=s.recv(1024)
                                print result
        s.close()

ip.close()
</code>```

and this is the error i have :

```<code>root@kali:~/smtppython# ./smtpv2.py

Traceback (most recent call last):
  File "./smtpv2.py", line 12, in <module>
    connect=s.connect(('IpTested', 25))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known
</code>```

答:
Instead of

```<code>connect=s.connect(('IpTested', 25))
</code>```

you should have

```<code>connect=s.connect((IpTested, 25))
</code>```

as the former passes the string 'IpTested', rather than the variable IpTested…

Also, you don't need

```<code>ip.close()
</code>```

because the context manager (with open("smtp_ip.txt", "r") as ip:) takes care of it.

Update: and, since IpTested is a line read from a file, it contains a newline - you need to remove it, so:

```<code>connect = s.connect((IpTested.rstrip(), 25))
</code>```

Body:
I need to create a script with Python which checks if a list of users exist on the SMTP server (the list of IPs of servers is in a file).

This is the script I have run but I have an error in the socket connect function:

#!/usr/bin/python

import socket
import sys
import os

with open("smtp_ip.txt", "r") as ip:
        for IpTested in ip :
                print IpTested
                s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                connect=s.connect(('IpTested', 25))
                banner=s.recv(1024)
                print "echec connect"
                with open("user.txt","r+") as username:
                        for user in username:
                                s.send('VRFY ' + user + '\r\n')
                                result=s.recv(1024)
                                print result
        s.close()

ip.close()

and this is the error i have :

root@kali:~/smtppython# ./smtpv2.py

Traceback (most recent call last):
  File "./smtpv2.py", line 12, in <module>
    connect=s.connect(('IpTested', 25))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known

Body:
Instead of

connect=s.connect(('IpTested', 25))

you should have

connect=s.connect((IpTested, 25))

as the former passes the string 'IpTested', rather than the variable IpTested…

Also, you don't need

ip.close()

because the context manager (with open("smtp_ip.txt", "r") as ip:) takes care of it.

Update: and, since IpTested is a line read from a file, it contains a newline - you need to remove it, so:

connect = s.connect((IpTested.rstrip(), 25))


问:
Culture sensitive ParseFloat Function in JavaScript?
Do anyone have suggestion for writing culture sensitive ParseFloat Function in JavaScript, So that when I have a string 100,000.22 in US culture format the parse float function returns 100000.22 whereas if I enter 100.000,22 in Swedish Culture it returns 100000.22 in float?</p>

答:
If you really for displaying and/or parsing floats (or dates or currencies or more) in different locales for JavaScript, then my recommendation is the GlobalizeJS (https://github.com/globalizejs/globalize) library.

It's a bit tough to set up at first (at least it was in my experience), but totally recommended for proper management of this matter.

ContentLicense: CC BY-SA 2.5


问:
Angular Generate a PDF document from a DIV class in HTML
I am working on an Invoicing app with angular.

Inside a DIV class, I have generated a preview of my Invoice.

I want to be able to generate a PDF file from this Div Class. Is it possible? Do you have any hint? What would another way?

Warms Regards
Mathieu

答:
When I open my PDF, I have a white page, and the PDF keeps on loading:

Here is my code:
component.show.ts

```<code>        import { Component, OnInit } from '@angular/core';
    import { BasicRequestsService } from '../../../../../core/services/basic-requests.service';
    import { ActivatedRoute } from '@angular/router';
    import { Observable, forkJoin } from 'rxjs';
    import { FormsModule, FormBuilder } from '@angular/forms';
    import { DatePipe } from '@angular/common';
    import * as jsPDF from 'jspdf';
    import { ElementRef, ViewChild} from "@angular/core";
    import { ToastsService } from '../../../../../core/services/toasts.service';
    import { Pipe, PipeTransform } from '@angular/core';

@Component({
      selector: 'app-tools-billing-invoices-show',
      templateUrl: './show.component.html',
      styleUrls: ['./show.component.scss', '../invoices.component.scss']
    })

export class InvoicesShowComponent implements OnInit {
      endpoint = '/tools/billing/billers/';
      billerId;
      billerData;
      invoiceId;
      invoice;
      invoiceUpdated;
      invoiceLines;
      invoiceForm;
      clientData;
      symbol;
      invoiceTotal = {taxExcluded: 0, tax: 0, taxIncluded: 0};
      date: Date;
      constructor(
        private basicRequestsService: BasicRequestsService,
        private route: ActivatedRoute,
        private formBuilder: FormBuilder,
        private toasts: ToastsService,
        ) { }

createPdf(): void {
        var doc = new jsPDF();
        var elementHandler = {
          '#ignorePDF': function (element, renderer) {
            return true;
          }
        };
        var source = window.document.getElementsByTagName("invoice-preview-box")[0];
        doc.fromHTML(
          source,
          15,
          15,
          {
            'width': 180,'elementHandlers': elementHandler
          });
        doc.output("dataurlnewwindow");
      }
    }
</code>```

Here is my HTML

```<code> <button class="dropdown-item" (click)="createPdf()">Generate PDF</button>

<div class="col-xl-9 invoice-preview-box" tag="invoice-preview-box" id="invoice-preview-box"> Hello World, here is MY PDF </div>
</code>```

Body:
When I open my PDF, I have a white page, and the PDF keeps on loading:

Here is my code:
component.show.ts

        import { Component, OnInit } from '@angular/core';
    import { BasicRequestsService } from '../../../../../core/services/basic-requests.service';
    import { ActivatedRoute } from '@angular/router';
    import { Observable, forkJoin } from 'rxjs';
    import { FormsModule, FormBuilder } from '@angular/forms';
    import { DatePipe } from '@angular/common';
    import * as jsPDF from 'jspdf';
    import { ElementRef, ViewChild} from "@angular/core";
    import { ToastsService } from '../../../../../core/services/toasts.service';
    import { Pipe, PipeTransform } from '@angular/core';

@Component({
      selector: 'app-tools-billing-invoices-show',
      templateUrl: './show.component.html',
      styleUrls: ['./show.component.scss', '../invoices.component.scss']
    })

export class InvoicesShowComponent implements OnInit {
      endpoint = '/tools/billing/billers/';
      billerId;
      billerData;
      invoiceId;
      invoice;
      invoiceUpdated;
      invoiceLines;
      invoiceForm;
      clientData;
      symbol;
      invoiceTotal = {taxExcluded: 0, tax: 0, taxIncluded: 0};
      date: Date;
      constructor(
        private basicRequestsService: BasicRequestsService,
        private route: ActivatedRoute,
        private formBuilder: FormBuilder,
        private toasts: ToastsService,
        ) { }

createPdf(): void {
        var doc = new jsPDF();
        var elementHandler = {
          '#ignorePDF': function (element, renderer) {
            return true;
          }
        };
        var source = window.document.getElementsByTagName("invoice-preview-box")[0];
        doc.fromHTML(
          source,
          15,
          15,
          {
            'width': 180,'elementHandlers': elementHandler
          });
        doc.output("dataurlnewwindow");
      }
    }

Here is my HTML

 <button class="dropdown-item" (click)="createPdf()">Generate PDF</button>

<div class="col-xl-9 invoice-preview-box" tag="invoice-preview-box" id="invoice-preview-box"> Hello World, here is MY PDF </div>


问:
can't access other roles when limiting the access based on tags
I want to allow my role to access only roles with a specific tag. Therefore, I've created a policy:

```<code>    "Statement": [
        {
            "Action": [
                "iam:GetRole"
            ],
            "Resource": "*",
            "Effect": "Allow",
            "Condition": {
                "StringLike": {
                    "iam:ResourceTag/key": "value"
                }
            }
        }
    ]
}
</code>```

and for each of the relevant role I've added the tag with the properties of - key - value.

However, when I'm using the specific role I keep getting these errors:
AccessDenied. User doesn't have permission to call iam:GetRole

Any idea?

答:
I created a policy with this json, and attached it to a role, which i ran with a lambda. I was successfully able to get the arn of a IAM:Role that had the key value tag and access denied on one that did not. Perhaps you aren't attaching the policy correctly or perhaps you're trying to perform the action using a different role, try creating an instance profile and attach it to a ec2 and run the commands from there or via lambda.
tldr; the json is fine problem is somewhere else.

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Condition": {
            "StringLike": {
                "iam:ResourceTag/key": "value"
            }
        },
        "Action": [
            "iam:GetRole"
        ],
        "Resource": "*",
        "Effect": "Allow"
    }
]
</code>```

}

Here is the full CF stack I used. It's yaml and Obviously the principle should be changed depending on your needs.

```<code> Resources:
  Role:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
            - edgelambda.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - !Ref Policy
  Policy:
      Type: AWS::IAM::ManagedPolicy
      Properties:
          ManagedPolicyName: Get_Role_With_Tag__Policy
          Path: /
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                - iam:GetRole
                Condition:
                  StringLike:
                    iam:ResourceTag/key: "value"
                Resource: "*"
</code>```

Body:
I want to allow my role to access only roles with a specific tag. Therefore, I've created a policy:

    "Statement": [
        {
            "Action": [
                "iam:GetRole"
            ],
            "Resource": "*",
            "Effect": "Allow",
            "Condition": {
                "StringLike": {
                    "iam:ResourceTag/key": "value"
                }
            }
        }
    ]
}

and for each of the relevant role I've added the tag with the properties of - key - value.

However, when I'm using the specific role I keep getting these errors:
AccessDenied. User doesn't have permission to call iam:GetRole

Any idea?

Body:
I created a policy with this json, and attached it to a role, which i ran with a lambda. I was successfully able to get the arn of a IAM:Role that had the key value tag and access denied on one that did not. Perhaps you aren't attaching the policy correctly or perhaps you're trying to perform the action using a different role, try creating an instance profile and attach it to a ec2 and run the commands from there or via lambda.
tldr; the json is fine problem is somewhere else.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Condition": {
            "StringLike": {
                "iam:ResourceTag/key": "value"
            }
        },
        "Action": [
            "iam:GetRole"
        ],
        "Resource": "*",
        "Effect": "Allow"
    }
]

}

Here is the full CF stack I used. It's yaml and Obviously the principle should be changed depending on your needs.

 Resources:
  Role:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
            - edgelambda.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - !Ref Policy
  Policy:
      Type: AWS::IAM::ManagedPolicy
      Properties:
          ManagedPolicyName: Get_Role_With_Tag__Policy
          Path: /
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                - iam:GetRole
                Condition:
                  StringLike:
                    iam:ResourceTag/key: "value"
                Resource: "*"


问:
Cannot send message without a sender address :: Email by Gmail to reset password
i just did this to get password reset mail, i have not added anything to controller or routes for this please suggest me the solution

Peoples are working and running it fine Using Default Auth in laravel 6

```<code>     ## .env ##

        '''
        MAIL_DRIVER=smtp
        MAIL_HOST=smtp.gmail.com
        MAIL_PORT=587
        MAIL_USERNAME=email@gmail.com
        MAIL_PASSWORD=djscsajhfslowhwo  //two step verified Password
        MAIL_ENCRYPTION=tls
        MAIL_FROM_ADDRESS=null
        MAIL_FROM_NAME="${APP_NAME}"

        '''

    ## mail.php ##
</code>```

Mail.php file Please Review this i have entered the two step vereification code in passwsord and have also updated using tls and all the thing are here .... But remember i haven't added anything to routes and controlller for this issue what should ypu suggest

```<code>    '''
    return [
        'driver' => env('MAIL_DRIVER', 'smtp'),
        'host' => env('MAIL_HOST', 'smtp.gmail.com'),
        'port' => env('MAIL_PORT', 587),
        'from' => [
            'address' => env('MAIL_FROM_ADDRESS', 'email@gmail.com'),
            'name' => env('MAIL_FROM_NAME', 'test'),
        ],
        'encryption' => env('MAIL_ENCRYPTION', 'tls'),
        'username' => env('MAIL_USERNAME'),
        'password' => env('MAIL_PASSWORD'),
        'sendmail' => '/usr/sbin/sendmail -bs',

        'markdown' => [
            'theme' => 'default',

            'paths' => [
                resource_path('views/vendor/mail'),
            ],
        ],

        'log_channel' => env('MAIL_LOG_CHANNEL'),

    ];

    '''
</code>```

答:
You need to read and follow the process in https://support.google.com/accounts/answer/185833?hl=en

It will guide you to creating an app-specific password this password effectively bypasses 2-factor authentication, so you should create a password for this and never use that password again so a Keylogger or scraper can never get it so they hackers don't have the ability to bypass your two-factor authentication.

The Mail From Address address should not be the textual value of "null", just set it to the email address your logging into Gmail with.

Body:
i just did this to get password reset mail, i have not added anything to controller or routes for this please suggest me the solution

Peoples are working and running it fine Using Default Auth in laravel 6

     ## .env ##

        '''
        MAIL_DRIVER=smtp
        MAIL_HOST=smtp.gmail.com
        MAIL_PORT=587
        MAIL_USERNAME=email@gmail.com
        MAIL_PASSWORD=djscsajhfslowhwo  //two step verified Password
        MAIL_ENCRYPTION=tls
        MAIL_FROM_ADDRESS=null
        MAIL_FROM_NAME="${APP_NAME}"

        '''

    ## mail.php ##

Mail.php file Please Review this i have entered the two step vereification code in passwsord and have also updated using tls and all the thing are here .... But remember i haven't added anything to routes and controlller for this issue what should ypu suggest

    '''
    return [
        'driver' => env('MAIL_DRIVER', 'smtp'),
        'host' => env('MAIL_HOST', 'smtp.gmail.com'),
        'port' => env('MAIL_PORT', 587),
        'from' => [
            'address' => env('MAIL_FROM_ADDRESS', 'email@gmail.com'),
            'name' => env('MAIL_FROM_NAME', 'test'),
        ],
        'encryption' => env('MAIL_ENCRYPTION', 'tls'),
        'username' => env('MAIL_USERNAME'),
        'password' => env('MAIL_PASSWORD'),
        'sendmail' => '/usr/sbin/sendmail -bs',

        'markdown' => [
            'theme' => 'default',

            'paths' => [
                resource_path('views/vendor/mail'),
            ],
        ],

        'log_channel' => env('MAIL_LOG_CHANNEL'),

    ];

    '''


问:
Ticker should not execute if already running
I have some function that has to run periodically. I have used a ticker for this. But if the ticker is already running, and the time interval passes again, it should not execute again.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(3*time.Second)
    flag := 0
    defer ticker.Stop()
    for {
        select {
        case t := <-ticker.C:
            flag = flag + 1
            if (flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
            }
            fmt.Println("Current time: ", t)
        }
    }
}
</code>```

https://play.golang.org/p/2xV2MYInn4I

In the playground, the ticker prints every 3 seconds, but every even turn of the ticker the job takes more time than the interval. I expect it to not run then and drop those ticks.

How do I do this?

答:
The ticker channel is buffered, which is why you may see multiple triggers right one after the other. You can prevent that by simply transfering the ticker's values to an unbuffered channel (note also that the time.Time value received from the ticker is not the current time but the time of the last tick):

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan time.Time) // unbuffered
    ticker := time.NewTicker(3 * time.Second)
    defer ticker.Stop()

    go func() {
        for t := range ticker.C {
            select {
            case c <- t:
            default:
            }
        }
    }()

    for flag := 0; flag < 8; flag++ {
        <-c

        if flag%2 == 0 {
            time.Sleep(time.Second * 4)
        }
        fmt.Println("Current time: ", time.Now())
    }
}

// Output:
// Current time:  2020-02-19 12:21:57.095433032 +0100 CET m=+3.000213350
// Current time:  2020-02-19 12:22:04.095585208 +0100 CET m=+10.000365520
// Current time:  2020-02-19 12:22:06.095363327 +0100 CET m=+12.000143680
// Current time:  2020-02-19 12:22:13.095605268 +0100 CET m=+19.000385598
// Current time:  2020-02-19 12:22:15.095371885 +0100 CET m=+21.000152174
// Current time:  2020-02-19 12:22:22.095537562 +0100 CET m=+28.000317857
// Current time:  2020-02-19 12:22:24.095431317 +0100 CET m=+30.000211625
// Current time:  2020-02-19 12:22:31.095524308 +0100 CET m=+37.000304595
</code>```

Try it on the playground: https://play.golang.org/p/jDe5uJiRVe2

Body:
I have some function that has to run periodically. I have used a ticker for this. But if the ticker is already running, and the time interval passes again, it should not execute again.

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(3*time.Second)
    flag := 0
    defer ticker.Stop()
    for {
        select {
        case t := <-ticker.C:
            flag = flag + 1
            if (flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
            }
            fmt.Println("Current time: ", t)
        }
    }
}

https://play.golang.org/p/2xV2MYInn4I

In the playground, the ticker prints every 3 seconds, but every even turn of the ticker the job takes more time than the interval. I expect it to not run then and drop those ticks.

How do I do this?

Body:
The ticker channel is buffered, which is why you may see multiple triggers right one after the other. You can prevent that by simply transfering the ticker's values to an unbuffered channel (note also that the time.Time value received from the ticker is not the current time but the time of the last tick):

package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan time.Time) // unbuffered
    ticker := time.NewTicker(3 * time.Second)
    defer ticker.Stop()

    go func() {
        for t := range ticker.C {
            select {
            case c <- t:
            default:
            }
        }
    }()

    for flag := 0; flag < 8; flag++ {
        <-c

        if flag%2 == 0 {
            time.Sleep(time.Second * 4)
        }
        fmt.Println("Current time: ", time.Now())
    }
}

// Output:
// Current time:  2020-02-19 12:21:57.095433032 +0100 CET m=+3.000213350
// Current time:  2020-02-19 12:22:04.095585208 +0100 CET m=+10.000365520
// Current time:  2020-02-19 12:22:06.095363327 +0100 CET m=+12.000143680
// Current time:  2020-02-19 12:22:13.095605268 +0100 CET m=+19.000385598
// Current time:  2020-02-19 12:22:15.095371885 +0100 CET m=+21.000152174
// Current time:  2020-02-19 12:22:22.095537562 +0100 CET m=+28.000317857
// Current time:  2020-02-19 12:22:24.095431317 +0100 CET m=+30.000211625
// Current time:  2020-02-19 12:22:31.095524308 +0100 CET m=+37.000304595

Try it on the playground: https://play.golang.org/p/jDe5uJiRVe2