问:
Maths related task having trouble solving using python
I'm having trouble solving this question, using python.

When the middle digit of a three-digit number N is removed, the two-digit number thus obtained is N divided by 16. Find all such numbers n.

Can anyone answer the question and explain?

EDIT: The number N when divided by 16 has to equal that 2 digit number, but most of your answers don't work.

答:
Well, you can do this, that for every multiple of 16 that has 2 digits, insert every digit from 0 to 9 in between those 2 digits, and append the result in a list, then you can do linear or binary search on that list for further processing, here is the code:

```<code>results = []

i = 1

while len(str(i*16)) == 2:

    multiple = str(i*16)
    first_digit = multiple[0]
    second_digit = multiple[1]

    for digit in range(10):
        results.append(int(first_digit + str(digit) + second_digit))

    i += 1

print("your results are: ", results)
</code>```

The output is this:

```<code>your results are:  [106, 116, 126, 136, 146, 156, 166, 176, 186, 196, 302,
312, 322, 332, 342, 352, 362, 372, 382, 392, 408, 418, 428, 438, 448, 458,
468, 478, 488, 498, 604, 614, 624, 634, 644, 654, 664, 674, 684, 694, 800,
810, 820, 830, 840, 850, 860, 870, 880, 890, 906, 916, 926, 936, 946, 956,
966, 976, 986, 996]
</code>```

In this code, i goes from 1 to 6, and for each value of i the inner loop runs from 0 to 9, thus overall iterations for getting this list of numbers is 60.

Then, depending on whether you choose to do linear search or binary search, you will have to make 60 comparisons atmost or 6 comparisons atmost respectively.

Hope this helps.

Body:
Well, you can do this, that for every multiple of 16 that has 2 digits, insert every digit from 0 to 9 in between those 2 digits, and append the result in a list, then you can do linear or binary search on that list for further processing, here is the code:

results = []

i = 1

while len(str(i*16)) == 2:

    multiple = str(i*16)
    first_digit = multiple[0]
    second_digit = multiple[1]

    for digit in range(10):
        results.append(int(first_digit + str(digit) + second_digit))

    i += 1

print("your results are: ", results)

The output is this:

your results are:  [106, 116, 126, 136, 146, 156, 166, 176, 186, 196, 302,
312, 322, 332, 342, 352, 362, 372, 382, 392, 408, 418, 428, 438, 448, 458,
468, 478, 488, 498, 604, 614, 624, 634, 644, 654, 664, 674, 684, 694, 800,
810, 820, 830, 840, 850, 860, 870, 880, 890, 906, 916, 926, 936, 946, 956,
966, 976, 986, 996]

In this code, i goes from 1 to 6, and for each value of i the inner loop runs from 0 to 9, thus overall iterations for getting this list of numbers is 60.

Then, depending on whether you choose to do linear search or binary search, you will have to make 60 comparisons atmost or 6 comparisons atmost respectively.

Hope this helps.


来源: stackexchange

问:
nginx rewrite rule to generate search engine friendly urls for old xtcommerce 3.04 sp 2.1 shopsystem
i need some help while migrating an old shopsystem from apache to nginx.
Within apache there was no need to do anything. i guess the shopsystem was somehow optimized to handle those URLs. I dont have any mod_rewrite rules doing some magic. However what i need to do is rewriting urls in a certain pattern

desired behaviour:

```<code>Replace 1st / after Filename ending with (.php) with ?
Replace 2nd / with =
Replace 3rd / with &
Replace 4th / with =
[repeat 3/4] as long as there are parameters inside the URL
</code>```

example urls:

```<code>http://www.shop.de/login.php/action/process
should rewrite to => http://www.shop.de/login.php?action=process
</code>```

OR

```<code>http://www.shop.de/product_info.php/info/p283_foo-bar.html/action/add_product

should rewrite to ==> http://www.shop.de/product_info.php?info=p283_foo--bar.html&action=add_product
</code>```

i want to keep the URL as it is, just doing some internal rewrite.

Any kind of help is apprreciated!

答:
http://www.shop.de/login.php/action/process
should rewrite to http://www.shop.de/login.php?action=process

```<code>location / {
  rewrite ^/login.php/action/(.*)$ /login.php?action=$2$query_string;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i need some help while migrating an old shopsystem from apache to nginx.
Within apache there was no need to do anything. i guess the shopsystem was somehow optimized to handle those URLs. I dont have any mod_rewrite rules doing some magic. However what i need to do is rewriting urls in a certain pattern

desired behaviour:

Replace 1st / after Filename ending with (.php) with ?
Replace 2nd / with =
Replace 3rd / with &
Replace 4th / with =
[repeat 3/4] as long as there are parameters inside the URL

example urls:

http://www.shop.de/login.php/action/process
should rewrite to => http://www.shop.de/login.php?action=process

OR

http://www.shop.de/product_info.php/info/p283_foo-bar.html/action/add_product

should rewrite to ==> http://www.shop.de/product_info.php?info=p283_foo--bar.html&action=add_product

i want to keep the URL as it is, just doing some internal rewrite.

Any kind of help is apprreciated!

Body:
http://www.shop.de/login.php/action/process
should rewrite to http://www.shop.de/login.php?action=process

location / {
  rewrite ^/login.php/action/(.*)$ /login.php?action=$2$query_string;
}


问:
Validate checkbox using JavaScript.
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

```<code>        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });
</code>```

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.

答: You can achieve this by getting the number of elements with the class 'checked'. If the number is 6, then you can show the alert.</p>

Title: Validate checkbox using JavaScript.

Body:
I would like some help with checkbox validation.

If you look in below picture, when user click the image, the checkbox becomes selected.

What I would want is if all checkbox are selected alert an simple message.

This is a code to select checkbox by clicking on an image.

        $( document ).ready(function() {

    $("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
         var $$ = $(this)

          if( !$$.is('.checked')){
              $$.addClass('checked');

              $('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);

                }
            });
    });

So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.

Thank you in advance.


问:
Stubbing Methods does not work with OCMock3.4
Stubbing Methods works nicely With 'NSUserDefaults',but it just doesn't seem to work with My Custom Method.

My test code is as follows:

```<code>- (void)testExample
{
    id userDefaultMock = OCMClassMock([NSUserDefaults class]);
    OCMStub([userDefaultMock standardUserDefaults]).andReturn(userDefaultMock);
    OCMStub([userDefaultMock objectForKey:[OCMArg any]]).andReturn(@"user defaults mock obj");

    id managerMock = OCMClassMock([ViewManager class]);
    OCMStub([managerMock sharedInstance]).andReturn(managerMock);
    OCMStub([managerMock generateObjWithObj:[OCMArg any]]).andReturn(@(11));

    ViewController *vc = [[ViewController alloc]init];
    [vc publicMethod];

}
</code>```

code in ViewController:

```<code>- (void)publicMethod
{
    [[NSUserDefaults standardUserDefaults]setObject:@"mockObj" forKey:@"mockObjKey"];
    id obj = [[NSUserDefaults standardUserDefaults]objectForKey:@"mockObjKey"];
    NSLog(@"mockObjKey:%@",obj);

    NSNumber *num = @(0);
    NSNumber *i = [[ViewManager sharedInstance] generateIndexWithNumber:num];
    NSLog(@"i expected to be 1, actual :%ld",i.integerValue);
}
</code>```

code in ViewManager:

```<code>static ViewManager *sharedViewManager = nil;

+ (id)sharedInstance
{
    if (nil == sharedViewManager)
    {
        sharedViewManager = [[ViewManager alloc]init];
    }
    return sharedViewManager;
}
- (NSNumber *)generateIndexWithNumber:(NSNumber *)index
{
    NSLog(@"generateIndexWithNumber:%ld",index.integerValue);
    return @(index.integerValue + 1);
}
</code>```

and console output is as follows:

```<code>2017-07-03 10:12:25.812 OC_Unit[2214:64454] mockObjKey:user defaults mock obj
2017-07-03 10:12:25.812 OC_Unit[2214:64454] generateIndexWithNumber:0
2017-07-03 10:12:25.812 OC_Unit[2214:64454] i expected to be 1, actual :1
</code>```

The last line of output should be 'i expected to be 1, actual :11' if shubbing methods works. I'm wondering，why does it not output as expected。

答: It looks like you are stubbing generateObjWithObj: but the code is calling generateIndexWithNumber:.

Body:
Stubbing Methods works nicely With 'NSUserDefaults',but it just doesn't seem to work with My Custom Method.

My test code is as follows:

- (void)testExample
{
    id userDefaultMock = OCMClassMock([NSUserDefaults class]);
    OCMStub([userDefaultMock standardUserDefaults]).andReturn(userDefaultMock);
    OCMStub([userDefaultMock objectForKey:[OCMArg any]]).andReturn(@"user defaults mock obj");

    id managerMock = OCMClassMock([ViewManager class]);
    OCMStub([managerMock sharedInstance]).andReturn(managerMock);
    OCMStub([managerMock generateObjWithObj:[OCMArg any]]).andReturn(@(11));

    ViewController *vc = [[ViewController alloc]init];
    [vc publicMethod];

}

code in ViewController:

- (void)publicMethod
{
    [[NSUserDefaults standardUserDefaults]setObject:@"mockObj" forKey:@"mockObjKey"];
    id obj = [[NSUserDefaults standardUserDefaults]objectForKey:@"mockObjKey"];
    NSLog(@"mockObjKey:%@",obj);

    NSNumber *num = @(0);
    NSNumber *i = [[ViewManager sharedInstance] generateIndexWithNumber:num];
    NSLog(@"i expected to be 1, actual :%ld",i.integerValue);
}

code in ViewManager:

static ViewManager *sharedViewManager = nil;

+ (id)sharedInstance
{
    if (nil == sharedViewManager)
    {
        sharedViewManager = [[ViewManager alloc]init];
    }
    return sharedViewManager;
}
- (NSNumber *)generateIndexWithNumber:(NSNumber *)index
{
    NSLog(@"generateIndexWithNumber:%ld",index.integerValue);
    return @(index.integerValue + 1);
}

and console output is as follows:

2017-07-03 10:12:25.812 OC_Unit[2214:64454] mockObjKey:user defaults mock obj
2017-07-03 10:12:25.812 OC_Unit[2214:64454] generateIndexWithNumber:0
2017-07-03 10:12:25.812 OC_Unit[2214:64454] i expected to be 1, actual :1

The last line of output should be 'i expected to be 1, actual :11' if shubbing methods works. I'm wondering，why does it not output as expected。


答:
```<code>((N/100)*10+(N%10))/16
</code>```

N/100 gets you the 10^2 digit while N%10 gets you the 10^0 digit. % stands for the modulo operator

```<code>for i in range(100,1000):
    if ((i/100)*10+(i%10))%16==0:
        print i
