问:
What's wrong in this loop?
I checked and i don't found errors:

```<code>$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "</br>";
}
</code>```

I  recibe this:

```<code>MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz
</code>```

But I should recibe this:

```<code>MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz
</code>```

Thanks!!

答:
The code you posted is not consistent with the output you presented:

There's no way you get a Miguel in your output as you do:

```<code>$preparado[1] = "Miguel";
$preparado[1] = "Carlos";
</code>```

so the only variable you assign Miguel to, is overwritten the next line.

There is no variable $preparado1.

You should post the code you actually used to generate the output you got.

Title: What's wrong in this loop?

Body:
I checked and i don't found errors:

$_SESSION['variable'] = 2
$preparado[1] = "Miguel";
$preparado[2] = "Carlos";
$segundo[1]= "Beltran";
$segundo[2] = "Sanz";

for($i = 1; $i <=$_SESSION['variable']; $i++){
  $listo[$i] = $preparado1[$i] . $segundo[1];
}

for($i = ($_SESSION['variable'] + 1) ; $i <= ($_SESSION['variable'] * 2); $i++){
  for($n = 1; $n <=$_SESSION['variable']; $n++){
    $listo[$i] = $preparado1[$n] . $segundo[2];
  }
}

for($i = 1;$i <=$_SESSION['variable'] * $_SESSION['extension']; $i++ ){
  echo   $final[$i] . "
";
}

I  recibe this:

MiguelBeltran
CarlosBeltran
CarlosSanz
CarlosSanz

But I should recibe this:

MiguelBeltran
CarlosBeltran
MiguelSanz
CarlosSanz

Thanks!!

Body:
The code you posted is not consistent with the output you presented:

There's no way you get a Miguel in your output as you do:

$preparado[1] = "Miguel";
$preparado[1] = "Carlos";

so the only variable you assign Miguel to, is overwritten the next line.

There is no variable $preparado1.

You should post the code you actually used to generate the output you got.


来源: stackexchange

问:
how to print a message multiple times on multiple different lines?
for starters im new to python and not really good at this kind of thing so dont crusify me ive had bad experiences on reddit.

But, Im able to get user input to repeat the string x amount of times but i cant get it to repeat on different lines.

ive tried \n multiple times (the only thing ive used) in multiple different ways but i just get invalid syntax but i havent really tried to change the base code much.

```<code>age = int(input("how old are you?: "))

agedifference = 100 - age

print ("you will be 100 in",agedifference,"years") * int(input("pick a number: "))
</code>```

so basically i need the user to pick a number for example 4 then repeat the phrase 4 times on 4 different lines.

if you can give a solution with an in depth explanation i would greatly appreciate it (no such thing as to in depth im noob)

答:
Try this (assuming you are on python3):

```<code>age = int(input("how old are you?: "))

agedifference = 100 - age

print(f"you will be 100 in {agedifference} years\n" * int(input("pick a number: ")))
</code>```

For python2:

```<code>age = int(input("how old are you?: "))

agedifference = 100 - age

print("you will be 100 in {} years\n".format(agedifference) * int(input("pick a number: ")))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
for starters im new to python and not really good at this kind of thing so dont crusify me ive had bad experiences on reddit.

But, Im able to get user input to repeat the string x amount of times but i cant get it to repeat on different lines.

ive tried \n multiple times (the only thing ive used) in multiple different ways but i just get invalid syntax but i havent really tried to change the base code much.

age = int(input("how old are you?: "))

agedifference = 100 - age

print ("you will be 100 in",agedifference,"years") * int(input("pick a number: "))

so basically i need the user to pick a number for example 4 then repeat the phrase 4 times on 4 different lines.

if you can give a solution with an in depth explanation i would greatly appreciate it (no such thing as to in depth im noob)

Body:
Try this (assuming you are on python3):

age = int(input("how old are you?: "))

agedifference = 100 - age

print(f"you will be 100 in {agedifference} years\n" * int(input("pick a number: ")))

For python2:

age = int(input("how old are you?: "))

agedifference = 100 - age

print("you will be 100 in {} years\n".format(agedifference) * int(input("pick a number: ")))


问:
How can I use CSS for specific character code?
I want to apply CSS styles to the &#8226 (bullet) character but haven't found out how. Here's what I tried:

```<code>• {
    word-spacing: 1em;
}
</code>```

Can something like this be done? Thanks

答:
Your best bet is to use the bullet point in a span like this:

```<code><span class="custom-bullet">•</span>
</code>```

and then make your changes on the class as shown:

```<code>.custom-bullet {
     word-spacing: 1em;
}
</code>```

Body:
I want to apply CSS styles to the &#8226 (bullet) character but haven't found out how. Here's what I tried:

• {
    word-spacing: 1em;
}

Can something like this be done? Thanks

Body:
Your best bet is to use the bullet point in a span like this:

<span class="custom-bullet">&#8226;</span>

and then make your changes on the class as shown:

.custom-bullet {
     word-spacing: 1em;
}


问:
How to remove properties of objects from a array in javascript?
How to remove a key from an object

This function takes an array of user objects and deletes the moto key-value pair on each user object.

I have tried this code:

```<code>function deleteAllMoto(users) {

   for(var i=0; i<=users.length; i++) {

    delete users[i].password;
    return users[i];

}

</code>```

答:
deleteAllMoto function should be

```<code>function deleteAllMoto(users) {

  for(var i=0; i<=users.length; i++) {
    delete users[i].moto;
  }
  return users;

}
</code>```

Body:
How to remove a key from an object

This function takes an array of user objects and deletes the moto key-value pair on each user object.

I have tried this code:

function deleteAllMoto(users) {

   for(var i=0; i<=users.length; i++) {

    delete users[i].password;
    return users[i];

}

Body:
deleteAllMoto function should be

function deleteAllMoto(users) {

  for(var i=0; i<=users.length; i++) {
    delete users[i].moto;
  }
  return users;

}


答:
There are plenty of solutions for what you want:

The classic for loop:

```<code>for _ in range(num):
    print(f"you will be 100 in {agedifference} years")
</code>```

In python, a print ends the line by default, you can change this behaviour by modifying the end parameter of the function.

The more pythonic one liner:

```<code>print('\n'.join([f"you will be 100 in {agedifference} years"] * num))
</code>```

This one takes advantage of multiple python features:

str.join(iterable) will create a string by concatenating all elements contained in iterable and join them by adding the str in between.

list * int repeats all elements in the list int times.

f-string are one of the many ways to insert variables in string without having to concatenate strings.

Title: how to print a message multiple times on multiple different lines?

Body:
There are plenty of solutions for what you want:

The classic for loop:

for _ in range(num):
    print(f"you will be 100 in {agedifference} years")

In python, a print ends the line by default, you can change this behaviour by modifying the end parameter of the function.

The more pythonic one liner:

print('\n'.join([f"you will be 100 in {agedifference} years"] * num))

This one takes advantage of multiple python features:

str.join(iterable) will create a string by concatenating all elements contained in iterable and join them by adding the str in between.

list * int repeats all elements in the list int times.

f-string are one of the many ways to insert variables in string without having to concatenate strings.


问:
Is there a way to move an Azure Api Management instance to different datacenter?
We have an API Management instance with users and traffic in one datacenter. We would like to move this instance to another datacenter. There seems to be no way of doing this directly through the Azure portal.

We've tried to scale out the API management instance to the desired data center. However, the original instance is not possible to delete since it functions as some sort of 'master' instance. We've also tried backing upp the instance and restoring it to a new instance according to this guide: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-disaster-recovery-backup-restore

This works pretty good, but gives us some other issues since we need to close down the portal for some time to avoid an unsynchronized backup. Further, our DNS needs to be updated.

Is there any alternative to backing up and restoring? What would be best practice to perform this task?

答: There is no zero-downtime way to do that. Backup-restore is your best option.</p>


问:
At what point are request and response objects populated in express app
I’m always coding backend api’s and I don’t really get how express does its bidding with my code. I know what the request and response objects offer, I just don’t understand how they come to be.

This simplified code for instance:

```<code>exports.getBlurts = function() {
    return function(req, res) {

    // build query…

    qry.exec(function(err, results) {
            res.json(results);
        }
    });
  }
}
</code>```

Then I’d call in one of my routes:

```<code>app.get('/getblurts/, middleware.requireUser, routes.api.blurtapi.getBlurts());
</code>```

I get that the function is called upon the route request. It’s very abstract to me though and I don’t understand the when, where, or how as it pertains to the req\res params being injected.

For instance. I use a CMS that modifies the request object by adding a user property, which is then available globally on all requests made whether ajax or otherwise, making it easy at all times to determine if a user is logged in.

Are the req and res objects just pre-cooked by express but allow freedom for them to be modified to your needs? When are they actually 'built'

答:
At its heart express is actually using node's default http-module and passing the express-application as a callback to the http.createServer-function. The request and response objects are populated at that point, i.e. from node itself for every incoming connection. See the nodeJS documentation for more details regarding node's http-module and what req/res are.

You might want to check out express' source code which shows how the express application is passed as a callback to http.createServer.

https://github.com/expressjs/express/blob/master/lib/request.js and https://github.com/expressjs/express/blob/master/lib/response.js show how node's request/response are extended by express specific functions.

Body:
I’m always coding backend api’s and I don’t really get how express does its bidding with my code. I know what the request and response objects offer, I just don’t understand how they come to be.

This simplified code for instance:

exports.getBlurts = function() {
    return function(req, res) {

    // build query…

    qry.exec(function(err, results) {
            res.json(results);
        }
    });
  }
}

Then I’d call in one of my routes:

app.get('/getblurts/, middleware.requireUser, routes.api.blurtapi.getBlurts());

I get that the function is called upon the route request. It’s very abstract to me though and I don’t understand the when, where, or how as it pertains to the req\res params being injected.

For instance. I use a CMS that modifies the request object by adding a user property, which is then available globally on all requests made whether ajax or otherwise, making it easy at all times to determine if a user is logged in.

Are the req and res objects just pre-cooked by express but allow freedom for them to be modified to your needs? When are they actually 'built'


问:
DropDownGallery Object?
I was trying to follow this link to set up a drop down gallery on my ribbon bar using wpf and c#: http://msdn.microsoft.com/en-us/library/dd742868(v=VS.85).aspx

I cannot seem to initialize the dropdowngallery object on my ribbon bar in the xaml there is no option to create one... I have access to all the other ribbon controls besides the gallery controls in the xaml. There is a RibbonGallery object but not any specific gallery controls (DropDown, SplitButton, In-Ribbon) Am I missing something?

答: This blog post includes an example of how to add a Ribbon gallery in WPF. The link you include in your question is for the Win32/MFC version of the Ribbon control, which is different.</p>

ContentLicense: CC BY-SA 3.0

Title: DropDownGallery Object?


问:
Pandas-Insert a first row with sum of a column and then use the previous value-LAG of column
Lets say I have the data like this

```<code>df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
</code>```

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

```<code> MONTHS  METRIC                     MONTHS NEW_METRIC            NEW_METRIC
 1          430                      0       3378                 sum of METRIC
 2          584                      1       3378                 sum of METRIC
 3          648        -->           2       2948     explain  previous value-lag of metric(3378-430)
 4          571                      3       2364              previous value-lag of metric(2948-584)
 5          610                      4       1716              =2364-648
 6          535                      5       1145              =1716-571
                                     6       535               =1145-535
</code>```

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric with previous row value of the same column (3378-430) and similiarly for months3 it would be (2948-584) month4 is (2364-648)etc till the end. I used the following code.

```<code>df["METRIC"].sum() - df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0)
</code>```

but I want the first two values to be sum but later it should take the previous value -df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0). From the months 3 the new metric fails as I need to use previous value instead of sum of metric. How do I correct it?

答:
You can subtract by the cumulative sum.

```<code>df.METRIC.sum() - df.METRIC.reindex(np.arange(df.shape[0]+1)).shift(2).cumsum().fillna(0)
</code>```

```<code>0    3378.0
1    3378.0
2    2948.0
3    2364.0
4    1716.0
5    1145.0
6     535.0
Name: METRIC, dtype: float64
</code>```

Body:
Lets say I have the data like this

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

 MONTHS  METRIC                     MONTHS NEW_METRIC            NEW_METRIC
 1          430                      0       3378                 sum of METRIC
 2          584                      1       3378                 sum of METRIC
 3          648        -->           2       2948     explain  previous value-lag of metric(3378-430)
 4          571                      3       2364              previous value-lag of metric(2948-584)
 5          610                      4       1716              =2364-648
 6          535                      5       1145              =1716-571
                                     6       535               =1145-535

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric with previous row value of the same column (3378-430) and similiarly for months3 it would be (2948-584) month4 is (2364-648)etc till the end. I used the following code.

df["METRIC"].sum() - df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0)

but I want the first two values to be sum but later it should take the previous value -df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0). From the months 3 the new metric fails as I need to use previous value instead of sum of metric. How do I correct it?

Body:
You can subtract by the cumulative sum.

df.METRIC.sum() - df.METRIC.reindex(np.arange(df.shape[0]+1)).shift(2).cumsum().fillna(0)

0    3378.0
1    3378.0
2    2948.0
3    2364.0
4    1716.0
5    1145.0
6     535.0
Name: METRIC, dtype: float64


问:
How to force another parallel component to refresh in react
I have splitted my page into few components and I need to force the other components to refresh their contents on the screen whenever a change happens in one of them.

It is possible to force parent and child components in react js to refresh each other but I wonder how I can handle this scenario when the components are not parent and child .

I know one way is to merge all of them in a single component and handle that but it makes source un-modular.

I have googled this and all the posts are about parent and child components.

Any recommendation would be appreciated.

答:
You should use some form of state management solution, be it redux or the React Context API.
This is the only scalable solution to updating multiple components that are not directly hierarchical. </p>


答:
You can do something like this as well:

You ask the user to input age and you calculate the agedifference.

Then you ask the user to input the times it has to repeat.

Then use a for loop for looping the output the number of times given by the user.

```<code>age = int(input("how old are you?: "))