</code>```

Title: Maths related task having trouble solving using python

Body:
I'm having trouble solving this question, using python.

When the middle digit of a three-digit number N is removed, the two-digit number thus obtained is N divided by 16. Find all such numbers n.

Can anyone answer the question and explain?

EDIT: The number N when divided by 16 has to equal that 2 digit number, but most of your answers don't work.

Body:
((N/100)*10+(N%10))/16

N/100 gets you the 10^2 digit while N%10 gets you the 10^0 digit. % stands for the modulo operator

for i in range(100,1000):
    if ((i/100)*10+(i%10))%16==0:
        print i


问:
compare images using systemC
I wrote in this forum asking for help to solve this problem that took ame a lot of my time,i write my first program using systemC, I will expain my aim as much as I can , I stored 2 matrix of pixel value of image in two different text files, I write a systemC code that load two matrix and apply somme of absolute difference, if number of different superior of a Threshold the code displays message (motion).

My code composed of two modules, the first module check if there a number stored in a text file, if yes this Module will automates the other module to load the two matrix and compare them, I really need this code for my project graduation any help or suggestion.

```<code>#include "systemC.h"
 #include "string.h"
#include "stdio.h"
 #include"stdlib.h"
#include <time.h>
#include <math.h>       /* fabs */
#include <fstream>
 #include <iostream>
  #include <fstream>
 using namespace std;
 #define _CRT_SECURE_NO_WARNINGS
_CRT_SECURE_NO_WARNINGS
double elapsed;

 int H = 0;
 int D = 0;
 int a, b;
 int in = false;
 int L = 0;
 char *mode1 = "r";
 char *mode2 = "w";
  int i, j, k;
 int rows1, cols1, rows2, cols2;
 bool fileFound = false;
 FILE *SwitchContext;
 FILE *image1;
 FILE *image2;
 FILE *image3;
 int sum = 0;
 clock_t start = clock();
  SC_MODULE(synchronization)
 {
sc_in<bool>sig ;
SC_CTOR(synchronization)
{
    SC_METHOD(synchroprocess)

}
void synchroprocess()
{
    cout << "\n Running Automation";
    SwitchContext = fopen("F:/SWITCH CONTEXT.txt", mode2);
    fscanf(SwitchContext, "%d", &L);

    while (L != 0)

    {
        cout << "waiting...";
    }
    sig == true;
}

   };

    SC_MODULE(imageProcess)
    {
        sc_in<bool>sig;
            SC_CTOR(imageProcess)
        {
                SC_METHOD(MotionDetector)
                    sensitive(sig);
        }
        void MotionDetector()
        {

                    image3 = fopen("F:/image3.txt", mode2);
                do
                {
                    char *mode1 = "r";
                    char *mode2 = "w";
                    image1 = fopen("F:/image1.txt", mode1);

                          if (!image1)
                          {
                        printf("File Not Found!!\n");
                        fileFound = true;
                          }
                         else
                        fileFound = false;
                          }
                        while (fileFound);
                          do
                          {
                     image2 = fopen("F:/image2.txt", mode1);
                     if (!image2)
                          {
                        printf("File Not Found!!\n");
                        fileFound = true;
                          }
                         else
                        fileFound = false;
                        }
                        while (fileFound);
                rows1 = rows2 = 384;
                cols1 = cols2 = 512;

                int **mat1 = (int **)malloc(rows1 * sizeof(int*));
                for (i = 0; i < rows1; i++)
                mat1[i] = (int *)malloc(cols1 * sizeof(int));

                i = 0;

                int **mat2 = (int **)malloc(rows2 * sizeof(int*));
                for (i = 0; i < rows2; i++)
                    mat2[i] = (int *)malloc(cols2 * sizeof(int));

                            i = 0;

                while (!feof(image1))
                {
                    for (i = 0; i < rows1; i++)
                    {
                        for (j = 0; j < cols1; j++)
                            fscanf(image1, "%d%", &mat1[i][j]);
                    }
                }

                i = 0;
                j = 0;

                while (!feof(image2))
                {
                    for (i = 0; i < rows2; i++)
                    {
                        for (j = 0; j < cols2; j++)
                            fscanf(image2, "%d%", &mat2[i][j]);
                    }
                }

                i = 0;
                j = 0;

                    printf("\n\n");
                    for (i = 0; i < rows1; i++)
                {
                    for (j = 0; j < cols1; j++) {
                        a = abs(mat1[i][j] = mat2[i][j]);
                            b = b + a;
                }
                }

                i = j = 0;
                D = b / 196608;

                if (D > 0.9)
                {
                    printf("%d,&K");
                    printf("MOTION...DETECTED");
                    getchar();
                    sc_pause;
                    for (i = 0; i < rows1; i++) {
                        for (j = 0; j < cols1; j++)
                        {
                            fprintf(image3, "%d ", mat2[i][j]);
                        }

                        fprintf(image3, "\n");
                    }
                    printf("\n Image Saved....");
                    std::ofstream mon_fichier("F:\toto.txt");
                    mon_fichier << elapsed << '\n';
                    }

                    fclose(image1);
                    fclose(image2);
                    fclose(image3);
                    clock_t end = clock();
                    elapsed = ((double)end - start) / CLOCKS_PER_SEC;
                    printf("time is %f", elapsed);

                    }
                 };

    int sc_main(int argc, char* argv[])
    {
            imageProcess master("EE2");
            master.MotionDetector();

        sc_start();
        return(0);
    }
</code>```

答:
What you did is basically wrong.

You copy pasted code to SC_MODULE, this code is simple C code

(Do not mix C and C++ files)

This is not how you use clock

What you should do:

You need to check if your algorithm works, for this you do not need SystemC at all

Then you can replace data types with HW one and check if it still works

Then you have to find which data interface is used in HW and how to use this interface

Then you have to tweak your alg. to work with this interface (There you can use SC_MODULE, sc ports etc...)

Also take look at SC_CTHREAD, you will need it.

Without any informations about target platform I can not provide any other help.

Title: compare images using systemC

Body:
I wrote in this forum asking for help to solve this problem that took ame a lot of my time,i write my first program using systemC, I will expain my aim as much as I can , I stored 2 matrix of pixel value of image in two different text files, I write a systemC code that load two matrix and apply somme of absolute difference, if number of different superior of a Threshold the code displays message (motion).

My code composed of two modules, the first module check if there a number stored in a text file, if yes this Module will automates the other module to load the two matrix and compare them, I really need this code for my project graduation any help or suggestion.

#include "systemC.h"
 #include "string.h"
#include "stdio.h"
 #include"stdlib.h"
#include <time.h>
#include <math.h>       /* fabs */
#include <fstream>
 #include <iostream>
  #include <fstream>
 using namespace std;
 #define _CRT_SECURE_NO_WARNINGS
_CRT_SECURE_NO_WARNINGS
double elapsed;

 int H = 0;
 int D = 0;
 int a, b;
 int in = false;
 int L = 0;
 char *mode1 = "r";
 char *mode2 = "w";
  int i, j, k;
 int rows1, cols1, rows2, cols2;
 bool fileFound = false;
 FILE *SwitchContext;
 FILE *image1;
 FILE *image2;
 FILE *image3;
 int sum = 0;
 clock_t start = clock();
  SC_MODULE(synchronization)
 {
sc_in<bool>sig ;
SC_CTOR(synchronization)
{
    SC_METHOD(synchroprocess)

}
void synchroprocess()
{
    cout << "\n Running Automation";
    SwitchContext = fopen("F:/SWITCH CONTEXT.txt", mode2);
    fscanf(SwitchContext, "%d", &L);

    while (L != 0)

    {
        cout << "waiting...";
    }
    sig == true;
}

   };

    SC_MODULE(imageProcess)
    {
        sc_in<bool>sig;
            SC_CTOR(imageProcess)
        {
                SC_METHOD(MotionDetector)
                    sensitive(sig);
        }
        void MotionDetector()
        {

                    image3 = fopen("F:/image3.txt", mode2);
                do
                {
                    char *mode1 = "r";
                    char *mode2 = "w";
                    image1 = fopen("F:/image1.txt", mode1);

                          if (!image1)
                          {
                        printf("File Not Found!!\n");
                        fileFound = true;
                          }
                         else
                        fileFound = false;
                          }
                        while (fileFound);
                          do
                          {
                     image2 = fopen("F:/image2.txt", mode1);
                     if (!image2)
                          {
                        printf("File Not Found!!\n");
                        fileFound = true;
                          }
                         else
                        fileFound = false;
                        }
                        while (fileFound);
                rows1 = rows2 = 384;
                cols1 = cols2 = 512;

                int **mat1 = (int **)malloc(rows1 * sizeof(int*));
                for (i = 0; i < rows1; i++)
                mat1[i] = (int *)malloc(cols1 * sizeof(int));

                i = 0;

                int **mat2 = (int **)malloc(rows2 * sizeof(int*));
                for (i = 0; i < rows2; i++)
                    mat2[i] = (int *)malloc(cols2 * sizeof(int));

                            i = 0;

                while (!feof(image1))
                {
                    for (i = 0; i < rows1; i++)
                    {
                        for (j = 0; j < cols1; j++)
                            fscanf(image1, "%d%", &mat1[i][j]);
                    }
                }

                i = 0;
                j = 0;

                while (!feof(image2))
                {
                    for (i = 0; i < rows2; i++)
                    {
                        for (j = 0; j < cols2; j++)
                            fscanf(image2, "%d%", &mat2[i][j]);
                    }
                }

                i = 0;
                j = 0;

                    printf("\n\n");
                    for (i = 0; i < rows1; i++)
                {
                    for (j = 0; j < cols1; j++) {
                        a = abs(mat1[i][j] = mat2[i][j]);
                            b = b + a;
                }
                }

                i = j = 0;
                D = b / 196608;

                if (D > 0.9)
                {
                    printf("%d,&K");
                    printf("MOTION...DETECTED");
                    getchar();
                    sc_pause;
                    for (i = 0; i < rows1; i++) {
                        for (j = 0; j < cols1; j++)
                        {
                            fprintf(image3, "%d ", mat2[i][j]);
                        }

                        fprintf(image3, "\n");
                    }
                    printf("\n Image Saved....");
                    std::ofstream mon_fichier("F:\toto.txt");
                    mon_fichier << elapsed << '\n';
                    }

                    fclose(image1);
                    fclose(image2);
                    fclose(image3);
                    clock_t end = clock();
                    elapsed = ((double)end - start) / CLOCKS_PER_SEC;
                    printf("time is %f", elapsed);

                    }
                 };

    int sc_main(int argc, char* argv[])
    {
            imageProcess master("EE2");
            master.MotionDetector();

        sc_start();
        return(0);
    }


问:
Add circle to map with carto.js and leaflet libraries
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

```<code>layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);
</code>```

Error and log are the same...

EDIT 2

With this code

```<code>var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);
</code>```

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

答:
According to the Carto Docs, the latlon argument in your featureClick callback contains:

Array with the LatLng ([lat,lng]) where the layer was clicked.

Is that where you want the circle to be placed?  If so, use this line:

```<code>L.circle(latlon, {radius: data.distance}).addTo(map);
</code>```

Body:
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);

Error and log are the same...

EDIT 2

With this code

var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

Body:
According to the Carto Docs, the latlon argument in your featureClick callback contains:

Array with the LatLng ([lat,lng]) where the layer was clicked.

Is that where you want the circle to be placed?  If so, use this line:

L.circle(latlon, {radius: data.distance}).addTo(map);


问:
String not Added to Observable Collection Xamarin Forms
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

```<code>public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }
</code>```

and the function (getMessages) that returns the data from an SQLite database:

```<code>   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }
</code>```

And for completeness the Xaml:

```<code><ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>
</code>```

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?

答:
In your foreach, you create a new instance of the ObservableCollection.

```<code>foreach (var variable in intermediary)
{
    DataBaseList = new ObservableCollection<string> { variable };
}
</code>```

For a ObservableCollection to work correctly, you need to instantiate it once. Just clear the list if you want to add new ones, like this:

```<code>DataBaseList.Clear();

foreach (var variable in intermediary)
{
    DataBaseList.Add(variable);
}
</code>```

Body:
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }

and the function (getMessages) that returns the data from an SQLite database:

   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }

And for completeness the Xaml:

<ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?

Body:
In your foreach, you create a new instance of the ObservableCollection.

foreach (var variable in intermediary)
{
    DataBaseList = new ObservableCollection<string> { variable };
}

For a ObservableCollection to work correctly, you need to instantiate it once. Just clear the list if you want to add new ones, like this:

DataBaseList.Clear();

foreach (var variable in intermediary)
{
    DataBaseList.Add(variable);
}


问:
Send the SIGHUP signal to a process in Perl
I have a UNIX daemon, which wait of SIGHUP for refresh a data. I try to send a signal from the Perl script (under Apache www-data:www-data on the same server) by Proc::Killall ("killall('HUP', 'mydaemon');"), but I have no properly permissions. suid bit doesn't work too. 'kill -n HUP ' from shell are working.

Does you have any idea to do this?

答:
The usual work-around is to employ a »touch file« to indicate a reload, see Apache2::Reload for a real life example.

Listen to notifications set up with e.g. File::ChangeNotify or AnyEvent::Inotify::Simple, then do your reloading.

ContentLicense: CC BY-SA 2.5


问:
initAuth butt where can i get SRPA
Hi I'm running aws cli

Here is my code

```<code>aws --region ap-southeast-2 cognito-idp initiate-auth --cli-input-json file://initiate-auth.json
</code>```

and json file

```<code>{    "AuthFlow": "USER_SRP_AUTH",    "AuthParameters": {
  "USERNAME" : "gabrielwu",
  "SRPA": "?????",
  "SECRET_HASH":"yyVMuFNZEehJ6Io9WZWUsngJFBVdsjqwX1zMyRhe+Bg="    },    "ClientId": "31vegbhbi2hesihbc0m4h5r8p1" }
</code>```

well i don't know how i can generate SRPA. I know how to use Python. Is there any Python library can help this ?

答: This may be quite late but refer to this stackoverflow post. It contains the link to such a library and some very good pointers about how the SRP and ChallengeResponse works.</p>

Title: initAuth butt where can i get SRPA

Body:
Hi I'm running aws cli

Here is my code

aws --region ap-southeast-2 cognito-idp initiate-auth --cli-input-json file://initiate-auth.json

and json file

{    "AuthFlow": "USER_SRP_AUTH",    "AuthParameters": {
  "USERNAME" : "gabrielwu",
  "SRPA": "?????",
  "SECRET_HASH":"yyVMuFNZEehJ6Io9WZWUsngJFBVdsjqwX1zMyRhe+Bg="    },    "ClientId": "31vegbhbi2hesihbc0m4h5r8p1" }

well i don't know how i can generate SRPA. I know how to use Python. Is there any Python library can help this ?


问:
RabbitMQ flooded by new connections
i'm using java api client with Automatic Recovery but every time it loses the connection, when it reconnects it creates a new connection on a different port, flooding my RabbitMQ with multiple connections.The environment I am working on loses the connection frequently.

Is it possibile use the same connection when it tries to reconnect?

Thanks in advance

答:
You can also delete idle connection via the help of heartbeat

Enable it in your java client

```<code>ConnectionFactory cf = new ConnectionFactory();
cf.setRequestedHeartbeat(60);
</code>```

It can also be hardcoded in server's config

Or you may refer refer Connection AutoRecovering

Title: RabbitMQ flooded by new connections

Body:
You can also delete idle connection via the help of heartbeat

Enable it in your java client

ConnectionFactory cf = new ConnectionFactory();
cf.setRequestedHeartbeat(60);

It can also be hardcoded in server's config

Or you may refer refer Connection AutoRecovering


问:
Select Input on Label Click
I want to search data
but i have multiple label like firstname,lastname and Username
and only one input
i want to place different placeholder based on the label clicked
how this possible with jquery and javascript

Thanks In Advance

答:
You can use this code

$(document).ready(function(){
  $('.searchLabels').click(function(e){
     $('#searchTxt').prop('placeholder',$(this).text())
 });
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='searchTxt' type="text"  placeholder="" >

 <br/><label class='searchLabels'>firstname</label>
 <br/><label class='searchLabels'>lastname </label>
 <br/><label class='searchLabels'>Username </label></code>```

Title: Select Input on Label Click

Body:
You can use this code