agedifference = 100 - age

times = int(input("pick a number: "))

for i in range(0,times):
    print ("you will be 100 in",agedifference,"years")
</code>```

Body:
You can do something like this as well:

You ask the user to input age and you calculate the agedifference.

Then you ask the user to input the times it has to repeat.

Then use a for loop for looping the output the number of times given by the user.

age = int(input("how old are you?: "))

agedifference = 100 - age

times = int(input("pick a number: "))

for i in range(0,times):
    print ("you will be 100 in",agedifference,"years")


问:
How to measure wallclock time in C++ instead of cpu time?
I would like to measure wallclock time taken by my algorithm in C++. Many articles point to this code.

```<code>clock_t begin_time, end_time;
begin_time = clock();
Algorithm();
end_time = clock();
cout << ((double)(end_time - begin_time)/CLOCKS_PER_SEC) << endl;
</code>```

But this measures only cpu time taken by my algorithm.
Some other article pointed out this code.

```<code>double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double begin_time, end_time;
begin_time = getUnixTime();
Algorithm();
end_time = getUnixTime();
cout << (double) (end_time - begin_time) << endl;

</code>```

I thought it would print wallclock time taken by my algorithm. But surprisingly, the time printed by this code is much lower than cpu time printed by previous code. So, I am confused. Please provide code for printing wallclock time.

答:
I'm getting approximately the same times in a single threaded program:

```<code>#include <time.h>
#include <stdio.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) { for(unsigned long i=0; i<Cnt;i++) nop(); }
int main()
{
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));
}
//prints 2 and 3 or 2 and 2 on my system
</code>```

But clocks manpage only describes it as returning an approximation. There's no indication that approximation is comparable to what clock_gettime returns.

Where I get drastically different results is where I throw in multiple threads:

```<code>#include <time.h>
#include <stdio.h>
#include <pthread.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) {
    for(unsigned long i=0; i<Cnt;i++) nop();
}
void *busy(void *A){ (void)A; for(;;) nop(); }
int main()
{
    pthread_t ptids[4];
    for(size_t i=0; i<sizeof(ptids)/sizeof(ptids[0]); i++)
        pthread_create(&ptids[i], 0, busy, 0);
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));

}
//prints 18 and 4 on my 4-core linux system
</code>```

That's because both musl and glibc on Linux use clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) to implement clock() and the CLOCK_PROCESS_CPUTIME_ID nonstandard clock is described in the clock_gettime manpage as returning time for all process threads together.

Body:
I would like to measure wallclock time taken by my algorithm in C++. Many articles point to this code.

clock_t begin_time, end_time;
begin_time = clock();
Algorithm();
end_time = clock();
cout << ((double)(end_time - begin_time)/CLOCKS_PER_SEC) << endl;

But this measures only cpu time taken by my algorithm.
Some other article pointed out this code.

double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double begin_time, end_time;
begin_time = getUnixTime();
Algorithm();
end_time = getUnixTime();
cout << (double) (end_time - begin_time) << endl;

I thought it would print wallclock time taken by my algorithm. But surprisingly, the time printed by this code is much lower than cpu time printed by previous code. So, I am confused. Please provide code for printing wallclock time.

Body:
I'm getting approximately the same times in a single threaded program:

#include <time.h>
#include <stdio.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) { for(unsigned long i=0; i<Cnt;i++) nop(); }
int main()
{
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));
}
//prints 2 and 3 or 2 and 2 on my system

But clocks manpage only describes it as returning an approximation. There's no indication that approximation is comparable to what clock_gettime returns.

Where I get drastically different results is where I throw in multiple threads:

#include <time.h>
#include <stdio.h>
#include <pthread.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) {
    for(unsigned long i=0; i<Cnt;i++) nop();
}
void *busy(void *A){ (void)A; for(;;) nop(); }
int main()
{
    pthread_t ptids[4];
    for(size_t i=0; i<sizeof(ptids)/sizeof(ptids[0]); i++)
        pthread_create(&ptids[i], 0, busy, 0);
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));

}
//prints 18 and 4 on my 4-core linux system

That's because both musl and glibc on Linux use clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) to implement clock() and the CLOCK_PROCESS_CPUTIME_ID nonstandard clock is described in the clock_gettime manpage as returning time for all process threads together.


问:
RestSharp Response Content Always Null But Still Logs With Execute
When sending a basic GET the response.Content is always NULL on return. The weird thing is that it will log the content on the standard execute, but not on the async. I'm at my wit's end. Any help would be appreciated.

I tried using the standard client.Execute and client.ExecuteAsync and both seem to have the same result, except for the logging part.

The regular method (with identifying info X'd out):

```<code>                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXX");

                Serilog.Log.Information($"Request is {request}");

                IRestResponse response = myClient.Execute(request);
                var htmlString = response.Content;
                Serilog.Log.Information($"Request is {response.Content}");

                return htmlString;
</code>```

The executeAsync method:

```<code>                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXXXXXXXXX");

                Serilog.Log.Information($"Request is {request}");
                var htmlString = "";
                myClient.ExecuteAsync(request, response =>
                {
                    htmlString = response.Content;
                    Serilog.Log.Information($"Response is {response.Content}");
                });
                return htmlString;
</code>```

Obviously I want it to both log AND return the actual content. Ok, gurus, what am I doing wrong?

答: You have to be kidding me. It was working all the time (at least the regular execute), but there was so much whitespace at the beginning of the string that VS 2017 didn't display it as a local. I had to really drill down to see it. </p>

Body:
When sending a basic GET the response.Content is always NULL on return. The weird thing is that it will log the content on the standard execute, but not on the async. I'm at my wit's end. Any help would be appreciated.

I tried using the standard client.Execute and client.ExecuteAsync and both seem to have the same result, except for the logging part.

The regular method (with identifying info X'd out):

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXX");

                Serilog.Log.Information($"Request is {request}");

                IRestResponse response = myClient.Execute(request);
                var htmlString = response.Content;
                Serilog.Log.Information($"Request is {response.Content}");

                return htmlString;

The executeAsync method:

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXXXXXXXXX");

                Serilog.Log.Information($"Request is {request}");
                var htmlString = "";
                myClient.ExecuteAsync(request, response =>
                {
                    htmlString = response.Content;
                    Serilog.Log.Information($"Response is {response.Content}");
                });
                return htmlString;

Obviously I want it to both log AND return the actual content. Ok, gurus, what am I doing wrong?


问:
React error when using audio.play() function
I'm trying to play a sound by triggering the function with onClick event in React and I'm getting the following error:

Uncaught Error: The error you provided does not contain a stack trace.

at B (index.js:1582)

at G (index.js:1899)

at eval (index.js:1914)

at eval (index.js:1933)

at eval (index.js:1414)

```<code>import React from "react";
import firebase from "../../firebase";
import classes from "./Sidenav.module.sass";

const Sidenav = props => {
  const logout = () => {
    firebase.auth().signOut();
    window.location.href = "..";
  };

  const playAudio = () => {
    let audio = new Audio("../../assets/bellNotification.mp3");
    audio.play();
  };

  return (
    <div style={props.styles.sideNavDiv} className={classes.sidenavDiv}>
      <i />
      <div style={props.styles.iconDiv} className={classes.iconDiv}>
        <i className={"material-icons " + classes.navIcon}>account_box</i>
        <p className={classes.iconText}>Account</p>
      </div>
      <div style={props.styles.iconDiv} className={classes.iconDiv}>
        <i className={"material-icons " + classes.navIcon}>settings</i>
        <p className={classes.iconText}>Settings</p>
      </div>
      <div style={props.styles.iconDiv} className={classes.iconDiv}>
        <i className={"material-icons " + classes.navIcon}>trending_up</i>
        <p className={classes.iconText}>Check Progress</p>
      </div>
      <div style={props.styles.iconDiv} className={classes.iconDiv}>
        <i className={"material-icons " + classes.navIcon}>looks_one</i>
        <p className={classes.iconText}>1RM calculator</p>
      </div>
      <div
        onClick={props.toggleModal}
        style={props.styles.iconDiv}
        className={classes.iconDiv}
      >
        <i className={"material-icons " + classes.navIcon}>alarm</i>
        <p className={classes.iconText}>Edit timers</p>
      </div>
      <div
        onClick={playAudio}
        style={props.styles.iconDiv}
        className={classes.iconDiv}
      >
        <i className={"material-icons " + classes.navIcon}>help</i>
        <p className={classes.iconText}>Help</p>
      </div>
      <div
        onClick={logout}
        style={props.styles.iconDiv}
        className={classes.iconDiv}
      >
        <i className={"material-icons " + classes.navIcon}>
          power_settings_new
        </i>
        <p className={classes.iconText}>Logout</p>
      </div>
    </div>
  );
};

export default Sidenav;