$(document).ready(function(){
  $('.searchLabels').click(function(e){
     $('#searchTxt').prop('placeholder',$(this).text())
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='searchTxt' type="text"  placeholder="" >

 <br/><label class='searchLabels'>firstname</label>
 <br/><label class='searchLabels'>lastname </label>
 <br/><label class='searchLabels'>Username </label>


问:
How to communicate in Angular 4 app with the DOM?
I'm try to invoke addItems method however, I'm an getting error:

Uncaught TypeError: this.addItems is not a function

I'm using Angular 4 with jQuery and fullpage.js library.

page-content.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { MyDataService } from './my-data.service';
import * as $ from 'jquery';
import 'fullpage.js';

@Component({
  selector: 'page-content',
  providers: [MyDataService],
  templateUrl: './page-content.component.html',
  styleUrls: ['./page-content.component.css']
})
export class PageContentComponent implements OnInit {
  single_post = '';
  posts = [];
  constructor(private newService: MyDataService) {
      this.addItems(0, this.no_of_post);
  }
  ngOnInit() {
      $(document).ready(function() {
         if($('html').hasClass('fp-enabled')){
                $.fn.fullpage.destroy('all');
            }
        $('#fullpage').fullpage({
            onLeave: function(index, nextIndex, direction){
              const start = this.no_of_post;
              this.no_of_post += 1;
              this.addItems(start, this.no_of_post);
            }
        });
      });
  }

  addItems(startIndex, endIndex) {
    for (let i = startIndex; i < this.no_of_post; ++i) {
        this.newService.fetchData().subscribe(data=>{
           this.single_post = data[i];
           this.posts.push(this.single_post);
        });
    }
  }
}
</code>```

答:
I'd suggest you to move this call from constructor to ngOnInit()

```<code> constructor(private newService: MyDataService) {
  this.addItems(0, this.no_of_post);
 }
</code>```

And thing is that this points on its class. You don't have property no_of_post in that class.

Also you have issue with this string

onLeave: function(index, nextIndex, direction) {

Use arrow function

onLeave: (index, nextIndex, direction) => {

Body:
I'm try to invoke addItems method however, I'm an getting error:

Uncaught TypeError: this.addItems is not a function

I'm using Angular 4 with jQuery and fullpage.js library.

page-content.component.ts

import { Component, OnInit } from '@angular/core';
import { MyDataService } from './my-data.service';
import * as $ from 'jquery';
import 'fullpage.js';

@Component({
  selector: 'page-content',
  providers: [MyDataService],
  templateUrl: './page-content.component.html',
  styleUrls: ['./page-content.component.css']
})
export class PageContentComponent implements OnInit {
  single_post = '';
  posts = [];
  constructor(private newService: MyDataService) {
      this.addItems(0, this.no_of_post);
  }
  ngOnInit() {
      $(document).ready(function() {
         if($('html').hasClass('fp-enabled')){
                $.fn.fullpage.destroy('all');
            }
        $('#fullpage').fullpage({
            onLeave: function(index, nextIndex, direction){
              const start = this.no_of_post;
              this.no_of_post += 1;
              this.addItems(start, this.no_of_post);
            }
        });
      });
  }

  addItems(startIndex, endIndex) {
    for (let i = startIndex; i < this.no_of_post; ++i) {
        this.newService.fetchData().subscribe(data=>{
           this.single_post = data[i];
           this.posts.push(this.single_post);
        });
    }
  }
}

Body:
I'd suggest you to move this call from constructor to ngOnInit()

 constructor(private newService: MyDataService) {
  this.addItems(0, this.no_of_post);
 }

And thing is that this points on its class. You don't have property no_of_post in that class.

Also you have issue with this string

onLeave: function(index, nextIndex, direction) {

Use arrow function

onLeave: (index, nextIndex, direction) => {


问:
Problem wit MDAC when trying to compile in VS2008 using x64 bit target platform
I am trying to compile an 32 bit application. I am aware of problems with it but that is why its being compiled on 64 bit version.

I am hanging at this problem.
Application uses lots of sql stuff.

In sqltypes.h file: (provided by MDAC)

```<code>#ifdef _WIN64
typedef INT64           SQLLEN;
typedef UINT64        SQLULEN;
typedef UINT64  SQLSETPOSIROW;
#else
  #define SQLLEN          SQLINTEGER
  #define SQLULEN         SQLUINTEGER
  #define SQLSETPOSIROW   SQLUSMALLINT
#endif
//For Backward compatibility
#ifdef WIN32
  typedef SQLULEN           SQLROWCOUNT;
  typedef SQLULEN           SQLROWSETSIZE;
  typedef SQLULEN           SQLTRANSID;
  typedef SQLLEN            SQLROWOFFSET;
#endif
</code>```

For some reason when its compiled on 32 bit platform it works great
But when I try building it on 64 it goes berserk.

Error 61 error C2146: syntax error : missing ';' before identifier 'SQLLEN' ..\external\microsoft sdk\include\sqltypes.h 50

It does not recognize INT64, UINT64.

Is there something I need to enable so it will work under 64 build process?
Missing some #include or #define?

Any help would be great

Thanks

答:
Use

```<code>#include <windows.h>
</code>```

It contains BaseTsd.h and other relevant Windows-specific definitions.

Body:
I am trying to compile an 32 bit application. I am aware of problems with it but that is why its being compiled on 64 bit version.

I am hanging at this problem.
Application uses lots of sql stuff.

In sqltypes.h file: (provided by MDAC)

#ifdef _WIN64
typedef INT64           SQLLEN;
typedef UINT64        SQLULEN;
typedef UINT64  SQLSETPOSIROW;
#else
  #define SQLLEN          SQLINTEGER
  #define SQLULEN         SQLUINTEGER
  #define SQLSETPOSIROW   SQLUSMALLINT
#endif
//For Backward compatibility
#ifdef WIN32
  typedef SQLULEN           SQLROWCOUNT;
  typedef SQLULEN           SQLROWSETSIZE;
  typedef SQLULEN           SQLTRANSID;
  typedef SQLLEN            SQLROWOFFSET;
#endif

For some reason when its compiled on 32 bit platform it works great
But when I try building it on 64 it goes berserk.

Error 61 error C2146: syntax error : missing ';' before identifier 'SQLLEN' ..\external\microsoft sdk\include\sqltypes.h 50

It does not recognize INT64, UINT64.

Is there something I need to enable so it will work under 64 build process?
Missing some #include or #define?

Any help would be great

Thanks

Body:
Use

#include <windows.h>

It contains BaseTsd.h and other relevant Windows-specific definitions.


问:
Looking for fast method to converting boolean[] in Gray code to BigInteger and vice versa in Java
For GA needed two methods:

```<code>BigInteger greyToBigInteger(boolean[]){...}
</code>```

and

```<code>boolean[] bigIntegerToGrey(BigInteger){...}
</code>```

For example:

```<code>15 ---> {true,false,false,false}
and
{true,false,false,false} --> 15
</code>```

I don't know, how to make that very fast. Max number to convert is 10^1125, so it works more than 5 minutes for one number, if I do it, like in Wikipedia example.

答:
I've writen this piece of code, and it run pretty fast without any special tricks - on my laptop machine it takes less than 2 milliseconds to convert the given number that is less than or equal 10^1125 to gray and back:

```<code>import java.math.BigInteger;
import java.util.Random;

public class GrayCode {

    public static void main(String[] args) {

        // actually 10^1125 is a number with max length of 3738 bits
        int bitLength = new BigInteger("10").pow(1125).bitLength();
        System.out.println("10^1125 is a number with max bit length = " + bitLength);
        new GrayCode().test(bitLength);
    }

    private void test(int bitLength) {
        long totalTime = 0;
        long numberOfTests = 1000;

        for (int n = 0; n < numberOfTests; n++) {
            // We don't include time needed for generation of a number
            BigInteger binary = generateBigInteger(bitLength);

            // here we start measuring execution time of single conversion
            long start = System.currentTimeMillis();

            // The conversion to gray and back
            boolean[] gray = bigIntegerToGrey(binary);
            BigInteger back = grayToBigInteger(gray);

            // we sum up the conversion times to totalTime per this test suite
            totalTime += System.currentTimeMillis() - start;
        }
        System.out.println("We have run a "+numberOfTests+" tests, for a random numbers of "+bitLength+" bit length to convert to gray code and back to binary");
        System.out.println("The total execution time of this test was "+totalTime+" milliseconds, giving average convesion time of " + totalTime/1000d + " ms per single test ");

    }

    private BigInteger grayToBigInteger(boolean[] booleanGray) {
        BigInteger input = booleanToBigInteger(booleanGray);
        return grayToBinary(input);
    }

    private boolean[] bigIntegerToGrey(BigInteger binary) {
        BigInteger gray = binaryToGray(binary);
        return bigIntegerToBooleanArray(gray);
    }

    public boolean[] bigIntegerToBooleanArray(BigInteger number) {
        char[] binary = number.toString(2).toCharArray();
        boolean[] binaryBoolean = new boolean[binary.length];
        for (int n = 0; n < binary.length; n++) {
            if (binary[n] == '1') {
                binaryBoolean[n] = true;
            }
        }
        return binaryBoolean;
    }

    private BigInteger generateBigInteger(int numBits) {
        Random rnd = new Random();
        BigInteger number = new BigInteger(numBits, rnd);
        return number;
    }

    public BigInteger booleanToBigInteger(boolean[] binary) {
        StringBuilder sb = new StringBuilder();
        for (boolean b : binary) {
            sb.append(b ? '1' : '0');
        }
        return new BigInteger(sb.toString(), 2);
    }

    public BigInteger binaryToGray(BigInteger num) {
        return num.xor(num.shiftRight(1));
    }

    public BigInteger grayToBinary(BigInteger num) {
        BigInteger mask;
        for (mask = num.shiftRight(1); mask.compareTo(BigInteger.ZERO) != 0; mask = mask.shiftRight(1)) {
            num = num.xor(mask);
        }
        return num;
    }

}
</code>```

the results:

```<code>10^1125 is a number with max bit length = 3738
We have run a 1000 tests, for a number of 3738 bit length to convert to gray code and back to binary
The total execution time of this test was 1828 milliseconds, giving average convesion time of 1.828 ms per single test
</code>```

Body:
For GA needed two methods:

BigInteger greyToBigInteger(boolean[]){...}

and

boolean[] bigIntegerToGrey(BigInteger){...}

For example:

15 ---> {true,false,false,false}
and
{true,false,false,false} --> 15

I don't know, how to make that very fast. Max number to convert is 10^1125, so it works more than 5 minutes for one number, if I do it, like in Wikipedia example.

Body:
I've writen this piece of code, and it run pretty fast without any special tricks - on my laptop machine it takes less than 2 milliseconds to convert the given number that is less than or equal 10^1125 to gray and back:

import java.math.BigInteger;
import java.util.Random;

public class GrayCode {

    public static void main(String[] args) {

        // actually 10^1125 is a number with max length of 3738 bits
        int bitLength = new BigInteger("10").pow(1125).bitLength();
        System.out.println("10^1125 is a number with max bit length = " + bitLength);
        new GrayCode().test(bitLength);
    }

    private void test(int bitLength) {
        long totalTime = 0;
        long numberOfTests = 1000;

        for (int n = 0; n < numberOfTests; n++) {
            // We don't include time needed for generation of a number
            BigInteger binary = generateBigInteger(bitLength);

            // here we start measuring execution time of single conversion
            long start = System.currentTimeMillis();

            // The conversion to gray and back
            boolean[] gray = bigIntegerToGrey(binary);
            BigInteger back = grayToBigInteger(gray);

            // we sum up the conversion times to totalTime per this test suite
            totalTime += System.currentTimeMillis() - start;
        }
        System.out.println("We have run a "+numberOfTests+" tests, for a random numbers of "+bitLength+" bit length to convert to gray code and back to binary");
        System.out.println("The total execution time of this test was "+totalTime+" milliseconds, giving average convesion time of " + totalTime/1000d + " ms per single test ");

    }

    private BigInteger grayToBigInteger(boolean[] booleanGray) {
        BigInteger input = booleanToBigInteger(booleanGray);
        return grayToBinary(input);
    }

    private boolean[] bigIntegerToGrey(BigInteger binary) {
        BigInteger gray = binaryToGray(binary);
        return bigIntegerToBooleanArray(gray);
    }

    public boolean[] bigIntegerToBooleanArray(BigInteger number) {
        char[] binary = number.toString(2).toCharArray();
        boolean[] binaryBoolean = new boolean[binary.length];
        for (int n = 0; n < binary.length; n++) {
            if (binary[n] == '1') {
                binaryBoolean[n] = true;
            }
        }
        return binaryBoolean;
    }

    private BigInteger generateBigInteger(int numBits) {
        Random rnd = new Random();
        BigInteger number = new BigInteger(numBits, rnd);
        return number;
    }

    public BigInteger booleanToBigInteger(boolean[] binary) {
        StringBuilder sb = new StringBuilder();
        for (boolean b : binary) {
            sb.append(b ? '1' : '0');
        }
        return new BigInteger(sb.toString(), 2);
    }

    public BigInteger binaryToGray(BigInteger num) {
        return num.xor(num.shiftRight(1));
    }

    public BigInteger grayToBinary(BigInteger num) {
        BigInteger mask;
        for (mask = num.shiftRight(1); mask.compareTo(BigInteger.ZERO) != 0; mask = mask.shiftRight(1)) {
            num = num.xor(mask);
        }
        return num;
    }

}

the results:

10^1125 is a number with max bit length = 3738
We have run a 1000 tests, for a number of 3738 bit length to convert to gray code and back to binary
The total execution time of this test was 1828 milliseconds, giving average convesion time of 1.828 ms per single test


问:
Jenkins build blocks because of a windows form
We have a .net application where it checks whether the build is on release mode and open up a simple windows form to input the version as a pre build event. I made this form to automatically close in 10 seconds if the user does not give an input. But unfortunately, in Jenkins, the build gets stuck on this step without going forward. So my guess was since Jenkins runs on command line it waits until the user input for continue. But even when I add automatically close the form it does not continue. Is there a way to build this job without UI blocking Jenkins? </p>

答:
You are not using Jenkins in the optimal way. Here are a few tips to help you out:

Get rid of your windows form to increment version

Add a CommonAssemblyInfo.cs in your visual studio solution with an initial version number

Force Jenkins to increment the version automatically [described below]

Commit the file by jenkins using git publisher or using svn.exe with commit flag

Reading Version number using powershell:

```<code>param([string]$assemblyInfoPath, [string]$workSpace)

$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)

$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)

$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"

$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'

$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")

$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path
</code>```

Increment Version using powershell:

```<code>#
# This script will increment the build number in an AssemblyInfo.cs file
#
param([string]$assemblyInfoPath, [string]$workSpace)

$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)

$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)