</code>```

答:
Okay, I managed to fix my problem. This error is caused because the new Audio(url).play() points to the index.html in the public folder and for some reason it doesn't seem to work in the root div in my case. I created the audio element in the index.html file and moved the mp3 file to the public folder.

<audio id="audio"><source src="bellNotification.mp3" type="audio/mpeg"></source></audio>

I changed the function like this

const playAudio = () => {
    document.getElementById("audio").play();
 };

It works for me but I hope that someone can fix this problem with pure js without accessing the html file.

Body:
I'm trying to play a sound by triggering the function with onClick event in React and I'm getting the following error:

Uncaught Error: The error you provided does not contain a stack trace.

at B (index.js:1582)

at G (index.js:1899)

at eval (index.js:1914)

at eval (index.js:1933)

at eval (index.js:1414)

import React from "react";
import firebase from "../../firebase";
import classes from "./Sidenav.module.sass";

const Sidenav = props => {
  const logout = () => {
    firebase.auth().signOut();
    window.location.href = "..";
  };

  const playAudio = () => {
    let audio = new Audio("../../assets/bellNotification.mp3");
    audio.play();
  };

  return (

        account_box

Account

        settings

Settings

        trending_up

Check Progress

        looks_one

1RM calculator

        alarm

Edit timers

        help

Help

          power_settings_new

Logout

  );
};

export default Sidenav;


问:
Matplotlib imshow() collapsing for axes values of different orders of magnitude
I am trying to plot a heatmap using imshow(). When my x and y data values are all of similar order of magnitude, it works fine. However, if x and y are different orders of magnitude (for example, all 0 < x < 1.0 and all y > 1.0), it collapses the plot along the axis with small numbers, as below. How do I avoid this?

<img src="https://lh3.googleusercontent.com/_93QjB5-MR3qjzx6BhsVroZEvJZc89MxYsXWxNkEi0kv2oFYUoTW2CPpIEkt0UjyE8ui4ja5jmWxDvTjYoZ11E_5HcHec2D-QJcQ1B3qCl44h4giVrQPRZ6oPi1R0ON1gokJ8ya-4zCOUj23M5thaBmuwzNq1-n8TxQ-_dzJ-MSalk58hle7VmMvd7Gr2pJfKwaW413XlvB3Cr-1A5Vp6rtXEcFJFmpLOGmSUWoBKtczUxYvDiWXV9_b_McANJe5TjIfPuehj4-znGX6hI-vhQx0KoIFmDOhoCOuwHXvWvrW81GcrY-HpnM94iPyw2YaK-cMZhj7Zv--8DZz9lz6VvG-kpGHe_iQTd4r5zw-z0zeHLvjFByg3t3mdB0WFzj0MEhLeX5MLWLcxAbK34-HvRXxDn56S5qKlvbYs00jZs2eud81LR9kjUV3WKSWjx3OxXvKSYsvHH5fhle9ZLEOTkmWXQZaRnPKyoZfCOxUlMEWteqhE3VuYOYr9aaC8xofgjZEpjCeOBLdWwVaT4hNF4TiO5o6Cm06CD8LrjzzbR4u7gSkRzQubQZNYWbANYHPK--Cb5psz2ags2z7WRt1DDrcjKxjwqmPb7lgC5r9M6Zf9jp9ordN6Cxp6k6PpNZtlb61a7lWx7F6D9Vu40bcyALQgssbbguPuThMBzQKsxP2Y4zIjWeC4KF8h0V9NOCbgdq-c76_37xAdHpwQXdrh4p3jA=w107-h469-no" alt="plot">

答:
Stumbled on this question (wasn't finding it before because of my phrasing/keyword differences), which has the answer I'm looking for.

figure of imshow() is too small

I'll leave my question here as a pointer in case anyone else uses my search terms.

What's happening (explained on the link) is that imshow defaults to having its aspect parameter default to "equal", which causes the behavior described in my initial question. To fix this, set aspect="auto". For example:

```<code>ax.imshow(data, aspect="auto", **kwargs)
</code>```

Body:
Stumbled on this question (wasn't finding it before because of my phrasing/keyword differences), which has the answer I'm looking for.

figure of imshow() is too small

I'll leave my question here as a pointer in case anyone else uses my search terms.

What's happening (explained on the link) is that imshow defaults to having its aspect parameter default to "equal", which causes the behavior described in my initial question. To fix this, set aspect="auto". For example:

ax.imshow(data, aspect="auto", **kwargs)


问:
Best way to search data in xml files?
In our new project we have to provide a search functionality to retrieve data from hundreds of xml files. I have a brief of our current plan below, I would like to know your suggestions/improvements on this.

These xml files contain personal information, and the search is based on 10 elements in it for example last name, first name, email etc. Our current plan is to create an master XmlDocument with all the searchable data and a key to the actual file. So that when the user searches the data we first look at master file and get the the results. We will also cache the actual xml files from the recent searches so simillar searches later can be handled quickly.

Our application is a .net 2.0 web application.

答:
First: how big are the xml files? XmlDocument doesn't scale to "huge"... but can handle "large" OK.

Second: can you perhaps put the data into a regular database structure (perhaps SQL Server Express Edition), index it, and access via regular TSQL? That will usually out-perform an xpath search. Equally, if it is structured, SQL Server 2005 and above supports the xml data-type, which shreds data - this allows you to index and query xml data in the database without having the entire DOM in memory (it translates xpath into relational queries).

OwnerDisplayName: gk

ContentLicense: CC BY-SA 2.5

Title: Best way to search data in xml files?

OwnerDisplayName: Marc Gravell


问:
HTML String in Objective-C
I have a web view which loads HTML string.
The code is under

```<code>[self.wvAttributes loadHTMLString:[product.additional_Info stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"] baseURL:nil];
</code>```

and result is under:

I want to align this text to Right, I'm not good in Objective-C so please help me to do that.

Thank in advance.

答:
You should change the text alignment in css. If you don't have access to the css file try this</p>

```<code>NSString *htmltring = [product.additional_Info stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];
htmltring = [htmltring stringByReplacingOccurrencesOfString:@"text-align: left" withString:@"text-align: right"];
[self.wvAttributes loadHTMLString:htmltring baseURL:nil];
</code>```

Title: HTML String in Objective-C

Body:
I have a web view which loads HTML string.
The code is under

[self.wvAttributes loadHTMLString:[product.additional_Info stringByReplacingOccurrencesOfString:@"\n" withString:@"
"] baseURL:nil];

and result is under:

I want to align this text to Right, I'm not good in Objective-C so please help me to do that.

Thank in advance.

Body:
You should change the text alignment in css. If you don't have access to the css file try this

NSString *htmltring = [product.additional_Info stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];
htmltring = [htmltring stringByReplacingOccurrencesOfString:@"text-align: left" withString:@"text-align: right"];
[self.wvAttributes loadHTMLString:htmltring baseURL:nil];


问:
Is there an way to make loading progress bar run again in visjs?
I have created a new network visualization using visjs and I follow the example here: http://visjs.org/examples/network/exampleApplications/loadingBar.html to implement a loading progress bar and it worked perfectly.
I can switch to other 2 visualizations using a radio button. When I load the other visualizations the loading bar doesn't appear again.
I would like to know how to call the loading bar again.
Thanks in advance.

...
<input type="radio" name="op" onclick="net1()" checked>
<input type="radio" name="op" onclick="net2()">

0%

```

答:
I solved it changing the methods stabilizationProgress and stabilizationIterationsDone to:

```<code>network.on("stabilizationProgress", function (params) {
    document.getElementById('loadingBar').style.opacity = 1;
    var maxWidth = 496;
    var minWidth = 20;
    var widthFactor = params.iterations / params.total;
    var width = Math.max(minWidth, maxWidth * widthFactor);
    document.getElementById('bar').style.width = width + 'px';
    document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
});
network.on("stabilizationIterationsDone", function () {
    document.getElementById('text').innerHTML = '100%';
    document.getElementById('bar').style.width = '496px';
    document.getElementById('loadingBar').style.opacity = 0;
});
</code>```

Body:
I solved it changing the methods stabilizationProgress and stabilizationIterationsDone to:

network.on("stabilizationProgress", function (params) {
    document.getElementById('loadingBar').style.opacity = 1;
    var maxWidth = 496;
    var minWidth = 20;
    var widthFactor = params.iterations / params.total;
    var width = Math.max(minWidth, maxWidth * widthFactor);
    document.getElementById('bar').style.width = width + 'px';
    document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
});
network.on("stabilizationIterationsDone", function () {
    document.getElementById('text').innerHTML = '100%';
    document.getElementById('bar').style.width = '496px';
    document.getElementById('loadingBar').style.opacity = 0;
});


问:
assign variables to argparse not through command line
I am trying to write tests (using pytest) for a script, but I don't know how to create/pass arguments to main(), especially when it doesn't recieve arguments. and even if I change it to def main(args = None): then it'll initiate it on the first line.

tests.py

```<code>def test_main(capfd):
    main()
    out, err = capfd.readouterr()
    assert out == "my expected output"
</code>```

script.py

```<code>def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default=[sys.stdin],
                        help='the name of the file(s) to search.')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u', '--underscore', action='store_true', help='prints \
                       "^" under the matching text.')
    group.add_argument('-c', '--color', action='store_true', help='highlights \
                       matching text.')
    group.add_argument('-m', '--machine', action='store_true', help='generates \
                       machine readable output.')

    return parser

def main():
    args = init_parser().parse_args()
    for file in args.infile:
        for i, line in enumerate(iter(file.readline, '')):
            for substring in re.finditer(args.regex, line):
                    if args.underscore:
                        underscore_output(file.name, i + 1, line[:-1],
                                          substring.start(), substring.end())
                    elif args.color:
                        color_output(file.name, i + 1, line[:-1],
                                     substring.group())
                    elif args.machine:
                        machine_output(file.name, i + 1, substring.start(),
                                       substring.group())
                    else:
                        print_line(file.name, i + 1, line[:-1])```
```

答:
parse_args can take an explicit None argument to tell it to parse sys.argv[1:]. Write your code so that it can be easily tested:

```<code>def main(args=None):
    args = init_parser().parse_args(args)
    ...
</code>```

In production use, you'll call main() to let it parse sys.argv. For tests, you'll pass a specific set of arguments.

```<code>def test_main(capfd):
    main(['[a-z]*', 'foo.txt', '-u'])  # For example
    out, err = capfd.readouterr()
    assert out == "my expected output"
</code>```

Body:
I am trying to write tests (using pytest) for a script, but I don't know how to create/pass arguments to main(), especially when it doesn't recieve arguments. and even if I change it to def main(args = None): then it'll initiate it on the first line.

tests.py

def test_main(capfd):
    main()
    out, err = capfd.readouterr()
    assert out == "my expected output"

script.py

def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default=[sys.stdin],
                        help='the name of the file(s) to search.')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u', '--underscore', action='store_true', help='prints \
                       "^" under the matching text.')
    group.add_argument('-c', '--color', action='store_true', help='highlights \
                       matching text.')
    group.add_argument('-m', '--machine', action='store_true', help='generates \
                       machine readable output.')

    return parser

def main():
    args = init_parser().parse_args()
    for file in args.infile:
        for i, line in enumerate(iter(file.readline, '')):
            for substring in re.finditer(args.regex, line):
                    if args.underscore:
                        underscore_output(file.name, i + 1, line[:-1],
                                          substring.start(), substring.end())
                    elif args.color:
                        color_output(file.name, i + 1, line[:-1],
                                     substring.group())
                    elif args.machine:
                        machine_output(file.name, i + 1, substring.start(),
                                       substring.group())
                    else:
                        print_line(file.name, i + 1, line[:-1])```

Body:
parse_args can take an explicit None argument to tell it to parse sys.argv[1:]. Write your code so that it can be easily tested:

def main(args=None):
    args = init_parser().parse_args(args)
    ...

In production use, you'll call main() to let it parse sys.argv. For tests, you'll pass a specific set of arguments.

def test_main(capfd):
    main(['[a-z]*', 'foo.txt', '-u'])  # For example
    out, err = capfd.readouterr()
    assert out == "my expected output"


问:
How to close or dismiss a modal dialog
I have a modal dialog which I need to close/dismiss after I have identified it's presence and extracted it's text. The modal comes up when I click on the button to download a file and it says "Generating the debuginfo file. Please wait." This modal is present until the file download starts which is too long depending upon the debuginfo file size. Is there a way to close this dialog and exit with text extracted from it.

I am extracting the text using following code:

```<code>downloadText = WebDriverWait(self.driver,40).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widgetcontent#dialog"))).get_attribute("innerHTML").split(">")[1]
</code>```

Following is the html code for this modal:

```<code>     <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
     <span id="ui-id-1" class="ui-dialog-title">Download debug info</span>
     <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
       <span class="ui-button-icon-primary ui-icon ui-icon-closethick">
       </span>
       <span class="ui-button-text">close</span>
     </button>
   </div>
   <div id="dialog" class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 0px; max-height: none; height: 177px;">
     <br>Generating the debuginfo file. Please wait.</div>
     <div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;">

 </div> ```
```

答:
Based on the sample code provided in the Original Post, you should be able to close the dialog with the below xpath.

```<code> //span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']
</code>```

Here is the script to click on the element even if it's not visible.

```<code>ele = driver.find_element_by_xpath("//span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']")
driver.execute_script("arguments[0].click();",ele)
</code>```

Title: How to close or dismiss a modal dialog

Body:
I have a modal dialog which I need to close/dismiss after I have identified it's presence and extracted it's text. The modal comes up when I click on the button to download a file and it says "Generating the debuginfo file. Please wait." This modal is present until the file download starts which is too long depending upon the debuginfo file size. Is there a way to close this dialog and exit with text extracted from it.

I am extracting the text using following code:

downloadText = WebDriverWait(self.driver,40).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widgetcontent#dialog"))).get_attribute("innerHTML").split(">")[1]

Following is the html code for this modal:

     Download debug info
     <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">

       close
     </button>

Generating the debuginfo file. Please wait.

 ```

Body:
Based on the sample code provided in the Original Post, you should be able to close the dialog with the below xpath.

 //span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']

Here is the script to click on the element even if it's not visible.

ele = driver.find_element_by_xpath("//span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']")
driver.execute_script("arguments[0].click();",ele)


问:
Prestashop 1.6 and SwiftMailer with PHP version 5.6 - fsockopen error
I have an issue with sending mail using the version of Swiftmailer that came with PS1.6

Swift Error: The SMTP connection failed to start [ssl://mail.wineofthemonth.co.za:465]: fsockopen returned Error Number 0 and Error String ''

This is due to the fact that since PHP 5.6 the verify_peer option is set to true by default.

Now I have found various instructions on how to set verify peer to false:

```<code>$https['ssl']['verify_peer'] = FALSE;
$https['ssl']['verify_peer_name'] = FALSE;
</code>```

The issue is that there is no place to set this in the version of Swiftmailer that is being used in Prestashop.

So my question is, where in class/mail.php or anywhere else would I set verify_peer to false?

Here is the line in mail.php that I think pertains to this:

```<code>$connection = new Swift_Connection_SMTP(
                    $configuration['PS_MAIL_SERVER'],
                    $configuration['PS_MAIL_SMTP_PORT'],
                    $configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : (($configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF))
                );
</code>```

There is also a sendMailtest method that could lend more clarity:

```<code>public static function sendMailTest($smtpChecked, $smtpServer, $content, $subject, $type, $to, $from, $smtpLogin, $smtpPassword, $smtpPort = 25, $smtpEncryption)
    {
        $result = false;
        try {
            if ($smtpChecked)
            {
                $smtp = new Swift_Connection_SMTP($smtpServer, $smtpPort, ($smtpEncryption == 'off') ?
                    Swift_Connection_SMTP::ENC_OFF : (($smtpEncryption == 'tls') ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_SSL));
                $smtp->setUsername($smtpLogin);
                $smtp->setpassword($smtpPassword);
                $smtp->setTimeout(5);
                $swift = new Swift($smtp, Configuration::get('PS_MAIL_DOMAIN'));
            }
            else
                $swift = new Swift(new Swift_Connection_NativeMail(), Configuration::get('PS_MAIL_DOMAIN'));

            $message = new Swift_Message($subject, $content, $type);

            if ($swift->send($message, $to, $from))
                $result = true;

            $swift->disconnect();
        } catch (Swift_ConnectionException $e) {
            $result = $e->getMessage();
        } catch (Swift_Message_MimeException $e) {
            $result = $e->getMessage();
        }

        return $result;
    }
</code>```

Alternatively, where in any conf or ini file, could I set verify_peer to false?

Prestashop 1.6.1.1 to 1.6.1.4 are affected.

答:
This works for me:

Open the file /tools/swift/classes/Swift/Transport/StreamBuffer.php

On line 263, just before $this->_stream =, add these two lines:

$options['ssl']['verify_peer'] = FALSE;

$options['ssl']['verify_peer_name'] = FALSE;

The code should now looks like this:

```<code>[...]

$options = array();
if (!empty($this->_params['sourceIp'])) {
    $options['socket']['bindto'] = $this->_params['sourceIp'].':0';
}
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
$this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));

[...]
</code>```

I hope this helps!

Body:
I have an issue with sending mail using the version of Swiftmailer that came with PS1.6

Swift Error: The SMTP connection failed to start [ssl://mail.wineofthemonth.co.za:465]: fsockopen returned Error Number 0 and Error String ''

This is due to the fact that since PHP 5.6 the verify_peer option is set to true by default.

Now I have found various instructions on how to set verify peer to false:

$https['ssl']['verify_peer'] = FALSE;
$https['ssl']['verify_peer_name'] = FALSE;

The issue is that there is no place to set this in the version of Swiftmailer that is being used in Prestashop.

So my question is, where in class/mail.php or anywhere else would I set verify_peer to false?

Here is the line in mail.php that I think pertains to this:

$connection = new Swift_Connection_SMTP(
                    $configuration['PS_MAIL_SERVER'],
                    $configuration['PS_MAIL_SMTP_PORT'],
                    $configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : (($configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF))
                );

There is also a sendMailtest method that could lend more clarity:

public static function sendMailTest($smtpChecked, $smtpServer, $content, $subject, $type, $to, $from, $smtpLogin, $smtpPassword, $smtpPort = 25, $smtpEncryption)
    {
        $result = false;
        try {
            if ($smtpChecked)
            {
                $smtp = new Swift_Connection_SMTP($smtpServer, $smtpPort, ($smtpEncryption == 'off') ?
                    Swift_Connection_SMTP::ENC_OFF : (($smtpEncryption == 'tls') ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_SSL));
                $smtp->setUsername($smtpLogin);
                $smtp->setpassword($smtpPassword);
                $smtp->setTimeout(5);
                $swift = new Swift($smtp, Configuration::get('PS_MAIL_DOMAIN'));
            }
            else
                $swift = new Swift(new Swift_Connection_NativeMail(), Configuration::get('PS_MAIL_DOMAIN'));

            $message = new Swift_Message($subject, $content, $type);

            if ($swift->send($message, $to, $from))
                $result = true;

            $swift->disconnect();
        } catch (Swift_ConnectionException $e) {
            $result = $e->getMessage();
        } catch (Swift_Message_MimeException $e) {
            $result = $e->getMessage();
        }

        return $result;
    }

Alternatively, where in any conf or ini file, could I set verify_peer to false?

Prestashop 1.6.1.1 to 1.6.1.4 are affected.

Body:
This works for me:

Open the file /tools/swift/classes/Swift/Transport/StreamBuffer.php

On line 263, just before $this->_stream =, add these two lines:

$options['ssl']['verify_peer'] = FALSE;

$options['ssl']['verify_peer_name'] = FALSE;

The code should now looks like this:

[...]

$options = array();
if (!empty($this->_params['sourceIp'])) {
    $options['socket']['bindto'] = $this->_params['sourceIp'].':0';
}
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
$this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));

[...]

I hope this helps!


问:
Vector entries changing?
I have uploaded a SQL table to R and I am trying to replace NAs with a replacement. For some reason, the vector entries are changing from A,B,C to 1,2,3

```<code>unique(p$Grade)
[1] <NA> A    B    C
Levels: A B C

qq=ifelse(is.na(p$Grade) & p$Decision_FICO>740,"A",ifelse(is.na(p$Grade) & p$Decision_FICO>680,"B","C"))

unique(qq)
[1] "B" "A" "C"

x=cbind(p$Grade,qq)

View(x)
</code>```

When I view x, I see 2 columns, 1 named V1 and the other named qq.  I expected to see Grade and qq.

I also expected the entries in the V1 column to be A,B, or C but they are 1,2 or 3.

Any thoughts?

答:
I think it turned out to be a function of level of factors (but not 100% sure).

The following worked as a solution to what I was ultimately trying to do.

```<code>Grade2 <- ifelse(is.na(Originations$Grade) & Originations$Decision_FICO>740,"A",ifelse(is.na(Originations$Grade) &Originations$Decision_FICO>680,"B",ifelse(is.na(Originations$Grade),"C",Originations$Grade)))

z = cbind(Originations$Grade,Grade2)

unique(z)
</code>```

Another solution is as follows:

```<code>Grade1 <- Originations$Grade
Grade1[is.na(Originations$Grade)] <- "C"
Grade1[is.na(Originations$Grade) & Originations$Decision_FICO>740] <- "A"
Grade1[is.na(Originations$Grade) & Originations$Decision_FICO<=740 & Originations$Decision_FICO>680] <- "B"

unique(Grade1)

y = cbind(Originations$Grade,Grade1)

unique(y)
</code>```

Title: Vector entries changing?

Body:
I have uploaded a SQL table to R and I am trying to replace NAs with a replacement. For some reason, the vector entries are changing from A,B,C to 1,2,3

unique(p$Grade)
[1] <NA> A    B    C
Levels: A B C

qq=ifelse(is.na(p$Grade) & p$Decision_FICO>740,"A",ifelse(is.na(p$Grade) & p$Decision_FICO>680,"B","C"))

unique(qq)
[1] "B" "A" "C"

x=cbind(p$Grade,qq)

View(x)

When I view x, I see 2 columns, 1 named V1 and the other named qq.  I expected to see Grade and qq.

I also expected the entries in the V1 column to be A,B, or C but they are 1,2 or 3.

Any thoughts?

Body:
I think it turned out to be a function of level of factors (but not 100% sure).

The following worked as a solution to what I was ultimately trying to do.

Grade2 <- ifelse(is.na(Originations$Grade) & Originations$Decision_FICO>740,"A",ifelse(is.na(Originations$Grade) &Originations$Decision_FICO>680,"B",ifelse(is.na(Originations$Grade),"C",Originations$Grade)))

z = cbind(Originations$Grade,Grade2)

unique(z)

Another solution is as follows:

Grade1 <- Originations$Grade
Grade1[is.na(Originations$Grade)] <- "C"
Grade1[is.na(Originations$Grade) & Originations$Decision_FICO>740] <- "A"
Grade1[is.na(Originations$Grade) & Originations$Decision_FICO<=740 & Originations$Decision_FICO>680] <- "B"

unique(Grade1)

y = cbind(Originations$Grade,Grade1)

unique(y)


问:
how to set firebase cloud firestore security rules with firebase authentication
I have created a database cloud firestore. In this database I want anyone to be able to read and write if: request.auth.uid != null now an facing a permission problem when someone is trying to login or sign up using email and password with firebase authentication. I get insufficient permission. How can I let any of my users sign up and login at the same time protect the other part of the database

答:
This rule should be good enough.

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /YOUR_COLLECTION_NAME/{doc} {
       allow write, read: request.auth.uid != null
    }
  }
}
</code>```

But are you sure you are setting your authentication properly?

Check Authentication -> Sign-in Method and make sure you enable the providers you need. Using the Firebase sdk for auth you will be able to pass this validation after you log in your user. Take a look a this

Body:
This rule should be good enough.

service cloud.firestore {
  match /databases/{database}/documents {
    match /YOUR_COLLECTION_NAME/{doc} {
       allow write, read: request.auth.uid != null
    }
  }
}

But are you sure you are setting your authentication properly?

Check Authentication -> Sign-in Method and make sure you enable the providers you need. Using the Firebase sdk for auth you will be able to pass this validation after you log in your user. Take a look a this


问:
Need recommendation regarding rabbitmq
I am creating an chat application where I have a rest API and a socket.io server, What I want to do is the user will send messages to rest API, The api will persist those messages in database and then send these messages to the rabbimq queue then rabbitmq will send these messages to socket.io if the receiving user is online, Else the message will be stored in the queue and when the user will come online the user will retrieve these messages from the queue however I want to implement this in a way like whatsapp, The messages will be for a particular user and the user will only receive those messages which are meant for them i.e I don't want to broadcast messages I want only particular user to receive those messages</p>

答: Chat should be a near-real-time application, there are multiple ways of modeling such a thing. First of all, you can use HTTP pooling, HTTP long pooling but some time ago there where introduced the new application-level protocol - web socket. It would be good for you, along with Stomp messages. Here you can check a brief example. And sending messages to specific users is also supported out-of-the-box example

Title: Need recommendation regarding rabbitmq


问:
SQL return more than 1 value query
I have a problem with updating OR INSERTING a column based on condition. I want to be able to insert a variable if the reference number has not existed before in the table and if it exists then it should update. My question is that the @checklistscore is returning more than one row. When I did select @checklistscore it is giving the same error. How can I resolve this </p>

```<code>  SET XACT_ABORT ON;
DECLARE @TRANSACTION VARCHAR(20) = 'EXAMPLE';
BEGIN TRAN @TRANSACTION
DECLARE @checklistscore INT;

SET @checklistscore = (SELECT
      CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN NULL
        ELSE
        (
          CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  IN (2, 3, 50001, 50003, 50004, 50005, 50006, 50020, 50027, 50028) THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100

    END  FROM DB.D_CHECK_LIST   INNER JOIN DB.D_ENERGY_REFERENCE ON  D_CHECK_LIST.ID =D_ENERGY_REFERENCE.ID AND D_ENERGY_REFERENCE.REFERENCE = 19051
    GROUP BY D_CHECK_LIST.ID)

BEGIN

IF
    /* CHECKLIST TO UPDATE*/
    (EXISTS
        (SELECT *
        FROM    DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
                ,DB.D_CHECK_LIST D_CHECK_LIST
        WHERE   D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
        AND     D_ENERGY_REFERENCE.REFERENCE = 19051

        )
)

BEGIN
UPDATE DB.D_ENERGY_REFERENCE
SET D_ENERGY_REFERENCE.VALUE_INTEGER =  @checklistscore
FROM DB.D_ENERGY_REFERENCE
INNER JOIN DB.D_CHECK_LIST D_CHECK_LIST ON D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
WHERE  D_ENERGY_REFERENCE.REFERENCE = 19051

END

ELSE

BEGIN

INSERT INTO DB.D_ENERGY_REFERENCE(ID, REFERENCE_NO, REFERENCE,VALUE_INTEGER)
(SELECT ID,
                (SELECT  ISNULL(MAX(REFERENCE_NO), 0) + 1 FROM DB.D_ENERGY_REFERENCE),
                19051,  @checklistscore

FROM DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE

GROUP BY D_ENERGY_REFERENCE.ID
)

END
</code>```

答:
I think what you'll need to do is replace your variable with a temporary table. The temporary table can store 1 row for every ID. Then, your second half of your script will want to join with the temporary table using ID as the join condition and update every row, that way.

(Reposted my comment as a suggested answer.)

Title: SQL return more than 1 value query

Body:
I have a problem with updating OR INSERTING a column based on condition. I want to be able to insert a variable if the reference number has not existed before in the table and if it exists then it should update. My question is that the @checklistscore is returning more than one row. When I did select @checklistscore it is giving the same error. How can I resolve this

  SET XACT_ABORT ON;
DECLARE @TRANSACTION VARCHAR(20) = 'EXAMPLE';
BEGIN TRAN @TRANSACTION
DECLARE @checklistscore INT;

SET @checklistscore = (SELECT
      CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN NULL
        ELSE
        (
          CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  IN (2, 3, 50001, 50003, 50004, 50005, 50006, 50020, 50027, 50028) THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100

    END  FROM DB.D_CHECK_LIST   INNER JOIN DB.D_ENERGY_REFERENCE ON  D_CHECK_LIST.ID =D_ENERGY_REFERENCE.ID AND D_ENERGY_REFERENCE.REFERENCE = 19051
    GROUP BY D_CHECK_LIST.ID)

BEGIN

IF
    /* CHECKLIST TO UPDATE*/
    (EXISTS
        (SELECT *
        FROM    DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
                ,DB.D_CHECK_LIST D_CHECK_LIST
        WHERE   D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
        AND     D_ENERGY_REFERENCE.REFERENCE = 19051

        )
)

BEGIN
UPDATE DB.D_ENERGY_REFERENCE
SET D_ENERGY_REFERENCE.VALUE_INTEGER =  @checklistscore
FROM DB.D_ENERGY_REFERENCE
INNER JOIN DB.D_CHECK_LIST D_CHECK_LIST ON D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
WHERE  D_ENERGY_REFERENCE.REFERENCE = 19051

END

ELSE

BEGIN

INSERT INTO DB.D_ENERGY_REFERENCE(ID, REFERENCE_NO, REFERENCE,VALUE_INTEGER)
(SELECT ID,
                (SELECT  ISNULL(MAX(REFERENCE_NO), 0) + 1 FROM DB.D_ENERGY_REFERENCE),
                19051,  @checklistscore

FROM DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE

GROUP BY D_ENERGY_REFERENCE.ID
)

END


问:
Unable to enable TLS on ambassador
Trying to enable TLS port on ambassador using helm chart's service.annotations option. However it is either turning into incorrect config (where tls context is attached to cleartext port) or trying to bind 80 and 443 ports.

I've ambassador as a sub chart to my main chart. And I've defined values for this subchart as follows -

```<code>ambassador:
  replicaCount: 1
  service:
    annotations: {"getambassador.io/config": "---\napiVersion: ambassador/v1\nkind: Module\nname: tls\nconfig:\n  server:\n    enabled: true\n    secret: ambassador-certs\n    redirect_cleartext_from: 8080\n"}
</code>```

This results in binding the listener to port 443 always ignoring the actual tls target port (8443).

requirements.yaml look like this

```<code>dependencies:
- name: ambassador
  version: 2.0.*
  repository: "@stable"
</code>```

Checking the logs reveal that the listener is being created on port 443 and fails as it is not being run as root. If I keep both ambassador and tls modules, then the tls context is always attached to port 8080 and making it a tls port. /ambassador/envoy/envoy.json has always one listener (8080). The chart being is used is ambassador-2.0.2. Any idea why this behavior?

答: This issue addressed as part of the helm chart 2.5.x. Upgrading the dependencies to 2.5.* resolved this issue.</p>

Title: Unable to enable TLS on ambassador

Body:
Trying to enable TLS port on ambassador using helm chart's service.annotations option. However it is either turning into incorrect config (where tls context is attached to cleartext port) or trying to bind 80 and 443 ports.

I've ambassador as a sub chart to my main chart. And I've defined values for this subchart as follows -

ambassador:
  replicaCount: 1
  service:
    annotations: {"getambassador.io/config": "---\napiVersion: ambassador/v1\nkind: Module\nname: tls\nconfig:\n  server:\n    enabled: true\n    secret: ambassador-certs\n    redirect_cleartext_from: 8080\n"}

This results in binding the listener to port 443 always ignoring the actual tls target port (8443).

requirements.yaml look like this

dependencies:
- name: ambassador
  version: 2.0.*
  repository: "@stable"

Checking the logs reveal that the listener is being created on port 443 and fails as it is not being run as root. If I keep both ambassador and tls modules, then the tls context is always attached to port 8080 and making it a tls port. /ambassador/envoy/envoy.json has always one listener (8080). The chart being is used is ambassador-2.0.2. Any idea why this behavior?


问:
Image Resize with constraint proportion and tranparancy
How do i resize image preserving its dimension ratio proportion and transparancy in php</p>

答: The function you want is called imagecopyresampled(); don't forget to only use true color images for destinations.  Here is a comment which talks specifically about preserving transparency: http://www.php.net/manual/en/function.imagecopyresampled.php#93166 (note the usage of the imagecolorallocatealpha() function)


问:
Rails mysql2, undefined method 'accept' for nil:NilClass on rake db:migrate
So I'm working in a Rails application that has the following in the Gemfile:

gem 'mysql2', '< 0.4'

I proceeded with the following:

bundle install

rake db:create

From here I get

An error occurred while installing mysql2 (0.3.21), and Bundler cannot
  continue.

So I update it to

gem 'mysql2', '~> 0.4.10'

Run bundle install and rake db:create.

So I end up with

LoadError: Please install the mysql2 adapter: gem install
  activerecord-mysql2-adapter (can't activate mysql2 (~> 0.3.10),
  already activated mysql2-0.4.10. Make sure all dependencies are added
  to Gemfile.)

Gem::LoadError: can't activate mysql2 (~> 0.3.10), already activated
  mysql2-0.4.10. Make sure all dependencies are added to Gemfile.

From here if I try rails console I end up with:

block (2 levels) in replace_gem': Please install the mysql2 adapter:
  gem install activerecord-mysql2-adapter` (can't activate mysql2 (~>
  0.3.10), already activated mysql2-0.4.10. Make sure all dependencies are added to Gemfile.) (LoadError)