#Parse out the current build number from the AssemblyFileVersion
$currentBuild = [RegEx]::Match($versionString,"(\.)(\d+)(""\))").Groups[2]
Write-Host ("Current Build: " + $currentBuild.Value)

#Increment the build number
$newBuild= [int]$currentBuild.Value +  1
Write-Host ("New Build: " + $newBuild)

#update AssemblyFileVersion and AssemblyVersion, then write to file
Write-Host ("Setting version in assembly info file ")
$contents = [RegEx]::Replace($contents, "(AssemblyVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
$contents = [RegEx]::Replace($contents, "(AssemblyFileVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
[System.IO.File]::WriteAllText($assemblyInfoPath, $contents)

$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"

$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'

$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")

$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path
</code>```

Usage in Jenkins:

Version Format in CommonAssembly: 1.0.0.0

After incrementing: 1.0.0.1

Body:
You are not using Jenkins in the optimal way. Here are a few tips to help you out:

Get rid of your windows form to increment version

Add a CommonAssemblyInfo.cs in your visual studio solution with an initial version number

Force Jenkins to increment the version automatically [described below]

Commit the file by jenkins using git publisher or using svn.exe with commit flag

Reading Version number using powershell:

param([string]$assemblyInfoPath, [string]$workSpace)

$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)

$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)

$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"

$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'

$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")

$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path

Increment Version using powershell:

#
# This script will increment the build number in an AssemblyInfo.cs file
#
param([string]$assemblyInfoPath, [string]$workSpace)

$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)

$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)

#Parse out the current build number from the AssemblyFileVersion
$currentBuild = [RegEx]::Match($versionString,"(\.)(\d+)(""\))").Groups[2]
Write-Host ("Current Build: " + $currentBuild.Value)

#Increment the build number
$newBuild= [int]$currentBuild.Value +  1
Write-Host ("New Build: " + $newBuild)

#update AssemblyFileVersion and AssemblyVersion, then write to file
Write-Host ("Setting version in assembly info file ")
$contents = [RegEx]::Replace($contents, "(AssemblyVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
$contents = [RegEx]::Replace($contents, "(AssemblyFileVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
[System.IO.File]::WriteAllText($assemblyInfoPath, $contents)

$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"

$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'

$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")

$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path

Usage in Jenkins:

Version Format in CommonAssembly: 1.0.0.0

After incrementing: 1.0.0.1


问:
How to use the methods of the parent class?
Here the SMS_Store inherits the Message, but every time I call the parent method there is the error:

NoneType object does not have attribute 'read_message'.

and also the object stored in the list returns a None value??

```<code>class Message():

    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed=False
        self.from_number= from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def getTime(self):
        return self.time_arrived

    def getText(self):
        return self.text_of_sms

    def setView(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store(Message):

    def __init__(self):
        self.list_=[]

    def add_new_arrivals(self,from_number, time_arrived, text_of_sms):
        self.list_.append(Message.__init__(self,from_number,time_arrived,text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread =[]
        for i in range(len(self.list_)):
            if(super(SMS_Store,self).check_read() == False):
                unread.append(i)
        return unread

    def read_message(self,index):
        self.list_[index].getText()

    def delete(self,ints):
        a = int(ints)
        self.list_.pop(a)

    def clear():
        for i in list:
            self.list_.pop(i)

inbox = SMS_Store()
inbox.add_new_arrivals(12,9,'some nights i stay up')
inbox.add_new_arrivals(12,5,'cashing in my bad luck')
inbox.add_new_arrivals(14,7,'somenights i call it a draw')
inbox.add_new_arrivals(56,0,'somenights i wish that my lips could built a castle.')
inbox.read_message(0)
</code>```

答:
You shouldn't use inheritance in this case. Here's corrected version (also fixed code style):</p>

```<code>class Message:
    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed = False
        self.from_number = from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def get_time(self):
        return self.time_arrived

    def get_text(self):
        return self.text_of_sms

    def set_view(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMSStore:
    def __init__(self):
        self._list = []

    def add_new_arrivals(self, from_number, time_arrived, text_of_sms):
        self._list.append(Message(from_number, time_arrived, text_of_sms))

    def message_count(self):
        return len(self._list)

    def get_unread_index(self):
        return list(filter(lambda m: not m.check_read(), self._list))

    def read_message(self, index):
        return self._list[index].get_text()

    def delete(self, index):
        a = int(index)
        self._list.pop(a)

    def clear(self):
        self._list = []

inbox = SMSStore()
inbox.add_new_arrivals(12, 9, 'some nights i stay up')
inbox.add_new_arrivals(12, 5, 'cashing in my bad luck')
inbox.add_new_arrivals(14, 7, 'somenights i call it a draw')
inbox.add_new_arrivals(56, 0, 'somenights i wish that my lips could built a castle.')
print(inbox.read_message(0))
</code>```

Body:
Here the SMS_Store inherits the Message, but every time I call the parent method there is the error:

NoneType object does not have attribute 'read_message'.

and also the object stored in the list returns a None value??

class Message():

    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed=False
        self.from_number= from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def getTime(self):
        return self.time_arrived

    def getText(self):
        return self.text_of_sms

    def setView(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store(Message):

    def __init__(self):
        self.list_=[]

    def add_new_arrivals(self,from_number, time_arrived, text_of_sms):
        self.list_.append(Message.__init__(self,from_number,time_arrived,text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread =[]
        for i in range(len(self.list_)):
            if(super(SMS_Store,self).check_read() == False):
                unread.append(i)
        return unread

    def read_message(self,index):
        self.list_[index].getText()

    def delete(self,ints):
        a = int(ints)
        self.list_.pop(a)

    def clear():
        for i in list:
            self.list_.pop(i)

inbox = SMS_Store()
inbox.add_new_arrivals(12,9,'some nights i stay up')
inbox.add_new_arrivals(12,5,'cashing in my bad luck')
inbox.add_new_arrivals(14,7,'somenights i call it a draw')
inbox.add_new_arrivals(56,0,'somenights i wish that my lips could built a castle.')
inbox.read_message(0)

Body:
You shouldn't use inheritance in this case. Here's corrected version (also fixed code style):

class Message:
    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed = False
        self.from_number = from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def get_time(self):
        return self.time_arrived

    def get_text(self):
        return self.text_of_sms

    def set_view(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMSStore:
    def __init__(self):
        self._list = []

    def add_new_arrivals(self, from_number, time_arrived, text_of_sms):
        self._list.append(Message(from_number, time_arrived, text_of_sms))

    def message_count(self):
        return len(self._list)

    def get_unread_index(self):
        return list(filter(lambda m: not m.check_read(), self._list))

    def read_message(self, index):
        return self._list[index].get_text()

    def delete(self, index):
        a = int(index)
        self._list.pop(a)

    def clear(self):
        self._list = []

inbox = SMSStore()
inbox.add_new_arrivals(12, 9, 'some nights i stay up')
inbox.add_new_arrivals(12, 5, 'cashing in my bad luck')
inbox.add_new_arrivals(14, 7, 'somenights i call it a draw')
inbox.add_new_arrivals(56, 0, 'somenights i wish that my lips could built a castle.')
print(inbox.read_message(0))


问:
Pandas — match last identical row and compute difference
With a DataFrame like the following:

```<code>         timestamp    value
0       2012-01-01      3.0
1       2012-01-05      3.0
2       2012-01-06      6.0
3       2012-01-09      3.0
4       2012-01-31      1.0
5       2012-02-09      3.0
6       2012-02-11      1.0
7       2012-02-13      3.0
8       2012-02-15      2.0
9       2012-02-18      5.0
</code>```

What would be an elegant and efficient way to add a time_since_last_identical column, so that the previous example would result in:

```<code>         timestamp    value   time_since_last_identical
0       2012-01-01      3.0                         NaT
1       2012-01-05      3.0                      5 days
2       2012-01-06      6.0                         NaT
3       2012-01-09      3.0                      4 days
4       2012-01-31      1.0                         NaT
5       2012-02-09      3.0                     31 days
6       2012-02-11      1.0                     10 days
7       2012-02-13      3.0                      4 days
8       2012-02-15      2.0                         NaT
9       2012-02-18      5.0                         NaT
</code>```

The important part of the problem is not necessarily the usage of time delays. Any solution that matches one particular row with the previous row of identical value, and computes something out of those two rows (here, a difference) will be valid.

Note: not interested in apply or loop-based approaches.

答:
Here is a solution using pandas groupby:

```<code>out = df.groupby(df['value'])\
        .apply(lambda x: pd.to_datetime(x['timestamp'], format = "%Y-%m-%d").diff())\
        .reset_index(level = 0, drop = False)\
        .reindex(df.index)\
        .rename(columns = {'timestamp' : 'time_since_last_identical'})

out = pd.concat([df['timestamp'], out], axis = 1)
</code>```

That gives the following output:

```<code>    timestamp  value  time_since_last_identical
0  2012-01-01    3.0        NaT
1  2012-01-05    3.0     4 days
2  2012-01-06    6.0        NaT
3  2012-01-09    3.0     4 days
4  2012-01-31    1.0        NaT
5  2012-02-09    3.0    31 days
6  2012-02-11    1.0    11 days
7  2012-02-13    3.0     4 days
8  2012-02-15    2.0        NaT
9  2012-02-18    5.0        NaT
</code>```

It does not exactly match your desired output, but I guess it is a matter of conventions (e.g. whether to include current day or not). Happy to refine if you provide more details.

Body:
With a DataFrame like the following:

         timestamp    value
0       2012-01-01      3.0
1       2012-01-05      3.0
2       2012-01-06      6.0
3       2012-01-09      3.0
4       2012-01-31      1.0
5       2012-02-09      3.0
6       2012-02-11      1.0
7       2012-02-13      3.0
8       2012-02-15      2.0
9       2012-02-18      5.0

What would be an elegant and efficient way to add a time_since_last_identical column, so that the previous example would result in:

         timestamp    value   time_since_last_identical
0       2012-01-01      3.0                         NaT
1       2012-01-05      3.0                      5 days
2       2012-01-06      6.0                         NaT
3       2012-01-09      3.0                      4 days
4       2012-01-31      1.0                         NaT
5       2012-02-09      3.0                     31 days
6       2012-02-11      1.0                     10 days
7       2012-02-13      3.0                      4 days
8       2012-02-15      2.0                         NaT
9       2012-02-18      5.0                         NaT

The important part of the problem is not necessarily the usage of time delays. Any solution that matches one particular row with the previous row of identical value, and computes something out of those two rows (here, a difference) will be valid.

Note: not interested in apply or loop-based approaches.

Body:
Here is a solution using pandas groupby:

out = df.groupby(df['value'])\
        .apply(lambda x: pd.to_datetime(x['timestamp'], format = "%Y-%m-%d").diff())\
        .reset_index(level = 0, drop = False)\
        .reindex(df.index)\
        .rename(columns = {'timestamp' : 'time_since_last_identical'})

out = pd.concat([df['timestamp'], out], axis = 1)

That gives the following output:

    timestamp  value  time_since_last_identical
0  2012-01-01    3.0        NaT
1  2012-01-05    3.0     4 days
2  2012-01-06    6.0        NaT
3  2012-01-09    3.0     4 days
4  2012-01-31    1.0        NaT
5  2012-02-09    3.0    31 days
6  2012-02-11    1.0    11 days
7  2012-02-13    3.0     4 days
8  2012-02-15    2.0        NaT
9  2012-02-18    5.0        NaT

It does not exactly match your desired output, but I guess it is a matter of conventions (e.g. whether to include current day or not). Happy to refine if you provide more details.


问:
Need a single SELECT query in php
I am having three parameters $page, $date, $search. i need a single select sql query where i have to check all the three variables one by one whether any of these variables is having some value or not or if all of the three variables is having some value. According to which it will match from the database and give the result. Please help me out.</p>

答:
You can make where clause as follows in your Select query.(Below is MS SQL format, you can modify CASE statement equivalent with MY SQL)</p>

```<code>SELECT * FROM TABLE (if more than one table, you can use join)
WHERE  TABLE.search_COLUMN = case when @search <> '' then  @search else TABLE.search_COLUMN end
AND
TABLE.page_value_COLUMN = case when @page_value <> '' then  @page_value else TABLE.page_value_COLUMN end
AND
TABLE.date_value_COLUMN = case when @date_value <> '' then  @date_value else TABLE.date_value_COLUMN end
</code>```

Title: Need a single SELECT query in php

Body:
You can make where clause as follows in your Select query.(Below is MS SQL format, you can modify CASE statement equivalent with MY SQL)

SELECT * FROM TABLE (if more than one table, you can use join)
WHERE  TABLE.search_COLUMN = case when @search <> '' then  @search else TABLE.search_COLUMN end
AND
TABLE.page_value_COLUMN = case when @page_value <> '' then  @page_value else TABLE.page_value_COLUMN end
AND
TABLE.date_value_COLUMN = case when @date_value <> '' then  @date_value else TABLE.date_value_COLUMN end


问:
Keycloak redirect_fragment conflicts with react-router hashRouter
I'm running into an issue with the redirection that happens after a user of my app authenticates with Keycloak.

My app uses react-router hashRouter. When the initial redirect happens, I get a redirect_fragment that looks something like this:

http://localhost:3000/lol.html?redirect_fragment=%2F&redirect_fragment=%2Fstate%3D1c5900ee-954f-4532-b01c-dcf5d88f07a2%26code%3DKZNXVqQCcIXTCFu2ZIkx4quXa6zJb59zGKpNIhZwfNo.d2786d1e-67cd-437f-a873-bad49126bad4&redirect_fragment=%2Fstate%3D51a9cb44-b80a-4c14-8f3d-f04dfdb84377%26code%3Dp5cKQ7xVCR_n1s4ucXZTSE3O1T5lwNri_PBKD07Mt1Y.63364a83-f04f-4e64-a33e-faf00f6cd4ff&redirect_fragment=%2Fstate%3D05155315-ab60-4990-8d4e-444c7cce9748%26code%3DBxxpf_uMB28rKAQ6MXFTTrL9RE4rC3UtwCMXLu_K1Zo.4ce56da0-8e52-47e3-a0f2-4f982599bb98#/state=f3e362e4-c030-40ac-80df-9f9882296977&code=8HHTgd3KdlfwcupXR_5nDV0CqZNPV1xdCu3udc6l5xM.97b3ea71-366a-4038-a7ce-30ac2f416807

The URL keeps growing from there. I've read a few posts already that indicate that redirection from keycloak might have a problem with client-side routing via location.hash ... Any thoughts would be appreciated!

答:
I think I figured it out!

The redirection loop seems to stop if I use the 'noslash' hashRouter instead of the default which contains a slash.

My URLs look like this: localhost:3000/lol.html#client/side/route

instead of this: localhost:3000/lol.html#/client/side/route

The redirection now seems to terminate appropriately after one redirect, but now I'm running into a different problem where the hash portion of my route is not being honored by react-router...

EDIT: I figured the second issue out

react-router creates a wrapper around window.location that it uses to tell which client side "page" it is currently on. I found that this wrapper was out of sync with window.location.

Check this console output out. This was taken immediately after the redirection resolved (and the page was blank):

history pathname is /state=aon03i-238hnsln-soih930-8hsdlkh9-982hnkui-89hkgyq-8ihbei78-893hiugsu

history hash is (empty)

window.location pathname is /lol.html

window.location hash is #users/1

The state=blah-blah-blah in the history.pathname is part of the redirect url that keycloak sends back after auth. You'll notice that window.location is updated to the correct path / hash, but that history seems to be one URL behind. Maybe keycloak directly modifies window.location to perform this redirection?

I tried using a history.push(window.location.hash) to push the hash fragment and update react router, but got the error "this entry already exists on the stack". Since it clearly is not on the top of the location stack, this led me to believe that react-router compares window.location with its internal location to figure out where it ultimately is. So how did I get around this?

I used history.replace() instead, which just replaces the entry on the top of the stack with a new value, instead of pushing a new entry to the stack. This also makes sense, since we don't want users who navigate "back" in their browsers to go back to that /state=blah-blah-blah url <-- replace eliminates this entry from the history stack.

One final piece: react-router history.location, like window.location, has both pathname and hash components. HashRouter uses the history.location.pathname component to keep track of the client side route after the hash in the browser. The equivalent of this in window.location is stored in window.location.hash, so we will be using this as the value passed to history.replace() instead of window.location.pathname. This confused me for a bit, but makes sense when you think about it.

react-router history also keeps track of its current route with a prepended / instead of a prepended #, since it's just treating it like any normal URL. Before I called history.replace(), I needed to take my window.location.hash, replace the leading hash with a / and then pass that value history.replace()

const slashPath = window.location.hash.replace('#', '/');
history.replace(slashPath);

Whew!

Body:
I'm running into an issue with the redirection that happens after a user of my app authenticates with Keycloak.

My app uses react-router hashRouter. When the initial redirect happens, I get a redirect_fragment that looks something like this:

<a href="http://localhost:3000/lol.html?redirect_fragment=%2F&redirect_fragment=%2Fstate%3D1c5900ee-954f-4532-b01c-dcf5d88f07a2%26code%3DKZNXVqQCcIXTCFu2ZIkx4quXa6zJb59zGKpNIhZwfNo.d2786d1e-67cd-437f-a873-bad49126bad4&redirect_fragment=%2Fstate%3D51a9cb44-b80a-4c14-8f3d-f04dfdb84377%26code%3Dp5cKQ7xVCR_n1s4ucXZTSE3O1T5lwNri_PBKD07Mt1Y.63364a83-f04f-4e64-a33e-faf00f6cd4ff&redirect_fragment=%2Fstate%3D05155315-ab60-4990-8d4e-444c7cce9748%26code%3DBxxpf_uMB28rKAQ6MXFTTrL9RE4rC3UtwCMXLu_K1Zo.4ce56da0-8e52-47e3-a0f2-4f982599bb98#/state=f3e362e4-c030-40ac-80df-9f9882296977&code=8HHTgd3KdlfwcupXR_5nDV0CqZNPV1xdCu3udc6l5xM.97b3ea71-366a-4038-a7ce-30ac2f416807" rel="nofollow noreferrer">http://localhost:3000/lol.html?redirect_fragment=%2F&redirect_fragment=%2Fstate%3D1c5900ee-954f-4532-b01c-dcf5d88f07a2%26code%3DKZNXVqQCcIXTCFu2ZIkx4quXa6zJb59zGKpNIhZwfNo.d2786d1e-67cd-437f-a873-bad49126bad4&redirect_fragment=%2Fstate%3D51a9cb44-b80a-4c14-8f3d-f04dfdb84377%26code%3Dp5cKQ7xVCR_n1s4ucXZTSE3O1T5lwNri_PBKD07Mt1Y.63364a83-f04f-4e64-a33e-faf00f6cd4ff&redirect_fragment=%2Fstate%3D05155315-ab60-4990-8d4e-444c7cce9748%26code%3DBxxpf_uMB28rKAQ6MXFTTrL9RE4rC3UtwCMXLu_K1Zo.4ce56da0-8e52-47e3-a0f2-4f982599bb98#/state=f3e362e4-c030-40ac-80df-9f9882296977&code=8HHTgd3KdlfwcupXR_5nDV0CqZNPV1xdCu3udc6l5xM.97b3ea71-366a-4038-a7ce-30ac2f416807

The URL keeps growing from there. I've read a few posts already that indicate that redirection from keycloak might have a problem with client-side routing via location.hash ... Any thoughts would be appreciated!


问:
Can't edit file on android (wpa_supplicant is read only)
So i'm trying to connect 3 cameras (andoer 360) to one access point on my mobile.
I want to edit the wpa_supplicant_ap.conf, but this file is read only and i can't change it.

I'd really appreciate some help cause i can't move on.

答:
wpa_supplicant.conf file description from here says that

```<code># NOTE! This file may contain password information and should probably be made
# readable only by root user on multiuser systems.
</code>```

Typical file directory is /data/misc/wifi/wpa_supplicant.conf

You need root access to edit it or change access rights. Without root access only the mechanism of flashing an update (via recovery or OTA) can modify /system. There might be a way via a custom recovery which lets you edit all file systems directly (for example TWRP).

Here and here is the same problem.

Body:
wpa_supplicant.conf file description from here says that

# NOTE! This file may contain password information and should probably be made
# readable only by root user on multiuser systems.

Typical file directory is /data/misc/wifi/wpa_supplicant.conf

You need root access to edit it or change access rights. Without root access only the mechanism of flashing an update (via recovery or OTA) can modify /system. There might be a way via a custom recovery which lets you edit all file systems directly (for example TWRP).

Here and here is the same problem.


问:
JSTL in custom tag not parsed
I've implemented a custom tag that print some information about the logged user using JSTL core and format libary. Everything is working but the getJspContext().getOut().println("<fmt:message key='search'/>"); is not parsed in the JSP.

In the page, the <fmt:message is not interpreted.

This is my code:

navbar.tld

```<code><tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>testing</short-name>
<uri>/WEB-INF/tld/navbar.tld</uri>
<description>This is a demonstration tag library</description>

<tag>
    <name>userInformation</name>
    <tag-class>tag.NavbarTagHandler</tag-class>
    <body-content>scriptless</body-content>
    <description>This tag is for displaying headers of the navbar</description>

</tag>
</code>```

NavbarTagHandler

```<code>public class NavbarTagHandler extends SimpleTagSupport {

@Override
public void doTag() throws JspException {
    User user = null;
    user = (User) getJspContext().getAttribute("authenticatedUser", PageContext.SESSION_SCOPE);

    JspWriter out = getJspContext().getOut();

    try {
        if (user == null) {
            //not logged
            out.println("Not logged <fmt:message key='message1'/>");
            out.flush();
        } else {
            //logged
            out.println("Logged <fmt:message key='message2'/>");
            out.flush();
        }
    } catch (IOException es) {
        es.printStackTrace();
    }

}
</code>```

How can make it parsable?

答:
The used custom taglib is from JSP spec 1.0 and it does not allow nested tag interpretation.
In order to achieve this you need to use JSP spec 2.0 taglib specification which allows us to implement a JSP as a taglib.

Therefore,it allows using multiple tags within one taglib implementation.

Define the taglib content in a .tag file,along with the external taglibs

Refer the taglib in the general usable format

Elaboration

In order to create an use a custome tag,we need to follow couple of steps:

Create a tag file,defining the attributes used by it and any variables which will be used by the tag

a. The attributes need to have a name,their type and and required field with a boolean value

b. The variables will be defined with a name along with a certain scope-

NESTED(Available in tag body),

AT_BEGIN(Within tag till end of scope) and

AT_END(From end of tag till end of scope)

```<code>    <%@ attribute name="name" required="true" type="java.lang.String" description="Name of User"  %>
    <%@ attribute name="role" required="true" type="java.lang.String" description="Role of User" %>
    <%@ variable name-given="passBack" scope="AT_BEGIN"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <h1>${name}</h1>
    <h2>${role}</h2>

    <%String backToCaller="Back to caller";%>
    <c:set var="passBack" value="Pass back successful"/>
</code>```

Define the entry to import tag,where tagdir will be directory containing tag file with .tag extension

```<code><%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
</code>```

Finally use the tag,passing the required attributes,as per tag definition.
Here customTag is the name of the tag file,along with prefix as defined

```<code><tags:customTag name="Hello Tag!!" role="I am the boss here"/>
</code>```

The variable set from tag can be retrieved in the caller jsp using expression language

Hello ${passBack}

Title: JSTL in custom tag not parsed

Body:
I've implemented a custom tag that print some information about the logged user using JSTL core and format libary. Everything is working but the getJspContext().getOut().println("<fmt:message key='search'/>"); is not parsed in the JSP.

In the page, the <fmt:message is not interpreted.

This is my code:

navbar.tld

<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>testing</short-name>
<uri>/WEB-INF/tld/navbar.tld</uri>
<description>This is a demonstration tag library</description>

<tag>
    <name>userInformation</name>
    <tag-class>tag.NavbarTagHandler</tag-class>
    scriptless
    <description>This tag is for displaying headers of the navbar</description>

</tag>

NavbarTagHandler

public class NavbarTagHandler extends SimpleTagSupport {

@Override
public void doTag() throws JspException {
    User user = null;
    user = (User) getJspContext().getAttribute("authenticatedUser", PageContext.SESSION_SCOPE);

    JspWriter out = getJspContext().getOut();

    try {
        if (user == null) {
            //not logged
            out.println("Not logged <fmt:message key='message1'/>");
            out.flush();
        } else {
            //logged
            out.println("Logged <fmt:message key='message2'/>");
            out.flush();
        }
    } catch (IOException es) {
        es.printStackTrace();
    }

}

How can make it parsable?

Body:
The used custom taglib is from JSP spec 1.0 and it does not allow nested tag interpretation.
In order to achieve this you need to use JSP spec 2.0 taglib specification which allows us to implement a JSP as a taglib.

Therefore,it allows using multiple tags within one taglib implementation.

Define the taglib content in a .tag file,along with the external taglibs

Refer the taglib in the general usable format

Elaboration

In order to create an use a custome tag,we need to follow couple of steps:

Create a tag file,defining the attributes used by it and any variables which will be used by the tag

a. The attributes need to have a name,their type and and required field with a boolean value

b. The variables will be defined with a name along with a certain scope-

NESTED(Available in tag body),

AT_BEGIN(Within tag till end of scope) and

AT_END(From end of tag till end of scope)

    <%@ attribute name="name" required="true" type="java.lang.String" description="Name of User"  %>
    <%@ attribute name="role" required="true" type="java.lang.String" description="Role of User" %>
    <%@ variable name-given="passBack" scope="AT_BEGIN"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <h1>${name}</h1>
    <h2>${role}</h2>

    <%String backToCaller="Back to caller";%>
    <c:set var="passBack" value="Pass back successful"/>

Define the entry to import tag,where tagdir will be directory containing tag file with .tag extension

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>

Finally use the tag,passing the required attributes,as per tag definition.
Here customTag is the name of the tag file,along with prefix as defined

<tags:customTag name="Hello Tag!!" role="I am the boss here"/>

The variable set from tag can be retrieved in the caller jsp using expression language

Hello ${passBack}


问:
Java's Float.floatToIntBits implementation code in C\C++
I want the source code for java's Float.floatToIntBits() implementation code in C\C++.</p>

答:
This seems to be the best solution:

```<code>#include <cstring>

unsigned float_to_bits(float x)
{
    unsigned y;
    memcpy(&y, &x, 4);
    return y;
}
</code>```

Of course this depends on float and unsigned consuming 4 bytes.

Body:
This seems to be the best solution:

#include <cstring>

unsigned float_to_bits(float x)
{
    unsigned y;
    memcpy(&y, &x, 4);
    return y;
}

Of course this depends on float and unsigned consuming 4 bytes.


问:
how do you translate your toast?
hi my toast needs to translate to France or English depending on what you select as your language, in the login screen you can select your languages </p>

答: You can create different string resource file based on country. Then android will automatically refer the message from proper string file based on the selected language.</p>

Title: how do you translate your toast?


问:
reading middlebury 'flow' files with python (bytes array & numpy)
I'm trying to read a .flo file as a numpy 2Channels image.

The format is described like this:

".flo" file format used for optical flow evaluation

Stores 2-band float image for horizontal (u) and vertical (v) flow components.
Floats are stored in little-endian order.
A flow value is considered "unknown" if either |u| or |v| is greater than 1e9.

bytes  contents

0-3     tag: "PIEH" in ASCII, which in little endian happens to be the float 202021.25
        (just a sanity check that floats are represented correctly)
4-7     width as an integer
8-11    height as an integer
12-end  data (width*height*2*4 bytes total)
        the float values for u and v, interleaved, in row order, i.e.,
        u[row0,col0], v[row0,col0], u[row0,col1], v[row0,col1], ...
```

<p>(Excerpt from this readme)</p>

<p>Here's my code but I'm kind of stuck, I don't know how to read the file as a 2 Channels numpy 2D array. </p>

<pre class="lang-none prettyprint-override"><code>import numpy as np
import os

# test.flo, 512*512 optical flow file

f = open('test.flo', 'rb')
f.seek(11, os.SEEK_SET)  # skip header bytes

data_array = np.fromfile(f, np.float16)
data_2D = np.resize(data_array, (512, 512))
</code>```

Maybe someone knows how to do that ?

答:
bsa's answer does not work for python 3.5 onwards. The small modification shown below, e.g. np.fromfile(f, np.int32, count=1)[0], will. </p>

```<code>import numpy as np
import os
import sys

# WARNING: this will work on little-endian architectures (eg Intel x86) only!
if '__main__' == __name__:
    if len(sys.argv) > 1:
        with open(sys.argv[1], 'rb') as f:
            magic = np.fromfile(f, np.float32, count=1)
            if 202021.25 != magic:
                print('Magic number incorrect. Invalid .flo file')
            else:
                w = np.fromfile(f, np.int32, count=1)[0]
                h = np.fromfile(f, np.int32, count=1)[0]
                print('Reading %d x %d flo file' % (w, h))
                data = np.fromfile(f, np.float32, count=2*w*h)
                # Reshape data into 3D array (columns, rows, bands)
                data2D = np.resize(data, (h, w, 2))
    else:
        print('Specify a .flo file on the command line.')
</code>```

Body:
I'm trying to read a .flo file as a numpy 2Channels image.

The format is described like this:

".flo" file format used for optical flow evaluation

Stores 2-band float image for horizontal (u) and vertical (v) flow components.
Floats are stored in little-endian order.
A flow value is considered "unknown" if either |u| or |v| is greater than 1e9.

bytes  contents

0-3     tag: "PIEH" in ASCII, which in little endian happens to be the float 202021.25
        (just a sanity check that floats are represented correctly)
4-7     width as an integer
8-11    height as an integer
12-end  data (width*height*2*4 bytes total)
        the float values for u and v, interleaved, in row order, i.e.,
        u[row0,col0], v[row0,col0], u[row0,col1], v[row0,col1], ...

(Excerpt from this readme)

Here's my code but I'm kind of stuck, I don't know how to read the file as a 2 Channels numpy 2D array.

import numpy as np
import os

# test.flo, 512*512 optical flow file

f = open('test.flo', 'rb')
f.seek(11, os.SEEK_SET)  # skip header bytes

data_array = np.fromfile(f, np.float16)
data_2D = np.resize(data_array, (512, 512))

Maybe someone knows how to do that ?

Body:
bsa's answer does not work for python 3.5 onwards. The small modification shown below, e.g. np.fromfile(f, np.int32, count=1)[0], will.

import numpy as np
import os
import sys

# WARNING: this will work on little-endian architectures (eg Intel x86) only!
if '__main__' == __name__:
    if len(sys.argv) > 1:
        with open(sys.argv[1], 'rb') as f:
            magic = np.fromfile(f, np.float32, count=1)
            if 202021.25 != magic:
                print('Magic number incorrect. Invalid .flo file')
            else:
                w = np.fromfile(f, np.int32, count=1)[0]
                h = np.fromfile(f, np.int32, count=1)[0]
                print('Reading %d x %d flo file' % (w, h))
                data = np.fromfile(f, np.float32, count=2*w*h)
                # Reshape data into 3D array (columns, rows, bands)
                data2D = np.resize(data, (h, w, 2))
    else:
        print('Specify a .flo file on the command line.')

ContentLicense: CC BY-SA 4.0


问:
SyncAdapter: Account created, requestSync OK, but setSyncAutomatically not Working
I just created an Account for my app.

The account is visible in settings

I set syncable="true" in my XML

I can perform a manual sync by pressing the settings -> onPerformSync
is called

I can perform a "code" sync by calling ContentResolver.requestSync -> onPerformSync is called

And of course, yes, the sync is enabled in settings. I don't use any power saver.

I also followed all the steps from here: https://stackoverflow.com/a/5255360/327402

This is my code to get the sync by code

```<code>AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(ACCOUNT);
//Log.e("DEBUG", "Accounts: " + accounts.length);
if (accounts.length == 0) {
    Account account = new Account(getString(R.string.app_name), ACCOUNT);
    ContentResolver.setIsSyncable(account, AUTHORITY, 1);
    ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 7200);
    ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
    if (am.addAccountExplicitly(account, "pass1", null))
        Log.i("DEBUG", "account Created: " + account.name + ", " + account.type);
    else
        Log.i("DEBUG", "addAccountExplicitly returned false");
    }
else{
    ContentResolver.requestSync(accounts[0], AUTHORITY, new Bundle());// THIS IS WORKING!!!
    }
}
</code>```

So, everything looks correct and fine.

But unfortunately, I cannot get a periodic sync! When I open the settings, accounts, I see the account and the date and time is the time when I performed the sync by code, or manually.

Any idea on what I did wrong, or what I forgot?

答:
One important thing to remember is that the periodic sync time is not guaranteed and may not be accurate, this is mentioned in the documentation:

Although these sync are scheduled
  at the specified frequency, it may take longer for it to actually be
  started if other syncs are ahead of it in the sync operation queue.
  This means that the actual start time may drift.

I would also try to create the account using AccountManager and not by creating new Account()

```<code> manager.addAccountExplicitly(account, null, null)
</code>```

And last thing, if this account was just created than you may want to force only the first sync right after you set the automatic sync settings:

```<code> if (accountJustCreated) {
   SyncAdapter.performSync();
 }
</code>```

Body:
I just created an Account for my app.

The account is visible in settings

I set syncable="true" in my XML

I can perform a manual sync by pressing the settings -> onPerformSync
is called

I can perform a "code" sync by calling ContentResolver.requestSync -> onPerformSync is called

And of course, yes, the sync is enabled in settings. I don't use any power saver.

I also followed all the steps from here: https://stackoverflow.com/a/5255360/327402

This is my code to get the sync by code

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(ACCOUNT);
//Log.e("DEBUG", "Accounts: " + accounts.length);
if (accounts.length == 0) {
    Account account = new Account(getString(R.string.app_name), ACCOUNT);
    ContentResolver.setIsSyncable(account, AUTHORITY, 1);
    ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 7200);
    ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
    if (am.addAccountExplicitly(account, "pass1", null))
        Log.i("DEBUG", "account Created: " + account.name + ", " + account.type);
    else
        Log.i("DEBUG", "addAccountExplicitly returned false");
    }
else{
    ContentResolver.requestSync(accounts[0], AUTHORITY, new Bundle());// THIS IS WORKING!!!
    }
}

So, everything looks correct and fine.

But unfortunately, I cannot get a periodic sync! When I open the settings, accounts, I see the account and the date and time is the time when I performed the sync by code, or manually.

Any idea on what I did wrong, or what I forgot?

Body:
One important thing to remember is that the periodic sync time is not guaranteed and may not be accurate, this is mentioned in the documentation:

Although these sync are scheduled
  at the specified frequency, it may take longer for it to actually be
  started if other syncs are ahead of it in the sync operation queue.
  This means that the actual start time may drift.

I would also try to create the account using AccountManager and not by creating new Account()

 manager.addAccountExplicitly(account, null, null)

And last thing, if this account was just created than you may want to force only the first sync right after you set the automatic sync settings:

 if (accountJustCreated) {
   SyncAdapter.performSync();
 }


问:
How to get the key of every single object?
I have a firebase database contains a json data and I append it in cardViews, I want to get the key of the cardView when it clicked but instead it returns an array of the all objects in the database
this is my index.js:

```<code>var rootRef = firebase.database().ref().child("Stories");
rootRef.on("child_added", snap => {
  var title = snap.child("Story Title").val();
  var content = snap.child("Story Content").val();
  $("#stories").append("<div  id=\"cold\" class=\"col s8 m6\"><div
    class=\"card\"><div class=\"card-image\"><img
    src=\"https://www.joshmorony.com/wp-content/uploads/2016/11/firebase.png\">
    <a  class=\"btn-floating halfway-fab waves-effect waves-light red\"><i
    class=\"material-icons\">info</i></a></div><div class=\"card-content\"><p
    onclick=\"viewKey()\">" + title + "</p></div></div></div>");
  });

  function viewKey() {
    firebase.database().ref('/Stories/').once('value').then(function(snapshot) {
      var storiesArray = snapshot.val();
      var keys = Object.keys(storiesArray);
      for (var i = 0; i < keys.length; i++) {
        var currentStory = storiesArray[keys[i]];
       console.log(currentStory);
      }

    });
  }
</code>```

the object array :
["-Ko8JpEjsdN2KGBdIG3f", "-Ko8JtdcEBICVZqIXLdO", "-Ko8TvZuu0Wh_XDGa1YW","-KoBR0NmVmerjomE63-V", "-KoBSOybd5ymvOwz0Ip6"]

答:
I think this may be the answer:  snapshots have a key.

Since you are using child_added, each child is read in one at a time, so each child snap.key will give you the key to that child snapshot. In other words, the code within the closure after the child_added line will run once for each child node within the Stories node.

If you were to use value instead, that would read in ALL of the data in the Stories node in one 'big' snapshot (one parent with multiple children). So it would look like

```<code>Stories
  story_0
    story_info: "ads"
  story_1
    story_info: "assad"
</code>```

In that case, you would need to iterate over the Stories snapshot to get each child (story_0, story_1 etc). Each child would be it's own snapshot with it's own snapshot.key.

See Work with Lists of Data on the Web

This code will output the key for each story when using child_added:

```<code>var storiesRef = firebase.database().ref().child("Stories");
storiesRef.on('child_added', function(snap) {
  console.log(snap.key);
});
</code>```

If you want to get all of the Stories at one time using value, this will read in the Stories node and iterate over the child nodes, outputting each key

```<code>storiesRef.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    console.log(childSnapshot.key);
  });
});
</code>```

Note the child_added function above will get each child and continue to listen for child_added events whereas the value function above will execute once and not listen for future events.

Body:
I have a firebase database contains a json data and I append it in cardViews, I want to get the key of the cardView when it clicked but instead it returns an array of the all objects in the database
this is my index.js:

var rootRef = firebase.database().ref().child("Stories");
rootRef.on("child_added", snap => {
  var title = snap.child("Story Title").val();
  var content = snap.child("Story Content").val();
  $("#stories").append("

    info

" + title + "

");
  });

  function viewKey() {
    firebase.database().ref('/Stories/').once('value').then(function(snapshot) {
      var storiesArray = snapshot.val();
      var keys = Object.keys(storiesArray);
      for (var i = 0; i < keys.length; i++) {
        var currentStory = storiesArray[keys[i]];
       console.log(currentStory);
      }

    });
  }

the object array :
["-Ko8JpEjsdN2KGBdIG3f", "-Ko8JtdcEBICVZqIXLdO", "-Ko8TvZuu0Wh_XDGa1YW","-KoBR0NmVmerjomE63-V", "-KoBSOybd5ymvOwz0Ip6"]

Body:
I think this may be the answer:  snapshots have a key.

Since you are using child_added, each child is read in one at a time, so each child snap.key will give you the key to that child snapshot. In other words, the code within the closure after the child_added line will run once for each child node within the Stories node.

If you were to use value instead, that would read in ALL of the data in the Stories node in one 'big' snapshot (one parent with multiple children). So it would look like

Stories
  story_0
    story_info: "ads"
  story_1
    story_info: "assad"

In that case, you would need to iterate over the Stories snapshot to get each child (story_0, story_1 etc). Each child would be it's own snapshot with it's own snapshot.key.

See Work with Lists of Data on the Web

This code will output the key for each story when using child_added:

var storiesRef = firebase.database().ref().child("Stories");
storiesRef.on('child_added', function(snap) {
  console.log(snap.key);
});

If you want to get all of the Stories at one time using value, this will read in the Stories node and iterate over the child nodes, outputting each key

storiesRef.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    console.log(childSnapshot.key);
  });
});

Note the child_added function above will get each child and continue to listen for child_added events whereas the value function above will execute once and not listen for future events.


问:
Move a sprite along a slope
I'm trying to have a sprite swap places with another sprite. So far I think I can somehow use the slope between the two sprites' original location to move them, but I'm lost as to how to increment their position along that slope.

答:
You'll need to create a vector between the two sprites, normalize it, multiply that normalized vector by how much you want the sprite to move per frame, then add that vector into the sprite you are moving's location.  You didn't specify a language, so here is a little pseudo code:</p>

```<code>var p1 = sprite1.location
var p2 = sprite2.location

var vec = p2.subtract(p1)
vec.normalize()
vec.multiply(6) // I want it to advance 6 units per move

while (sprite1.location != sprite2.location) // best to check with some epsilon
  sprite1.location = sprite1.location.add(vec)
end
</code>```

Title: Move a sprite along a slope

Body:
You'll need to create a vector between the two sprites, normalize it, multiply that normalized vector by how much you want the sprite to move per frame, then add that vector into the sprite you are moving's location.  You didn't specify a language, so here is a little pseudo code:

var p1 = sprite1.location
var p2 = sprite2.location

var vec = p2.subtract(p1)
vec.normalize()
vec.multiply(6) // I want it to advance 6 units per move

while (sprite1.location != sprite2.location) // best to check with some epsilon
  sprite1.location = sprite1.location.add(vec)
end