So I update my gemfile to have:

gem 'mysql2', '~> 0.4.10'
  gem 'activerecord-mysql2-adapter'

Rails console works but rake db:migrate results in

rake aborted! NoMethodError: undefined method `accept' for
  nil:NilClass

And everything I've found for solutions was to remove activerecord-mysql2-adapter...and that doesn't work.

For reference I'm using: ruby 2.3.5, rails 3.2.22.5

答:
If you're using an obsolete version of Rails (and 3.2 is extremely out of date) you'll need to use a compatible version of mysql2. If that's 0.3.21 then:

```<code>gem 'mysql2', '~> 0.3.21'
</code>```

Nothing else will work.

Body:
If you're using an obsolete version of Rails (and 3.2 is extremely out of date) you'll need to use a compatible version of mysql2. If that's 0.3.21 then:

gem 'mysql2', '~> 0.3.21'

Nothing else will work.


问:
Find next element by class after an specific element in the entire code (jQuery)
I need to do a jQuery script to mirror what I type in an <input> of class="a" to the next forward <input> of class="b", for every key pressed in the keyboard.

But I have some restrictions:

No, unfortunately I can't change the HTML. It is a legacy code. The only thing I can do is add a jQuery script.

No, it can't be a pure JavaScript code. It must be a jQuery code.

Yes, I need to use .on() because the div that contains the inputs are created dynamically.

I have tried using .next(), .find(), .each(), .closest()... but I'm a beginner, so I don't know how to use them properly. Probably it is something using these functions.

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

```

```$(document).on('keyup', '.a', function (ev) {
    //1 - get value in input and store in a variable
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
});
```

IMPORTANT: Please note that the code isn't exactly like this. Between one input and the other, there is some code, and they aren't event in the same parent div. The only thing I cant assure is that the next input is after, in the code, ant that it'll be inside a div.

答:
Seeing how jQuery is pure JavaScript, one might argue that this is also "jQuery code" :D

on an input event, get the cousin input by getting the parent element's sibling (aunt element)

if the aunt isn't a
 keep searching, until finding the next

search under aunt for the desired input/class combo (i.e. input.b)

set value of that cousin element to the value of the input.a that is being typed in

document.addEventListener('input', event => {
  if (event.target.classList.contains('a')) {
    let aunt=event.target.parentElement.nextElementSibling
    while(aunt && aunt.nodeName!='DIV'){
      aunt=aunt.nextElementSibling;
    }
    const cousin = aunt.querySelector('input.b');
    cousin.value = event.target.value;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- any code -->
<div>
  <input type="text" class="a" />
</div>
```
  code
```
<div>
  <input type="text" class="b" />
</div>
```
  code
```
<div>
  <input type="text" class="a" />
</div>
<!-- any code -->
<div>
  <input type="text" class="b" />
</div>
<!-- any code -->
<div>
  <input type="text" class="a" />
</div>
```
  code
```
<div>
  <input type="text" class="b" />
</div></code>```

Body:
I need to do a jQuery script to mirror what I type in an <input> of class="a" to the next forward <input> of class="b", for every key pressed in the keyboard.

But I have some restrictions:

No, unfortunately I can't change the HTML. It is a legacy code. The only thing I can do is add a jQuery script.

No, it can't be a pure JavaScript code. It must be a jQuery code.

Yes, I need to use .on() because the div that contains the inputs are created dynamically.

I have tried using .next(), .find(), .each(), .closest()... but I'm a beginner, so I don't know how to use them properly. Probably it is something using these functions.

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

$(document).on('keyup', '.a', function (ev) {
    //1 - get value in input and store in a variable
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
});

IMPORTANT: Please note that the code isn't exactly like this. Between one input and the other, there is some code, and they aren't event in the same parent div. The only thing I cant assure is that the next input is after, in the code, ant that it'll be inside a div.

Body:
Seeing how jQuery is pure JavaScript, one might argue that this is also "jQuery code" :D

on an input event, get the cousin input by getting the parent element's sibling (aunt element)

if the aunt isn't a <div> keep searching, until finding the next <div>

search under aunt for the desired input/class combo (i.e. input.b)

set value of that cousin element to the value of the input.a that is being typed in

document.addEventListener('input', event => {
  if (event.target.classList.contains('a')) {
    let aunt=event.target.parentElement.nextElementSibling
    while(aunt && aunt.nodeName!='DIV'){
      aunt=aunt.nextElementSibling;
    }
    const cousin = aunt.querySelector('input.b');
    cousin.value = event.target.value;
  }
});

<!-- any code -->
<div>
  <input type="text" class="a" />
</div>
<pre>
  code
</pre>
<div>
  <input type="text" class="b" />
</div>
<pre>
  code
</pre>
<div>
  <input type="text" class="a" />
</div>
<!-- any code -->
<div>
  <input type="text" class="b" />
</div>
<!-- any code -->
<div>
  <input type="text" class="a" />
</div>
<pre>
  code
</pre>
<div>
  <input type="text" class="b" />
</div>


问:
Listen for 3 finger gestures?
I am making a java application for my computer science teacher that allows him to give students test digitally by loading a number of PDFs from a Google Drive folder and displaying them onto a JScrollPane using Java Swing. The goal of this application is to make the test inescapable so that students can't cheat by going to google to find answers. Then, at the end of class, my teacher will tell the students a code that will allow them to exit the application by entering it into a JTextField. Currently, the JFrame of this application is set with the following settings:

```<code>Frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
</code>```

This means that, for the most part, the application is inescapable, leaving the user stuck on the JFrame until they enter the code to exit. The problem I am facing is that there are certain ways to exit the app or minimize it through gestures built into the computer. Specifically, the one I am looking at involves swiping down with 3 fingers on the trackpad, which minimizes the application, allowing the user to open Google. To my knowledge, there is no way to temporarily disable the gestures built into the computer, so the next best option that I can see is listen for the user to put 3 fingers onto the trackpad and then deny the user the ability to scroll. Is there a way to do this ?
    Additionally, if there are other ways that you can think of to exit this app without the exit code, what are those ways ? And how would I stop the user from taking advantage of them ?

```<code>Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setUndecorated(true);
Frame.setVisible(true);
Frame.setAlwaysOnTop(true);
Frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
</code>```

Additionally, if there are other ways that you can think of to exit this app without the exit code, what are those ways ? And how would I stop the user from taking advantage of them ?

答:
You can try using a WindowAdapter to block Minimization of your JFrame. The WindowAdapter should just overwrite the default Action of your JFrame, when Minimize is pressed (or Gesture is recorded).

```<code>private WindowAdapter getWindowAdapter(JFrame frm) {
return new WindowAdapter() {
  @Override
  public void windowIconified(WindowEvent we) {
    frm.setState(JFrame.NORMAL);
  }
};
</code>```

And add the WindowListener to your JFrame:

```<code>frm.addWindowListener(getWindowAdapter(frm));
</code>```

Title: Listen for 3 finger gestures?

Body:
I am making a java application for my computer science teacher that allows him to give students test digitally by loading a number of PDFs from a Google Drive folder and displaying them onto a JScrollPane using Java Swing. The goal of this application is to make the test inescapable so that students can't cheat by going to google to find answers. Then, at the end of class, my teacher will tell the students a code that will allow them to exit the application by entering it into a JTextField. Currently, the JFrame of this application is set with the following settings:

Frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

This means that, for the most part, the application is inescapable, leaving the user stuck on the JFrame until they enter the code to exit. The problem I am facing is that there are certain ways to exit the app or minimize it through gestures built into the computer. Specifically, the one I am looking at involves swiping down with 3 fingers on the trackpad, which minimizes the application, allowing the user to open Google. To my knowledge, there is no way to temporarily disable the gestures built into the computer, so the next best option that I can see is listen for the user to put 3 fingers onto the trackpad and then deny the user the ability to scroll. Is there a way to do this ?
    Additionally, if there are other ways that you can think of to exit this app without the exit code, what are those ways ? And how would I stop the user from taking advantage of them ?

Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setUndecorated(true);
Frame.setVisible(true);
Frame.setAlwaysOnTop(true);
Frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Additionally, if there are other ways that you can think of to exit this app without the exit code, what are those ways ? And how would I stop the user from taking advantage of them ?

Body:
You can try using a WindowAdapter to block Minimization of your JFrame. The WindowAdapter should just overwrite the default Action of your JFrame, when Minimize is pressed (or Gesture is recorded).

private WindowAdapter getWindowAdapter(JFrame frm) {
return new WindowAdapter() {
  @Override
  public void windowIconified(WindowEvent we) {
    frm.setState(JFrame.NORMAL);
  }
};

And add the WindowListener to your JFrame:

frm.addWindowListener(getWindowAdapter(frm));


问:
How to measure wallclock time in C++ instead of cpu time?
I would like to measure wallclock time taken by my algorithm in C++. Many articles point to this code.

```<code>clock_t begin_time, end_time;
begin_time = clock();
Algorithm();
end_time = clock();
cout << ((double)(end_time - begin_time)/CLOCKS_PER_SEC) << endl;
</code>```

But this measures only cpu time taken by my algorithm.
Some other article pointed out this code.

```<code>double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double begin_time, end_time;
begin_time = getUnixTime();
Algorithm();
end_time = getUnixTime();
cout << (double) (end_time - begin_time) << endl;

</code>```

I thought it would print wallclock time taken by my algorithm. But surprisingly, the time printed by this code is much lower than cpu time printed by previous code. So, I am confused. Please provide code for printing wallclock time.

答:
Those times are probably down in the noise. To get a reasonable time measurement, try executing your algorithm many times in a loop:</p>

```<code>const int loops = 1000000;
double begin_time, end_time;
begin_time = getUnixTime();

for (int i = 0; i < loops; ++i)
    Algorithm();

end_time = getUnixTime();
cout << (double) (end_time - begin_time) / loops << endl;
</code>```

Body:
I would like to measure wallclock time taken by my algorithm in C++. Many articles point to this code.

clock_t begin_time, end_time;
begin_time = clock();
Algorithm();
end_time = clock();
cout << ((double)(end_time - begin_time)/CLOCKS_PER_SEC) << endl;

But this measures only cpu time taken by my algorithm.
Some other article pointed out this code.

double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double begin_time, end_time;
begin_time = getUnixTime();
Algorithm();
end_time = getUnixTime();
cout << (double) (end_time - begin_time) << endl;

I thought it would print wallclock time taken by my algorithm. But surprisingly, the time printed by this code is much lower than cpu time printed by previous code. So, I am confused. Please provide code for printing wallclock time.

Body:
Those times are probably down in the noise. To get a reasonable time measurement, try executing your algorithm many times in a loop:

const int loops = 1000000;
double begin_time, end_time;
begin_time = getUnixTime();

for (int i = 0; i < loops; ++i)
    Algorithm();

end_time = getUnixTime();
cout << (double) (end_time - begin_time) / loops << endl;


问:
Alfresco - /alfresco and /share difference
So i have installed Alfresco and have two web applications /alfresco and /share. Whats the difference and purposes of these applications? Can one application exist without the other?</p>

答:
/alfresco

This context points you to the Repository application. It's the "core" app, where the content is effectively stored and where all the magic happens. Back in the old times, it was the one and only application, so that when Alfresco introduced Share, it was the only place where to find a UI for some features. Now, Share is missing just a couple things.

Currently, the idea is that this JSF application should be a kind of Admin only interface, only to be accessed whenever Share is missing something. However, if you really love JSF (really?) you can still opt to use this interface to build your Alfresco implementation.

This application is mainly interesting for its features rather than for its UI: all the connections to external systems, like DB, CIFS or IMAP for example, happen from here.

On a side note, the "original" implementation of Alfresco WCM is built around this application. Anyway, because of several reasons this implementation of WCM is being phased out, with a new implementation built around Share and its concepts (e.g. Sites) that will grow quite a lot soon.

Don't expect new fancy development on this UI.

/share

This is usually intended the main UI for end users. No JSF here (thanks, God!), it's a Spring Surf frontend to Alfresco that focuses on providing a Collaborative environment. Here you will find the concepts of Sites, project/topic focussed containers for content, blogs and wikis.

As all the content is stored via the other application, Share is almost stateless: no DB connection is opened from here, everything is pulled and pushed to /alfresco via Alfresco REST API and CMIS.

As already mentioned, the new WCM is leveraged from here, as well as all the common ECM features of Alfresco such as workflows, versioning, document transformations, ACLs and so on. Plus, document previews and thumbnails, Blogs, Wikis, Data Lists, ...

This is most likely the UI Alfresco will continue to improve, adding all the whistles and bells they can come up with.


问:
Could not create an API using Azure Function App
I'm trying to create an API using an existing Azure Function App.

Function App Properties:

OS: Linux

Hosting Plan: Consumption Plan

Runtime Stack: Python

Here is the error:

答: Linux Function App import is not yet supported, but coming real soon.</p>


问:
SQL Server stored procedure for updating a table in SQL Server 2012 with incorrect syntax error
I have the below stored procedure, and I am getting this error message:

Incorrect syntax near '01'

I have other stored procedures which begin with '01,' and they work ok. I'm not sure where the incorrect syntax is.

Thanks for any leads.

Here is my table structure:

```<code>CREATE TABLE [dbo].[01_news_test]
(
     [interestid] [INT] IDENTITY(1, 1) NOT FOR REPLICATION NOT NULL,
     [username]   [VARCHAR](50) NULL,
     [approval]   [BIT] NULL,

     CONSTRAINT [PK_news_test]
         PRIMARY KEY CLUSTERED ([interestid] DESC)
                     WITH (pad_index = OFF, statistics_norecompute = OFF,
                           ignore_dup_key = OFF, allow_row_locks = on,
                           allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
</code>```

Here is the code for the stored procedure (below):

```<code>ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS
    DECLARE @sql NVARCHAR(4000)

    SELECT @sql = ' UPDATE [01_news_test] ' +
              ' SET ' +
              ' Approval = @Approval ' +
              ' WHERE '

    IF @InterestID IS NOT NULL
        SELECT @sql = @sql + ' InterestID = @InterestID'

    SELECT @sql = @sql + '; '

    EXEC sp_executesql @sql, N'@InterestID INT, @Approval BIT', InterestID, Approval
</code>```

And, here is the code upon execution of the stored procedure in SQL Server Management Studio:

```<code>DECLARE @return_value INT

EXEC    @return_value = [dbo].[01_cms_news_mgr_bull_appr_update]
               @InterestID = 1,
               @Approval = 0

SELECT  'Return Value' = @return_value
GO
</code>```

Finally, the resulting error msg:

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near '01'

Update: adding a bracket around the table name fixed the 'incorrect syntax error,' although I now am getting an error

Error converting data type nvarchar to int

答:
As commented, avoid any dynamic build of query since no structural component such as tables or columns needs to be dynamically modified. Parameters can be used directly in declared SQL statements.</p>

```<code>ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS

BEGIN
    UPDATE [01_news_test]
    SET Approval = @Approval
    WHERE InterestID = @InterestID
END
</code>```

Body:
I have the below stored procedure, and I am getting this error message:

Incorrect syntax near '01'

I have other stored procedures which begin with '01,' and they work ok. I'm not sure where the incorrect syntax is.

Thanks for any leads.

Here is my table structure:

CREATE TABLE [dbo].[01_news_test]
(
     [interestid] [INT] IDENTITY(1, 1) NOT FOR REPLICATION NOT NULL,
     [username]   [VARCHAR](50) NULL,
     [approval]   [BIT] NULL,

     CONSTRAINT [PK_news_test]
         PRIMARY KEY CLUSTERED ([interestid] DESC)
                     WITH (pad_index = OFF, statistics_norecompute = OFF,
                           ignore_dup_key = OFF, allow_row_locks = on,
                           allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

Here is the code for the stored procedure (below):

ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS
    DECLARE @sql NVARCHAR(4000)

    SELECT @sql = ' UPDATE [01_news_test] ' +
              ' SET ' +
              ' Approval = @Approval ' +
              ' WHERE '

    IF @InterestID IS NOT NULL
        SELECT @sql = @sql + ' InterestID = @InterestID'

    SELECT @sql = @sql + '; '

    EXEC sp_executesql @sql, N'@InterestID INT, @Approval BIT', InterestID, Approval

And, here is the code upon execution of the stored procedure in SQL Server Management Studio:

DECLARE @return_value INT

EXEC    @return_value = [dbo].[01_cms_news_mgr_bull_appr_update]
               @InterestID = 1,
               @Approval = 0

SELECT  'Return Value' = @return_value
GO

Finally, the resulting error msg:

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near '01'

Update: adding a bracket around the table name fixed the 'incorrect syntax error,' although I now am getting an error

Error converting data type nvarchar to int

Body:
As commented, avoid any dynamic build of query since no structural component such as tables or columns needs to be dynamically modified. Parameters can be used directly in declared SQL statements.

ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS

BEGIN
    UPDATE [01_news_test]
    SET Approval = @Approval
    WHERE InterestID = @InterestID
END


问:
Querying Perl Output
I need to query on the 2nd line which I am seeing in the output. I need to check if the command returns on "Listener LISTENER is running on" and provide the desired output. My code is able to read the first line and not the second line which I need to verify. Please advise.

Added a While statement so it can read the 2nd line, did not work.

```<code>use strict;
use warnings;
my $cmd="srvctl status listener";
my $listenerstatus0;
my $msg0;
my $msg1;
open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$listenerstatus0 = <Row1Stat>;
close(Row1Stat);
if( $listenerstatus0 =~ m/Listener LISTENER is running/)
{
$msg0="LISTENER is running";
$msg1=1
}
elsif ($listenerstatus0 =~ m/Listener LISTENER is not running/) {
$msg0 = "LISTENER is not running";
$msg1 = 0;
}
else {
$msg0 = "Unable to Query LISTENER Status";
$msg1 = 0;
}

print "\nStatistic.Name1:$msg1";
print "\nMessage.Name1:$msg0";
</code>```

Below is the Output of the command, I need to check the 2nd line.

```<code>srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ
</code>```

The script needs to check "Listener LISTENER is running " and exit out with the exit code as defined in the script.

答:
If you want to read two lines you shouldn't stop reading after the first:</p>

```<code>open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$ignorethis= <Row1Stat>;       # Read 1st line
$listenerstatus0 = <Row1Stat>; # Read 2nd line
close(Row1Stat);
</code>```

Title: Querying Perl Output

Body:
I need to query on the 2nd line which I am seeing in the output. I need to check if the command returns on "Listener LISTENER is running on" and provide the desired output. My code is able to read the first line and not the second line which I need to verify. Please advise.

Added a While statement so it can read the 2nd line, did not work.

use strict;
use warnings;
my $cmd="srvctl status listener";
my $listenerstatus0;
my $msg0;
my $msg1;
open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$listenerstatus0 = <Row1Stat>;
close(Row1Stat);
if( $listenerstatus0 =~ m/Listener LISTENER is running/)
{
$msg0="LISTENER is running";
$msg1=1
}
elsif ($listenerstatus0 =~ m/Listener LISTENER is not running/) {
$msg0 = "LISTENER is not running";
$msg1 = 0;
}
else {
$msg0 = "Unable to Query LISTENER Status";
$msg1 = 0;
}

print "\nStatistic.Name1:$msg1";
print "\nMessage.Name1:$msg0";

Below is the Output of the command, I need to check the 2nd line.

srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): XYZ

The script needs to check "Listener LISTENER is running " and exit out with the exit code as defined in the script.

Body:
If you want to read two lines you shouldn't stop reading after the first:

open(Row1Stat,"$cmd |") || die ("Could not read the pipe\n");
$ignorethis= <Row1Stat>;       # Read 1st line
$listenerstatus0 = <Row1Stat>; # Read 2nd line
close(Row1Stat);


问:
Changing current user timezone based on server UTC offset and user UTC offset
im writing a twitter web service in php. When a user signs in, i receive this node:

```<code><utc_offset>-18000</utc_offset>
</code>```

I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.

So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset

BTW, this is how i'm getting the server UTC offset value:

```<code>$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
</code>```

Any ideas? Thanks!

答:
To get current server time

```<code>date_default_timezone_set(date_default_timezone_get());
echo date('Y-m-d H:i:s', time());
</code>```

Output for Europe/Paris (my server settings; UTC+2)

```<code>2011-04-12 20:39:43
</code>```

To get user's time by offset

```<code>$user_offset = '-18000';
date_default_timezone_set('UTC');
$diff = "$user_offset seconds";
if ((substr($diff,0,1) != '+') && (substr($diff,0,1) != '-')) $diff = '+' . $diff;
$usertime = strtotime($diff, time());
echo date('Y-m-d H:i:s', $usertime);
</code>```

Output UTC-5 (Ecuador -> Quito time NO DST), php timezone identifier 'America/Guayaquil'.

```<code>2011-04-12 13:39:43
</code>```

PHP.net manual:

Timezone offset in seconds. The offset
  for timezones west of UTC is always
  negative, and for those east of UTC is
  always positive. (-43200 through
  50400)

Body:
im writing a twitter web service in php. When a user signs in, i receive this node:

<utc_offset>-18000</utc_offset>

I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.

So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset

BTW, this is how i'm getting the server UTC offset value:

$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);

Any ideas? Thanks!

Body:
To get current server time

date_default_timezone_set(date_default_timezone_get());
echo date('Y-m-d H:i:s', time());

Output for Europe/Paris (my server settings; UTC+2)

2011-04-12 20:39:43

To get user's time by offset

$user_offset = '-18000';
date_default_timezone_set('UTC');
$diff = "$user_offset seconds";
if ((substr($diff,0,1) != '+') && (substr($diff,0,1) != '-')) $diff = '+' . $diff;
$usertime = strtotime($diff, time());
echo date('Y-m-d H:i:s', $usertime);

Output UTC-5 (Ecuador -> Quito time NO DST), php timezone identifier 'America/Guayaquil'.

2011-04-12 13:39:43

PHP.net manual:

Timezone offset in seconds. The offset
  for timezones west of UTC is always
  negative, and for those east of UTC is
  always positive. (-43200 through
  50400)