问:
Resuming automation after a CAPTCHA has been completed
I'm currently writing a program (puppeteer and node.js) that can autonavigate and autofill user data on a specific website. The user is prompted with a CAPTCHA at a certain point, but I'm not sure how to signal to the program that the CAPTCHA has been completed after the fact so that it can resume it's processes.

Right now, the end of my fairly linear processes is

```<code>    await page.type('#orcer.string.required', cvv);
    page.waitFor(50);
    await page.click('input.button')
</code>```

When that last line executes, the CAPTCHA instance is created. Is there a specific function in puppeteer that will allow the program to resume after the user fills it out?

答:
Think of it this way: how does a human user operating browser understand that work may be resumed after captcha is completed?

Some element, like captcha placeholder, is gone or some other element has appeared. Therefore you can use page.waitFor or page.waitForFunction to observe the page for those changes.

```<code>await page.type('#orcer.string.required', cvv);
page.waitFor(50);
await page.click('input.button')
await pageWaitFor('.element-shown-after-captcha-solved')
</code>```

You should also probably disable or set very high timeouts so that script doesn't throw error because of long waiting.

Body:
I'm currently writing a program (puppeteer and node.js) that can autonavigate and autofill user data on a specific website. The user is prompted with a CAPTCHA at a certain point, but I'm not sure how to signal to the program that the CAPTCHA has been completed after the fact so that it can resume it's processes.

Right now, the end of my fairly linear processes is

    await page.type('#orcer.string.required', cvv);
    page.waitFor(50);
    await page.click('input.button')

When that last line executes, the CAPTCHA instance is created. Is there a specific function in puppeteer that will allow the program to resume after the user fills it out?

Body:
Think of it this way: how does a human user operating browser understand that work may be resumed after captcha is completed?

Some element, like captcha placeholder, is gone or some other element has appeared. Therefore you can use page.waitFor or page.waitForFunction to observe the page for those changes.

await page.type('#orcer.string.required', cvv);
page.waitFor(50);
await page.click('input.button')
await pageWaitFor('.element-shown-after-captcha-solved')

You should also probably disable or set very high timeouts so that script doesn't throw error because of long waiting.


来源: stackexchange

问:
Filtering wrong using a timestamp range in django views
When I want to filter my model using one exactly date I use the following code line,

```<code>today = datetime.datetime.now().date()
today_data = DevData.objects.filter(data_timestamp__date=today)
</code>```

And when I want to filter using a range of days, I use the following code line,

```<code>last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(data_timestamp__range=(last7days,today))
</code>```

The problem is that when I use this second code, appears a warning and runs very very slow,

RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-05-31 00:00:00) while time zone support is active.

How can I do it better?

I found this post, but don't understand how to solve it. Can somebody help me please?

答:
You are seeing a warning because last7days variable is not timezone-aware.

You can make it timezone-aware like so:

```<code>import datetime
from datetime import timezone

unaware = datetime.datetime(2020, 1, 1, 1, 1, 1, 1)
aware = unaware.replace(tzinfo=timezone.utc))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I want to filter my model using one exactly date I use the following code line,

today = datetime.datetime.now().date()
today_data = DevData.objects.filter(data_timestamp__date=today)

And when I want to filter using a range of days, I use the following code line,

last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(data_timestamp__range=(last7days,today))

The problem is that when I use this second code, appears a warning and runs very very slow,

RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-05-31 00:00:00) while time zone support is active.

How can I do it better?

I found this post, but don't understand how to solve it. Can somebody help me please?

Body:
You are seeing a warning because last7days variable is not timezone-aware.

You can make it timezone-aware like so:

import datetime
from datetime import timezone

unaware = datetime.datetime(2020, 1, 1, 1, 1, 1, 1)
aware = unaware.replace(tzinfo=timezone.utc))


问:
How to convert Windows ProductType to name?
The GetProductInfo() function returns pdwReturnedProductType as a  numeric type argument.

Is there a function to convert this number to a name?

Or, can you suggest to me a really full list of such product name constants?
The MSDN article is missing some values, like 0x59 - "Industry Pro (Embedded)".

答:
Look at the OSEdition Enumeration defines on MSDN, it has the numeric values you are looking for, including 0x59:

This section provides the product enumerations for the OSEdition element.

```<code>#define PRODUCT_EMBEDDED_INDUSTRY 0x00000059
</code>```

AFAIK, there is no function to convert these numeric values into human readable names.

Body:
Look at the OSEdition Enumeration defines on MSDN, it has the numeric values you are looking for, including 0x59:

This section provides the product enumerations for the OSEdition element.

#define PRODUCT_EMBEDDED_INDUSTRY 0x00000059

AFAIK, there is no function to convert these numeric values into human readable names.


问:
Program for ceasar cipher breaks at strcpy function returning segmentation fault
I wrote a program in C to explore the cesarean cipher but I always get segmentation fault when I run it. Below is the code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char ceaserEncrypt(char string[1000000],int key);

int main(int *argc,char *argv[])
{

char str[1000000] = "Hi there I am fine";
int key = 20;
char val[1000000];
strcpy(val,ceaserEncrypt(str,key));
printf("%s",val);

return 0;
}

char ceaserEncrypt(char string[1000000],int key)
{

 int len = strlen(string);
 char encryptlis[len];

if(key < 1 || key > 26)
{
    fprintf(stderr,"Key provided is invalid");
    exit(-1);
}

 for(int i = 0; i < len; i++)
 {
    if(string[i] = ' '){
        encryptlis[i] = ' ';
        continue;
    }
    int charcode = string[i] + key;
    if(charcode > 122)
    {
        encryptlis[i] = (char) (charcode - 25);
    }

    encryptlis[i] = (char) charcode;

 }

return encryptlis;
}

</code>```

```<code>Operating system: Ubuntu 18.04 LTS
Processor: Intel celeron
RAM Size: 4Gb
compiler: gcc
</code>```

I know about segmentation fault. But in this program I don't see where I accessed an illegal memory location because I provided ample size for the encrpylis and val array.
By the way I am a newbie to C. Any suggestions are welcomed. Thank you already.

答:
Main cause of segmentation fault is that you are trying to access the uninitialised memory location.

The string encryptlis was not initialised.

The return type of the function ceaserEncrypt is not correct.

Also, the conventions to pass string as parameter to the functions should be followed: The accepted convention of passing C-strings to functions is to use a pointer.

Have a look at the following working implementation:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* ceaserEncrypt(char* string,int key);

int main(int argc,char *argv[]){

    char str[100000] = "Hi there I am fine";
    int key = 20;
    char val[100000];

    strcpy(val,ceaserEncrypt(str,key));

    printf("%s",val);

    return 0;
}

char* ceaserEncrypt(char* string,int key)
{

    int len = strlen(string);
    char* encryptlis = (char*)(malloc((len+1) * sizeof(char)));

    if(key < 1 || key > 26)
    {
        fprintf(stderr,"Key provided is invalid");
        exit(-1);
    }

    for(int i = 0; i < len; i++)
    {
        if(string[i] == ' '){
            encryptlis[i] = ' ';
            continue;
        }

        int charcode = string[i] + key;
        if(charcode > 122)
        {
            encryptlis[i] = (char) (charcode - 25);
        }
        else{
            encryptlis[i] = (char) charcode;
        }
    }
    encryptlis[len] = '\0';

    return encryptlis;
}
</code>```

Body:
I wrote a program in C to explore the cesarean cipher but I always get segmentation fault when I run it. Below is the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char ceaserEncrypt(char string[1000000],int key);

int main(int *argc,char *argv[])
{

char str[1000000] = "Hi there I am fine";
int key = 20;
char val[1000000];
strcpy(val,ceaserEncrypt(str,key));
printf("%s",val);

return 0;
}

char ceaserEncrypt(char string[1000000],int key)
{

 int len = strlen(string);
 char encryptlis[len];

if(key < 1 || key > 26)
{
    fprintf(stderr,"Key provided is invalid");
    exit(-1);
}

 for(int i = 0; i < len; i++)
 {
    if(string[i] = ' '){
        encryptlis[i] = ' ';
        continue;
    }
    int charcode = string[i] + key;
    if(charcode > 122)
    {
        encryptlis[i] = (char) (charcode - 25);
    }

    encryptlis[i] = (char) charcode;

 }

return encryptlis;
}

Operating system: Ubuntu 18.04 LTS
Processor: Intel celeron
RAM Size: 4Gb
compiler: gcc

I know about segmentation fault. But in this program I don't see where I accessed an illegal memory location because I provided ample size for the encrpylis and val array.
By the way I am a newbie to C. Any suggestions are welcomed. Thank you already.

Body:
Main cause of segmentation fault is that you are trying to access the uninitialised memory location.

The string encryptlis was not initialised.

The return type of the function ceaserEncrypt is not correct.

Also, the conventions to pass string as parameter to the functions should be followed: The accepted convention of passing C-strings to functions is to use a pointer.

Have a look at the following working implementation:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* ceaserEncrypt(char* string,int key);

int main(int argc,char *argv[]){

    char str[100000] = "Hi there I am fine";
    int key = 20;
    char val[100000];

    strcpy(val,ceaserEncrypt(str,key));

    printf("%s",val);

    return 0;
}

char* ceaserEncrypt(char* string,int key)
{

    int len = strlen(string);
    char* encryptlis = (char*)(malloc((len+1) * sizeof(char)));

    if(key < 1 || key > 26)
    {
        fprintf(stderr,"Key provided is invalid");
        exit(-1);
    }

    for(int i = 0; i < len; i++)
    {
        if(string[i] == ' '){
            encryptlis[i] = ' ';
            continue;
        }

        int charcode = string[i] + key;
        if(charcode > 122)
        {
            encryptlis[i] = (char) (charcode - 25);
        }
        else{
            encryptlis[i] = (char) charcode;
        }
    }
    encryptlis[len] = '\0';

    return encryptlis;
}


问:
Aligning Clusters within Graphviz
I am using Graphviz to automatically create an architecture diagram.  I am having the following two problems and was hoping to get assistance.

I am using UUID to uniquely identify a component (example: "a5320de8-a320-11ea-bb37-0242ac130002" [label="Component A"]).  When mapping A -> B, I'll get "Component A" -> b0c5e47c.  Which is strange.  The only way that I've been able to map UUID to UUID is to put quotes around them. Any suggestions?

I want to align clusters in a specific manner and specific direction. I've tried {rank=same; cluster_B, cluster_C, cluster_D}; and "9653369c-a322-11ea-bb37-0242ac130002" -> "aa31adb9-9621-40c2-855c-621832dd8c61" [style=invis] But neither work.

I have three sections within my dot file, they are:

Components (within this section, I list out all 100+ components and color code them based on a specific rule.

Clusters (within this section, I cluster the components into specific 'groupings')

Diagram or mapping (within this section, I then map the different components and clusters).

Here is a sample of my DOT file.

```<code>digraph architecture {
    #graph [rankdir=LR]
    compound=true;

    #Compliant
    node[fillcolor="#013220" style="filled" shape=square fontcolor="white"];
        "a5320de8-a320-11ea-bb37-0242ac130002" [label="Component A"]
        "b0c5e47c-a320-11ea-bb37-0242ac130002" [label="Component B"]

     #Clusters
        #Customer-facing client application cluster
        subgraph cluster_A{
            label="Client Apps";

        "f7b3915d-6b3d-4d4c-bef0-bdabda915c03";
        "9912de2b-739a-4c5c-834e-e0c3d09d70d1";
        "16bb2066-9293-470e-99ec-c59d8426c0ab";
        "641a6601-f4f6-4c06-baa6-e5e232f8abed";
        "c5e92b09-a470-4fb6-af5c-e5f7dbeff919";
        }

     #Diagrams
     "f7b3915d-6b3d-4d4c-bef0-bdabda915c03" -> {"35305026-d285-458c-85ad-7eae4e785e84", "76e0e679-42a6-47f0-9164-abc223da07fe"};
      76e0e679-42a6-47f0-9164-abc223da07fe" -> "35305026-d285-458c-85ad-7eae4e785108";
}
</code>```

I get something like:

However, I want to arrange the cluster is a specific way, like:

答:
As you found out, hyphens are not legal characters in a node ID unless the string is quoted.  If you want more info:  https://www.graphviz.org/doc/info/lang.html

There is no straight-forward to align clusters.  Sometime you can force desired alignment by embedding multiple clusters within another cluster to "shrink-wrap" them.  For example embed B3 and B4 within cluster B34.  But no guarantees.

You can use gvpr to reposition clusters (and their contents) but that can get pretty complex.

Title: Aligning Clusters within Graphviz

Body:
I am using Graphviz to automatically create an architecture diagram.  I am having the following two problems and was hoping to get assistance.

I am using UUID to uniquely identify a component (example: "a5320de8-a320-11ea-bb37-0242ac130002" [label="Component A"]).  When mapping A -> B, I'll get "Component A" -> b0c5e47c.  Which is strange.  The only way that I've been able to map UUID to UUID is to put quotes around them. Any suggestions?

I want to align clusters in a specific manner and specific direction. I've tried {rank=same; cluster_B, cluster_C, cluster_D}; and "9653369c-a322-11ea-bb37-0242ac130002" -> "aa31adb9-9621-40c2-855c-621832dd8c61" [style=invis] But neither work.

I have three sections within my dot file, they are:

Components (within this section, I list out all 100+ components and color code them based on a specific rule.

Clusters (within this section, I cluster the components into specific 'groupings')

Diagram or mapping (within this section, I then map the different components and clusters).

Here is a sample of my DOT file.

digraph architecture {
    #graph [rankdir=LR]
    compound=true;

    #Compliant
    node[fillcolor="#013220" style="filled" shape=square fontcolor="white"];
        "a5320de8-a320-11ea-bb37-0242ac130002" [label="Component A"]
        "b0c5e47c-a320-11ea-bb37-0242ac130002" [label="Component B"]

     #Clusters
        #Customer-facing client application cluster
        subgraph cluster_A{
            label="Client Apps";

        "f7b3915d-6b3d-4d4c-bef0-bdabda915c03";
        "9912de2b-739a-4c5c-834e-e0c3d09d70d1";
        "16bb2066-9293-470e-99ec-c59d8426c0ab";
        "641a6601-f4f6-4c06-baa6-e5e232f8abed";
        "c5e92b09-a470-4fb6-af5c-e5f7dbeff919";
        }

     #Diagrams
     "f7b3915d-6b3d-4d4c-bef0-bdabda915c03" -> {"35305026-d285-458c-85ad-7eae4e785e84", "76e0e679-42a6-47f0-9164-abc223da07fe"};
      76e0e679-42a6-47f0-9164-abc223da07fe" -> "35305026-d285-458c-85ad-7eae4e785108";
}

I get something like:

However, I want to arrange the cluster is a specific way, like:


问:
A problem about IEEE 754 floating point operation
I want to ask an operation question about IEEE 754  floating-point:

(Take IEEE 754 single-precision floating-point number as an example : 1 sign bit, 8 exponent bits, 23 mantissa bit)

When calculating the addition and subtraction of two floating-point numbers, the mantissa with a small exponent should be aligned with the mantissa with a large exponent.

That is, it depends on the exponent difference between two floating-point numbers to see how much mantissa shifts

Here comes my problem : If the mantissa with the smaller exponent is beyond the range that mantissa can express after the shift.

Should we count the bits that exceed the range together, or do we have to discard them?

For example:
I want to calculate the subtraction of two floating point numbers

The first operand:
"0"(sign) 10010011(exponent) 0000 0000 0000 0000 1111 111(mantissa)

The second operand:
"1"(sign)   "10001110"(exponent) "0000 0000 0000 0111 1111 111"(mantissa)

The exponent of the first number is 147 in decimal, and the exponent of the second number is 142 in decimal, and 147-127 (bias) = 20,142-127 = 15

So in fact the above two numbers can become:

The first operand: 1.0000 0000 0000 0000 1111 111 * 2 ^ 20

The second operand: -1.0000 0000 0000 0111 1111 111 * 2 ^ 15

Because the second number is five less than the power of the first number, it needs to be shifted 5 bits to the right, Then my question is, it will become:

All bits are reserved, so a total of 28 bits are required to represent mantissa
-0.0000 1000 0000 0000 0011 111 "1 1111"(These five bits exceed 23bit) * (2 ^ 20)

Cut off directly after exceeding 23bit, so satisfying 23bit means mantissa
-0.0000 1000 0000 0000 0011 111 * (2 ^ 20)

Add three bits of round, guard, and sticky to consider, so use 25bit to represent mantissa.
-0.0000 1000 0000 0000 0011 111 11  =>the last two bits(bit 24 and bit 25) are guard bit and round bit,and set S = 1 (because the last three 1s are cut off)

Which one of the above options is right or none of them is right?

Body:
Where I was headed with my (deleted) comment was in the wrong direction.

Now while each implementation is subject to possible incorrect interpretation of the spec and bugs(and historically there have been lots of floating point implementation bugs, not just intel one time), we can or can try to examine one implementation.  (my computer)

Start with one operand 1.0

0x3F800000

001111111000...
0 01111111 000...
1.0000000 no shift

Then choose an operand that is going to have to have its mantissa shifted in order
to perform addition and subtraction.

0x3BFFFFFF

00111011111111
0 01110111 11111

That is going to shift right 8, so looking at some second operands

0x3BFFFFFF

  1.000000000000000...00 0000...
+ 0.000000011111111...11 1111...
==============================
  1.000000011111111...11

  1.000000000000000...00 0000...
- 0.000000011111111...11 1111...
==============================
  1.111111100000000...00

0x3BFFFF00

  1.000000000000000...00 0000...
+ 0.000000011111111...11 0000...
==============================
  1.000000011111111...11

  1.000000000000000...00 0000...
- 0.000000011111111...11 0000...
==============================
  1.111111100000000...10

0x3BFFFF80

  1.000000000000000...00 0000...
+ 0.000000011111111...11 1000...
==============================
  1.000000011111111...11

  1.000000000000000...00 0000...
- 0.000000011111111...11 1000...
==============================
  1.111111100000000...01

0x3BFFFFC0

  1.000000000000000...00 0000...
+ 0.000000011111111...11 1100...
==============================
  1.000000011111111...11

  1.000000000000000...00 0000...
- 0.000000011111111...11 1100...
==============================
  1.111111100000000...00

0x3BFFFF01

  1.000000000000000...00 00000000
+ 0.000000011111111...11 00000001
=================================
  1.000000011111111...11

  1.000000000000000...00 00000000
- 0.000000011111111...11 00000000
=================================
  1.111111100000000...00 00000001

For addition (without rounding) the base number the number not shifted needs to be padded (with zeros).  so two bits past the end of the size of the mantissa

0+0 = 0 carry 0
0+1 = 1 carry 0

you cannot have a carry in on the first bit past the mantissa (sticky bit). so for addition there is no reason for additional logic past that first bit, you need that first bit for rounding though. Only takes one bit to round.

Subtraction though you can look at it as a borrow or...

0x3BFFFF80

  1.000000000000000...00 0000...
- 0.000000011111111...11 1000...
==============================
  1.111111100000000...01

is really in logic

                                1
  1.000000000000000...00 00000000
+ 1.111111100000000...00 01111111
====================================
 10.111111100000000...00 10000000
hardware gives
  1.111111100000000...01

which I am still wrapping my head around because I chose both round to zero and round down, so it shouldnt have rounded up and/or how did that bit get there.

Anyway, I was on the wrong path, with subtraction, those bits do matter because
the carry in can now be non-zero going into that first bit past the mantissa edge
the first operands zero extension is still expected to be padded with zeros, but
for subtraction if you have a bunch of ones then add in the carry bit of one
you can push that carry all the way up to the edge of the mantissa.

Okay so I am either being affected by rounding or I have my boundary wrong (represented my second operand incorrectly)

0x3BFFFF80

  1.000000000000000...00 0000...
- 0.000000011111111...11 1000...
==============================
  1.111111100000000...01

0x3BFFFFC0

  1.000000000000000...00 0000...
- 0.000000011111111...11 1100...
==============================
  1.111111100000000...00

                                1
  1.000000000000000...00 00000000
+ ?.111111100000000...00 00111111
=================================

                          1111111
  1.000000000000000...00 00000000
+ ?.111111100000000...00 00111111
=================================
  1.111111100000000...00 01000000
hardware gives
  1.111111100000000...00

Either way bug in the demonstration or not because of borrowing during subtraction
off the end of the mantissa, that can affect both the rounding bit as well as the lsbit of the result (within the mantissa range before normalization).

So the answer is yes those bits have to be considered.  Basically see and vote for Eric's answer.

You should be able to demonstrate this on other not-grossly-broken implementations, including a software optimizer perhaps if you can get the conversion right from the high level language to the specific floating point value in binary.

But also when thinking about it on the addition side you cant get any carry outs
down there so you cant directly change bits in the fraction before normalization,
but of course the fraction from the smaller number directly affects/defines rounding.  Subtraction is the key here as it can affect both rounding and the carry bit into the pre-normalized fraction.

And as that answer comments, yes in logic there can be shortcuts to not have to have an adder that large, and also based on that answer, significant or fraction instead of mantissa, sorry...been using the old term since back when it wasnt the old term.


问:
How to query Wikipedia using SQL: Better description of Wiki schema? How can I query a page's contents?
I have been tasked with the following problem:
Using SQL, query Wikipedia and obtain the number of times the word 'nice' appears. Also, display the name of the article and the number of times per article this word 'nice' shows up.

I am having trouble actually accessing the contents of a Wikipedia page with SQL. I am using Quarry to play with queries, and I simply can't find where the contents of a page are stored. I am using this as a reference: https://www.mediawiki.org/w/index.php?title=Manual:Database_layout/diagram&action=render

I thought that a page's contents might be stored in the page table, or perhaps the content table. None of these fields and their datatypes make sense to me though (as far as saving the actual text contents of a page). Where is the actual content of an article stored? Can anyone provide a brief description of how this database actually represents a Wikipedia page?

答: A pages text is a little less straightforward. In MediaWiki each page (stored in the page table) can have multiple revisions (stored in the revision table), and each revision has its text in the text table. You will most likely want to do a join over these tables to connect the information.


问:
How to enable Developer Options by default in android source?
I want to enable Developer Options by default on android source?

Is it possible? Please let me know.

答:
The default depends on the Android build type.

For user or userdebug builds, you need to jump through the hoops of tapping the build number seven times.
For eng builds, Developer options are enabled by default.

As of Android Q, the codepath lies in frameworks/base/packages/SettingsLib/src/com/android/settingslib/development/DevelopmentSettingsEnabler.java.

final boolean settingEnabled = Settings.Global.getInt(
        context.getContentResolver(),
        Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
        /* Default if preference not yet set: */
        Build.TYPE.equals("eng") ? 1 : 0) != 0;
```

<p>You can change this to the following:</p>

<pre class="lang-java prettyprint-override"><code>final boolean settingEnabled = Settings.Global.getInt(
        context.getContentResolver(),
        Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
        1) != 0;
</code>```

...and development settings will be enabled by default, while still allowing you to toggle its enablement on and off in the UI.

For enabling (insecure) ADB connections without approving them beforehand to enable faster early-stage bringups, look into ro.adb.secure.

Body:
The default depends on the Android build type.

For user or userdebug builds, you need to jump through the hoops of tapping the build number seven times.
For eng builds, Developer options are enabled by default.

As of Android Q, the codepath lies in frameworks/base/packages/SettingsLib/src/com/android/settingslib/development/DevelopmentSettingsEnabler.java.

final boolean settingEnabled = Settings.Global.getInt(
        context.getContentResolver(),
        Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
        /* Default if preference not yet set: */
        Build.TYPE.equals("eng") ? 1 : 0) != 0;

You can change this to the following:

final boolean settingEnabled = Settings.Global.getInt(
        context.getContentResolver(),
        Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
        1) != 0;

...and development settings will be enabled by default, while still allowing you to toggle its enablement on and off in the UI.

For enabling (insecure) ADB connections without approving them beforehand to enable faster early-stage bringups, look into ro.adb.secure.


问:
Spring Data - Using property values in projections
I have Spring Data Rest Application where I created a projection like this

```<code>@Projection(name = "UserWithAvatar", types = { User.class })
public interface UserWithAvatar {
    String getName();
    String getEmail();

    @Value("${app.url}/pictures/#{target.imageId}")
    String getAvatar();
}

</code>```

The non working part is the getAvatar, it generates a url for seeing the picture.

However this ${app.url} is not working inside the projection.

How would I add this application.properties value in there?

答:
Use @environment.getProperty('app.url') inside #{} block. It works on Spring Boot 2.3.0, i'm not sure about older versions.

Example:

```<code>@Value("#{target.pictureUrl ?: @environment.getProperty('app.url') + 'static/default-avatar.png'}")
String getAvatarUrl();
</code>```

Body:
I have Spring Data Rest Application where I created a projection like this

@Projection(name = "UserWithAvatar", types = { User.class })
public interface UserWithAvatar {
    String getName();
    String getEmail();

    @Value("${app.url}/pictures/#{target.imageId}")
    String getAvatar();
}

The non working part is the getAvatar, it generates a url for seeing the picture.

However this ${app.url} is not working inside the projection.

How would I add this application.properties value in there?

Body:
Use @environment.getProperty('app.url') inside #{} block. It works on Spring Boot 2.3.0, i'm not sure about older versions.

Example:

@Value("#{target.pictureUrl ?: @environment.getProperty('app.url') + 'static/default-avatar.png'}")
String getAvatarUrl();


问:
Hide/Show components in react native
I'm really new to React Native and I'm wondering how can I hide/show a component.

Here's my test case:

```<code><TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>
</code>```

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.

Also, how can I hide the button from the very beginning?

答:
```<code>// You can use a state to control wether the component is showing or not
const [show, setShow] = useState(false); // By default won't show

// In return(
{
    show && <ComponentName />
}

/* Use this to toggle the state, this could be in a function in the
main javascript or could be triggered by an onPress */

show == true ? setShow(false) : setShow(true)

// Example:
const triggerComponent = () => {
    show == true ? setShow(false) : setShow(true)
}

// Or
<SomeComponent onPress={() => {show == true ? setShow(false) : setShow(true)}}/>

</code>```

Title: Hide/Show components in react native

Body:
I'm really new to React Native and I'm wondering how can I hide/show a component.

Here's my test case:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.

Also, how can I hide the button from the very beginning?


问:
Create Duplicate SQL Database for Testing
I have created a database on SQL server and a front end user application in winforms c#.
It's up and running and working fine, but I've now been asked to set up a test version by the client for training new employees, so they can put in dummy data whilst they are trained without effecting the 'real' live database.

When I installed the database I had it all scripted, but things have changed since, and I don't particularly want to script all the tables again.

Is there a fast, convenient way of duplicating the database (and its data) on the same server, but under a different name?

EDIT (subsequent to Tony Hopkinson post)

I've got as far as this

```<code>exec sp_addumpdevice 'Disk','MyDatabaseBackup',N'D:\MyDatabaseBackup'
Restore Database MyDatabase From MyDatabaseBackup With File = 1,
Move 'MyDatabase' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST.mdf',
Move 'MyDatabase_Log' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST_log.ldf',
NORECOVERY,  NOUNLOAD,  STATS = 10
RESTORE LOG [MyDatabaseTEST] FROM  [MyDatabaseBackup] WITH  FILE = 2,  NOUNLOAD,  STATS = 10
exec sp_dropdevice MyDatabaseBackup
</code>```

But I'm getting the following error message

Msg 3234, Level 16, State 2, Line 2
Logical file 'MyDatabase' is not part of database 'MyDatabase'. Use RESTORE FILELISTONLY to list the logical file names.
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.
Msg 3154, Level 16, State 4, Line 6
The backup set holds a backup of a database other than the existing 'MyDatabaseTEST' database.
Msg 3013, Level 16, State 1, Line 6
RESTORE LOG is terminating abnormally.
Device dropped.

答: If you need to create a database on the same server just create the empty database. Right Click on it and Select Restore-> Choose the database you want to make a copy of and click okay. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a database on SQL server and a front end user application in winforms c#.
It's up and running and working fine, but I've now been asked to set up a test version by the client for training new employees, so they can put in dummy data whilst they are trained without effecting the 'real' live database.

When I installed the database I had it all scripted, but things have changed since, and I don't particularly want to script all the tables again.

Is there a fast, convenient way of duplicating the database (and its data) on the same server, but under a different name?

EDIT (subsequent to Tony Hopkinson post)

I've got as far as this

exec sp_addumpdevice 'Disk','MyDatabaseBackup',N'D:\MyDatabaseBackup'
Restore Database MyDatabase From MyDatabaseBackup With File = 1,
Move 'MyDatabase' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST.mdf',
Move 'MyDatabase_Log' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST_log.ldf',
NORECOVERY,  NOUNLOAD,  STATS = 10
RESTORE LOG [MyDatabaseTEST] FROM  [MyDatabaseBackup] WITH  FILE = 2,  NOUNLOAD,  STATS = 10
exec sp_dropdevice MyDatabaseBackup

But I'm getting the following error message

Msg 3234, Level 16, State 2, Line 2
Logical file 'MyDatabase' is not part of database 'MyDatabase'. Use RESTORE FILELISTONLY to list the logical file names.
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.
Msg 3154, Level 16, State 4, Line 6
The backup set holds a backup of a database other than the existing 'MyDatabaseTEST' database.
Msg 3013, Level 16, State 1, Line 6
RESTORE LOG is terminating abnormally.
Device dropped.


问:
Should I leave the script tag empty if I use an external script file?
I mean, if I use JavaScript in an external file(write script code in another file, not in HTML file).

I write this code in my HTML file
But this code works only if I left the tags empty.

So I'm wondering that if we use JavaScript in an external way, should I leave the tag empty as I mentioned?

答:
Yes.
It's important to note that a script element using the src attribute should not include additional Javascript code between the  tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.

Reference

Note that html5 allows comments inside an external script tag.
Reference html5

Body:
Yes.
It's important to note that a script element using the src attribute should not include additional Javascript code between the <script> and </script> tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.

Reference

Note that html5 allows comments inside an external script tag.
Reference html5


问:
Extract String From String in PHP
I have string variable like ABC/DF/G I want extract DF from it means text between two /.
I have tried like below

```<code>$string= "ABC/DF/G";
$code = substr($string ,strpos($string,'/'));
echo $code;
</code>```

but I am getting result like below

```<code>/DF/G
</code>```

Let me know if someone can help me for do it.
Thanks!

答:
You can use explode function to split a string into an array.

```<code>$string= "ABC/DF/G";
$code = explode('/', $string);
echo $code[1];
</code>```

Title: Extract String From String in PHP

Body:
I have string variable like ABC/DF/G I want extract DF from it means text between two /.
I have tried like below

$string= "ABC/DF/G";
$code = substr($string ,strpos($string,'/'));
echo $code;

but I am getting result like below

/DF/G

Let me know if someone can help me for do it.
Thanks!

Body:
You can use explode function to split a string into an array.

$string= "ABC/DF/G";
$code = explode('/', $string);
echo $code[1];


问:
Which ORM syntax to join three tables in Django?
I have the following three Models (tables) in my Django project:

```<code>class Tool(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', unique=True, max_length=50)

class Flow(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    Toolid = models.ForeignKey(Tool, models.DO_NOTHING, db_column='ToolId')
    name = models.CharField(db_column='Name', unique=True, max_length=50)

class Task(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', max_length=50)
    FlowId = models.ForeignKey('Flow', models.DO_NOTHING, db_column='FlowId')
</code>```

I want to make ORM query that returns all info of Tool, Flow, and Task together that are related to each other (i.e. JOIN method in SQL queries). For example, I want to get something like this:

```<code>[
 { Tool name: ...
   Flow name: ...
   Task name: ...
 }
 { Tool name: ...
   Flow name: ...
   Task name: ...
 }
 ...
 ...
]
</code>```

Do you know what ORM sentence should I write to get that output?
I really want to get the result from all of the three tables (not only from two of them)!

It would be really appreciated if you provide me with the syntax related to my tables I provided above.

Thanks a lot!

答:
As Task has a foreign key for its Flow, which has a foreign key to Tool, you should be able to retrieve them all in one query like:

```<code>task_flow_tool_tuple_list = Task.objects.all().values_list('name', 'FlowId__name', 'FlowId__Toolid__name')
</code>```

You use the 'dunders' (double-underscores) to link from model to model, and finally to the attribute you want from the last model in the chain. So we are selecting all the Task objects, and for each we are returning a list of:

the Task name

the Task's FlowId's name

the Task's FlowId's Toolid's name

Hope that helps, happy coding!

Body:
I have the following three Models (tables) in my Django project:

class Tool(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', unique=True, max_length=50)

class Flow(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    Toolid = models.ForeignKey(Tool, models.DO_NOTHING, db_column='ToolId')
    name = models.CharField(db_column='Name', unique=True, max_length=50)

class Task(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', max_length=50)
    FlowId = models.ForeignKey('Flow', models.DO_NOTHING, db_column='FlowId')

I want to make ORM query that returns all info of Tool, Flow, and Task together that are related to each other (i.e. JOIN method in SQL queries). For example, I want to get something like this:

[
 { Tool name: ...
   Flow name: ...
   Task name: ...
 }
 { Tool name: ...
   Flow name: ...
   Task name: ...
 }
 ...
 ...
]

Do you know what ORM sentence should I write to get that output?
I really want to get the result from all of the three tables (not only from two of them)!

It would be really appreciated if you provide me with the syntax related to my tables I provided above.

Thanks a lot!

Body:
As Task has a foreign key for its Flow, which has a foreign key to Tool, you should be able to retrieve them all in one query like:

task_flow_tool_tuple_list = Task.objects.all().values_list('name', 'FlowId__name', 'FlowId__Toolid__name')

You use the 'dunders' (double-underscores) to link from model to model, and finally to the attribute you want from the last model in the chain. So we are selecting all the Task objects, and for each we are returning a list of:

the Task name

the Task's FlowId's name

the Task's FlowId's Toolid's name

Hope that helps, happy coding!


问:
How to order by "Month" using a column that has "Date format" in my sql?
I have a table that has a session name and session date, ex:

```<code>Name: Football game, date: 2020-05-31.
</code>```

Is there a way to display these results in a group by date as in months?? ex:

Date X

1  (month 1) ...

2  (month 2)  ...

...

```<code>SELECT Date(?) , count(*) nb from Session group by Date(?)
</code>```

答:
Please use below query,</p>

```<code>SELECT month(Date) , count(*) nb from Session group by month(Date);
</code>```

Body:
I have a table that has a session name and session date, ex:

Name: Football game, date: 2020-05-31.

Is there a way to display these results in a group by date as in months?? ex:

Date X

1  (month 1) ...

2  (month 2)  ...

...

SELECT Date(?) , count(*) nb from Session group by Date(?)

Body:
Please use below query,

SELECT month(Date) , count(*) nb from Session group by month(Date);


问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答:
```<code>for (statement1; statement2; statement3)
{
     /* body */
}
</code>```

(1) First the statement1 is executed.

(2) Next statement2 is executed.

(3) If the evaluation of statement2 is true then the body is executed

(4) Then statement3 is executed.

(5) Repeat from step (2)

```<code>          |                  +<-----------------+
          |                  |                  ^
          V                  V                  |
 for (  (s1); -------->(s2 true? | false?);    (s3) )
 {                           |       |          ^
                             |       |          |
                             |       |          |
                             V       |          |
                          (body)-----|--------->+
 }                                   |
                                     |
                                     V
                                 (come out)
</code>```

The structure you have shown is the same normal structure as above. The statement n could be any statement. In your example, you have separated by comma operators in statement1 and statement3. You can separate any number of statements by comma operators.

Generally for loops are used with the statement1 with initialization as it is executed only once. The statement2 is used for the loop termination condition checking, because the evaluation value of this statement is used to decide if to enter the body of break out. And the statement3 is used for update of the loop termination variable as it is executed after the body. But generally they could be used in any way.

First statement1 is i=10, j=0; this initializes the variables. Next in the statement2 is j <= 10 if this is true then the body is executed. After the body is executed, statement3 which is i--,j++ is executed. The loop will iterate 11 times 0 to 10. But will print 5 times, as at one point i and j will become same and the if (i > j) will evaluate false.

EDIT
Here is an example where it might be used, not much practical but a sample use, to check for a palindrome string.

```<code>  int i, j, n, flag;
  char str[128];

  printf ("\nEnter string: ");
  scanf ("%s", &str);
  n = strlen (str);

for (flag=1, i=n-1, j=0; j<n/2; j++, i--)
{
  if (str[i] != str[j])
  {
    flag = 0;
    break;
  }
}

if (flag)
 printf ("\n\"%s\" is a palindrome");
else
 printf ("\n\"%s\" is not a palindrome");
</code>```

We should always try to write code which is easy to read and which does not create confusion. This helps the code writer as well as others who read the code.

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

Body:
for (statement1; statement2; statement3)
{
     /* body */
}

(1) First the statement1 is executed.

(2) Next statement2 is executed.

(3) If the evaluation of statement2 is true then the body is executed

(4) Then statement3 is executed.

(5) Repeat from step (2)

          |                  +<-----------------+
          |                  |                  ^
          V                  V                  |
 for (  (s1); -------->(s2 true? | false?);    (s3) )
 {                           |       |          ^
                             |       |          |
                             |       |          |
                             V       |          |
                          (body)-----|--------->+
 }                                   |
                                     |
                                     V
                                 (come out)

The structure you have shown is the same normal structure as above. The statement n could be any statement. In your example, you have separated by comma operators in statement1 and statement3. You can separate any number of statements by comma operators.

Generally for loops are used with the statement1 with initialization as it is executed only once. The statement2 is used for the loop termination condition checking, because the evaluation value of this statement is used to decide if to enter the body of break out. And the statement3 is used for update of the loop termination variable as it is executed after the body. But generally they could be used in any way.

First statement1 is i=10, j=0; this initializes the variables. Next in the statement2 is j <= 10 if this is true then the body is executed. After the body is executed, statement3 which is i--,j++ is executed. The loop will iterate 11 times 0 to 10. But will print 5 times, as at one point i and j will become same and the if (i > j) will evaluate false.

EDIT
Here is an example where it might be used, not much practical but a sample use, to check for a palindrome string.

  int i, j, n, flag;
  char str[128];

  printf ("\nEnter string: ");
  scanf ("%s", &str);
  n = strlen (str);

for (flag=1, i=n-1, j=0; j<n/2; j++, i--)
{
  if (str[i] != str[j])
  {
    flag = 0;
    break;
  }
}

if (flag)
 printf ("\n\"%s\" is a palindrome");
else
 printf ("\n\"%s\" is not a palindrome");

We should always try to write code which is easy to read and which does not create confusion. This helps the code writer as well as others who read the code.


问:
what is the type of a pointer to dynamically allocated memory of pointers of type char?
I am new to C. I need to allocate memory and store pointers in it. These pointers are of type char. So what is the type of the pointer to that memory? char? or long because addresses are just numbers?</p>

答:
The type is char**, pointer to pointer to char, aka double pointer to char.

Note that you wouldn't need to manually allocate space for the pointers if you don't want to.

Take the code:

```<code>#define POINTER_N 10
//...
char *ptr[POINTER_N]; //array of 10 pointers to char
</code>```

This already reserves space for these 10 pointers, their size is the size of a pointer to char, this size deppends on your system, for a 64 bit system the pointers are 8 bytes, for a 32 bit one it's 4 bytes, this is generic, there can be differences in these values depending on the implementation.

Already having the pointer you only will then need to allocate space for the strings themselves, so for 20 char strings initialized to \0 you would do:

```<code>#include <stdlib.h>
#define STRING_SIZE 21
//...
for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof *ptr[0]); //21 char long string
</code>```

This would suffice, note that I'm reserving one extra character for the null terminator.

If you really want to allocate the space for these pointers yourself you would declare a double pointer, and allocate space for the numbers of pointers to char you need:

```<code>char **ptr = calloc(POINTER_N, sizeof *ptr); // 10 pointers to pointers to char
</code>```

And for the strings:

```<code>for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof **ptr);
</code>```

Body:
The type is char**, pointer to pointer to char, aka double pointer to char.

Note that you wouldn't need to manually allocate space for the pointers if you don't want to.

Take the code:

#define POINTER_N 10
//...
char *ptr[POINTER_N]; //array of 10 pointers to char

This already reserves space for these 10 pointers, their size is the size of a pointer to char, this size deppends on your system, for a 64 bit system the pointers are 8 bytes, for a 32 bit one it's 4 bytes, this is generic, there can be differences in these values depending on the implementation.

Already having the pointer you only will then need to allocate space for the strings themselves, so for 20 char strings initialized to \0 you would do:

#include <stdlib.h>
#define STRING_SIZE 21
//...
for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof *ptr[0]); //21 char long string

This would suffice, note that I'm reserving one extra character for the null terminator.

If you really want to allocate the space for these pointers yourself you would declare a double pointer, and allocate space for the numbers of pointers to char you need:

char **ptr = calloc(POINTER_N, sizeof *ptr); // 10 pointers to pointers to char

And for the strings:

for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof **ptr);


问:
Overriding methods from a derived class
I have the following coding:-

Progam 1

```<code>class Person :

    '''A base to define Person properties.'''

    def __inti__( self , name ):
        self.name = name

    def speak( self , msg = '(Calling The Base Class)' ):
        print( self.name , msg )
</code>```

Program 2

```<code>from Person import *
'''A derived class to define Man properties.'''

class Man( Person ):
        def speak( self , msg ):
                print( self.name , ':\n\tHello!' , msg )
</code>```

Program 3

```<code>from Person import *
'''A derived class to define Hombre properties.'''

class Hombre( Person ):
        def speak( self , msg ):
                print( self.name , ':\n\tHola!' , msg )
</code>```

Program 4

```<code>from Man import *
from Hombre import *

guy__1 = Man('Richard')
guy__2 = Hombre('Ricardo')
guy__1.speak( 'It\'s a beautiful evening.\n' )
guy__2.speak( 'Es una tarde hermosa.\n' )
Person.speak( guy__1 )
Person.speak( guy__2 )
</code>```

I get the following error;-
guy__1 = Man('Richard')
TypeError: object() takes no parameters

答:
change </p>

```<code>def __inti__( self , name ):
</code>```

<p>to </p>

```<code>def __init__( self , name ):
</code>```

Title: Overriding methods from a derived class

Body:
I have the following coding:-

Progam 1

class Person :

    '''A base to define Person properties.'''

    def __inti__( self , name ):
        self.name = name

    def speak( self , msg = '(Calling The Base Class)' ):
        print( self.name , msg )

Program 2

from Person import *
'''A derived class to define Man properties.'''

class Man( Person ):
        def speak( self , msg ):
                print( self.name , ':\n\tHello!' , msg )

Program 3

from Person import *
'''A derived class to define Hombre properties.'''

class Hombre( Person ):
        def speak( self , msg ):
                print( self.name , ':\n\tHola!' , msg )

Program 4

from Man import *
from Hombre import *

guy__1 = Man('Richard')
guy__2 = Hombre('Ricardo')
guy__1.speak( 'It\'s a beautiful evening.\n' )
guy__2.speak( 'Es una tarde hermosa.\n' )
Person.speak( guy__1 )
Person.speak( guy__2 )

I get the following error;-
guy__1 = Man('Richard')
TypeError: object() takes no parameters

Body:
change

def __inti__( self , name ):

to

def __init__( self , name ):


问:
How to add Document with Custom ID to Firebase (Firestore) on Swift
Is there any way to add a document to firestore collection with custom id on Swift Language, not the id generated by firestore engine.

Thanks in advance for your responses.

答:
2020

Usually you'd want the error handling:

```<code>Firestore.firestore()
    .collection("companyAddress")
    .document(companyID)
    .setData([
        "address1": a1,
        "address2": a2,
        "city": c
    ]) { [weak self] err in
        guard let self = self else { return }
        if let err = err {
            print("err ... \(err)")
            self.yourErrorAlert()
        }
        else {
            print("saved ok")
            self.proceedWithUX()
        }
}
</code>```

Body:
2020

Usually you'd want the error handling:

Firestore.firestore()
    .collection("companyAddress")
    .document(companyID)
    .setData([
        "address1": a1,
        "address2": a2,
        "city": c
    ]) { [weak self] err in
        guard let self = self else { return }
        if let err = err {
            print("err ... \(err)")
            self.yourErrorAlert()
        }
        else {
            print("saved ok")
            self.proceedWithUX()
        }
}


问:
Why is looking for an item in a hash map faster than looking for an item in an array?
You might have come across someplace where it is mentioned that it is faster to find elements in hashmap/dictionary/table than list/array. My question is WHY?

(inference so far I made: Why should it be faster, as far I see, in both data structure, it has to travel throughout till it reaches the required element)

答:
To understand this you can think of how the elements are stored in these Data structures.

HashMap/Dictionary as you know it is a key-value data structure. To store the element, you first find the Hash value (A function which always gives a unique value to a key. For example, a simple hash function can be made by doing the modulo operation.). Then you basically put the value against this hashed key.

In List, you basically keep appending the element to the end. The order of the element insertion would matter in this data structure. The memory allocated to this data structure is not contiguous.

In Array, you can think of it as similar to List. But In this case, the memory allocated is contiguous in nature. So, if you know the value of the address for the first index, you can find the address of the nth element.

Now think of the retrieval of the element from these Data structures:

From HashMap/Dictionary: When you are searching for an element, the first thing that you would do is find the hash value for the key. Once you have that, you go to the map for the hashed value and obtain the value. In this approach, the amount of action performed is always constant. In Asymptotic notation, this can be called as O(1).

From List: You literally need to iterate through each element and check if the element is the one that you are looking for. In the worst case, your desired element might be present at the end of the list. So, the amount of action performed varies, and in the worst case, you might have to iterate the whole list. In Asymptotic notation, this can be called as O(n). where n is the number of elements in the list.

From array: To find the element in the array, what you need to know is the address value of the first element. For any other element, you can do the Math of how relative this element is present from the first index.

For example, Let's say the address value of the first element is 100. Each element takes 4 bytes of memory. The element that you are looking for is present at 3rd position. Then you know the address value for this element would be 108. Math used is

Addresses of first element + (position of element -1 )* memory used for each element.

That is 100 + (3 - 1)*4 = 108.

In this case also as you can observe the action performed is always constant to find an element. In Asymptotic notation, this can be called as O(1).

Now to compare, O(1) will always be faster than O(n). And hence retrieval of elements from HashMap/Dictionary or array would always be faster than List.

I hope this helps.


问:
Spring Boot Redis store a list of POJOs as values
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

```<code>@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}
</code>```

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

```<code>1) "schools::ABC"
</code>```

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.

答:
The reason why you are seeing those strange characters is because it is binary data.

You configured the GenericJackson2JsonRedisSerializer as the serializer for the values. This class internally calls ObjectMapper#writeValueAsBytes(...) which as the name suggest converts the value you put in to bytes.

This is to be expected. Redis does not directly support storing Java objects. It however does support storing binary data. By using Jackson we can convert our Java object to bytes and store that in Redis. Of course the other way around also works.

Body:
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

1) "schools::ABC"

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.


问:
Get name of current script in Python
I'm trying to get the name of the Python script that is currently running.

I have a script called foo.py and I'd like to do something like this in order to get the script name:

print(Scriptname)
```

答:
all that answers are great, but have some problems You might not see at the first glance.

lets define what we want - we want the name of the script that was executed, not the name of the current module - so __file__ will only work if it is used in the executed script, not in an imported module.
sys.argv is also questionable - what if your program was called by pytest ? or pydoc runner ? or if it was called by uwsgi ?

and - there is a third method of getting the script name, I havent seen in the answers - You can inspect the stack.

Another problem is, that You (or some other program) can tamper around with sys.argv and __main__.__file__ - it might be present, it might be not. It might be valid, or not. At least You can check if the script (the desired result) exists !

the library lib_programname does exactly that :

check if __main__ is present

check if __main__.__file__ is present

does give __main__.__file__ a valid result (does that script exist ?)

if not: check sys.argv:

is there pytest, docrunner, etc in the sys.argv ? --> if yes, ignore that

can we get a valid result here ?

if not: inspect the stack and get the result from there possibly

if also the stack does not give a valid result, then throw an Exception.

by that way, my solution is working so far with setup.py test, uwsgi, pytest, pycharm pytest , pycharm docrunner (doctest), dreampie, eclipse

there is also a nice blog article about that problem from Dough Hellman, "Determining the Name of a Process from Python"

BTW, it will change again in python 3.9 : the file attribute of the main module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed by os.chdir()

So I rather want to take care of one small module, instead of skimming my codebase if it should be changed somewere ...

Disclaimer: I'm the author of the lib_programname library.

Title: Get name of current script in Python


问:
Unable to execute Snowflake PUT Command through Java
We are trying to load JSON files using Java from a file location to Snowflake Named Stage. Currently, the PUT command only works for ODBC and not JDBC. So is there any way to execute PUT command using Java code?

Thanks

答:
The Snowflake JDBC Driver does support use of PUT statements for local file uploads. The following java statement is considered a valid query and the file is uploaded:

statement.executeQuery("PUT file:///tmp/foo.json @JSONSTAGE/ overwrite=true");
```

<p>Running it under a logger produces logs such as the following (logs here are from JDBC driver version <code>v3.12.2</code>):</p>

```n.s.c.jdbc.SnowflakeFileTransferAgent$1 FINE call:778 - filePath: /tmp/foo.json
n.s.c.jdbc.SnowflakeFileTransferAgent FINE uploadFiles:1751 - Done with uploading
```

The JDBC driver also supports a more efficient way of uploading a stream directly, documented here.

Body:
The Snowflake JDBC Driver does support use of PUT statements for local file uploads. The following java statement is considered a valid query and the file is uploaded:

statement.executeQuery("PUT file:///tmp/foo.json @JSONSTAGE/ overwrite=true");

Running it under a logger produces logs such as the following (logs here are from JDBC driver version v3.12.2):

n.s.c.jdbc.SnowflakeFileTransferAgent$1 FINE call:778 - filePath: /tmp/foo.json
n.s.c.jdbc.SnowflakeFileTransferAgent FINE uploadFiles:1751 - Done with uploading

The JDBC driver also supports a more efficient way of uploading a stream directly, documented here.


问:
Unnecessary LEFT JOINs on all Child tables from main LEFT JOIN table required in query for correct result
I am LEFT JOIN-ing the table RECALLS_T with EVENTS_T. Some Recalls do not have any Events, and for those I want a blank row returned.

However, once an entry in EVENTS_T exists, all the following extra tables from EVENTS_T which I also need (ANSWERS_T, ACTIVITY_QUESTIONS_T, ACTIVITES_T) are guaranteed to have entries. For these subsequent tables there is no need to do a LEFT JOIN from their parent, it can be an INNER JOIN just as well.

But if I do the following, the query does not return blank EVENTS_T rows for a RECALLS_T.

```<code>SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )     --Only LEFT JOIN this main table
   INNER JOIN answers_t ans ON (ans.event_id = e.id)
   INNER JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   INNER JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
</code>```

Instead, I need to change every subsequent INNER JOIN to a LEFT JOIN as well, in order to get Recalls with blank Events.

```<code>SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )
   LEFT JOIN answers_t ans ON (ans.event_id = e.id)
   LEFT JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   LEFT JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
</code>```

I'm just not clear on why I have to do this. The top-level optional join is all I care about, but the downstream joins from EVENTS_T are guaranteed to have data provided the Event exists. Shouldn't the top-level single EVENTS_T join be enough? I'm using Postgres.

答:
You have to do this because answers_t`` is joining onevents_s.  If thejoinkey (e.recall_id) isNULL`, then there will be no match.  And the inner join will not return the row.  And so on for the other tables.

You seem to understand the fix.  Once you use left join, you need to continue using left join for those tables that are connected to the second table of the left join.

Body:
I am LEFT JOIN-ing the table RECALLS_T with EVENTS_T. Some Recalls do not have any Events, and for those I want a blank row returned.

However, once an entry in EVENTS_T exists, all the following extra tables from EVENTS_T which I also need (ANSWERS_T, ACTIVITY_QUESTIONS_T, ACTIVITES_T) are guaranteed to have entries. For these subsequent tables there is no need to do a LEFT JOIN from their parent, it can be an INNER JOIN just as well.

But if I do the following, the query does not return blank EVENTS_T rows for a RECALLS_T.

SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )     --Only LEFT JOIN this main table
   INNER JOIN answers_t ans ON (ans.event_id = e.id)
   INNER JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   INNER JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)

Instead, I need to change every subsequent INNER JOIN to a LEFT JOIN as well, in order to get Recalls with blank Events.

SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )
   LEFT JOIN answers_t ans ON (ans.event_id = e.id)
   LEFT JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   LEFT JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)

I'm just not clear on why I have to do this. The top-level optional join is all I care about, but the downstream joins from EVENTS_T are guaranteed to have data provided the Event exists. Shouldn't the top-level single EVENTS_T join be enough? I'm using Postgres.


问:
AES Encryption : Encrypt using Arduino and decrypt using Java
I want to encrypt a text using Arduino and decrypt it using Java. I tried this code from this link but without success.

I am using this Arduino library for encryption on the Arduino and the Java Cryptographic Extension (JCE) framework for the Java side.

This the Arduino code:

```<code>#include <AESLib.h>  //replace the ( with < to compile (forum posting issue)
#include <Base64.h>

void setup() {
  Serial.begin(9600);
  uint8_t key[] = {50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50};
  //expressed in 16 unsigned in characters, be careful not to typecast this as a char in a decrypter
  //16- 50's (uint8) is the way to express 16 2's in ASCII, the encryption matches to what will show up on <a href="http://aesencryption.net/" target="_blank" rel="nofollow">http://aesencryption.net/</a>
  char data[] = "0123456789012345";
  //The message to encrypt, 16 chars == 16 bytes, no padding needed as frame is 16 bytes
  char encryptedData[100];
  int *size;
  Serial.print("Message:");
  Serial.println(data);
  aes128_enc_single(key, data);
  Serial.print("encrypted:");
  Serial.println(data);
  int inputLen = sizeof(data);
  int encodedLen = base64_enc_len(inputLen);
  char encoded[encodedLen];
  base64_encode(encoded, data, inputLen);
  Serial.print("encrypted(base64):"); //used
  Serial.println(encoded);
  Serial.println("***********Decrypter************");
  int input2Len = sizeof(encoded);
  int decodedLen = base64_dec_len(encoded, input2Len);
  char decoded[decodedLen];
  base64_decode(decoded, encoded, input2Len);
  Serial.print("encrypted (returned from Base64):");
  Serial.println(decoded);
  Serial.print("decrypted:");
  Serial.println(decoded);
}

void loop() {
}
</code>```

This is the Java code:

```<code>package main;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class ForTest {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        String message= "0123456789012345";//Message to encode
        String key = "2222222222222222";
        // 128 bit key  -this key is processed as ASCII values
        System.out.println("Processing 3.0 AES-128 ECB Encryption/Decryption Example");
        System.out.println("++++++++++++++++++++++++++++++++");
        System.out.println("Original Message: " + message);
        System.out.println("Key: " + key);
        System.out.println("key in bytes: "+key.getBytes("UTF-8"));
        System.out.println("==========================");
        //Encrypter
        SecretKeySpec skeySpec_encode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_encode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_encode = Cipher.getInstance("AES/ECB/PKCS5PADDING"); //AES-CBC with IV encoding, ECB is used without the IV, example shown on <a href="http://aesencryption.net/" target="_blank" rel="nofollow">http://aesencryption.net/</a>
        cipher_encode.init(Cipher.ENCRYPT_MODE, skeySpec_encode);
        byte[] encrypted = cipher_encode.doFinal(message.getBytes());
        System.out.println("Encrypted String (base 64): "
                + DatatypeConverter.printBase64Binary(encrypted));
        //encode without padding: Base64.getEncoder().withoutPadding().encodeToString(encrypted));
        //encode with padding:  Base64.getEncoder().encodeToString(encrypted));
        String base64_encrypted = DatatypeConverter.printBase64Binary(encrypted);
        //Decrypter
        SecretKeySpec skeySpec_decode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_decode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_decode = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher_decode.init(Cipher.DECRYPT_MODE, skeySpec_decode);
        System.out.println("length: "+"Ouril+UTDF8htLzE".length());
        byte[] decrypted_original = cipher_decode.doFinal(DatatypeConverter.parseBase64Binary("Ouril+UTDF8htLzEhiRj7wA="));
        String decrypt_originalString = new String(decrypted_original);
        System.out.println("Decrypted String: " + decrypt_originalString);
    }
}
</code>```

In Java when I try to decrypt the encoded String by Arduino I get this:

```<code>Processing 3.0 AES-128 ECB Encryption/Decryption Example
++++++++++++++++++++++++++++++++
Original Message: 0123456789012345
Key: 2222222222222222
key in bytes: [B@2a139a55
==========================
Encrypted String (base 64): Ouril+UTDF8htLzEhiRj7w==
length: 16
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1016)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at main.ForTest.main(ForTest.java:46)
</code>```

Any ideas?
Thanks!

答:
I was able to get this working after like a week - working Arduino documentation on integration with other systems is crap : )

Working Arduino code:

```<code>#include "mbedtls/aes.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <base64.h>

void makeUpdateAPICall()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http;

    // Your Domain name with URL path or IP address with path
    http.begin(serverName);

    // Specify content-type header
    http.addHeader("Content-Type", "text/plain");
    http.addHeader("Authorization", "Bearer XXXXXXXX [whatever your web token is]");
    http.addHeader("X-Content-Type-Options", "nosniff");
    http.addHeader("X-XSS-Protection", "1; mode=block");

    //AES Encrypt
    esp_aes_context aesOutgoing;
    unsigned char key[32] = "1234567812345678123456781234567" ;
    key[31] = '8';   // we replace the 32th (index 31) which contains '/0' with the '8' char.

    char *input = "Tech tutorials x";
    unsigned char encryptOutput[16];

    mbedtls_aes_init(&aesOutgoing);
    mbedtls_aes_setkey_enc(&aesOutgoing, key, 256);
    int encryptAttempt = mbedtls_aes_crypt_ecb(&aesOutgoing, MBEDTLS_AES_ENCRYPT, (const unsigned char *)input, encryptOutput);
    USE_SERIAL.println();
    USE_SERIAL.println("MBEDTLS_AES_EBC encryption result:\t ");
    USE_SERIAL.print(encryptAttempt); //0 means that the encrypt/decrypt function was successful
    USE_SERIAL.println();
    mbedtls_aes_free(&aesOutgoing);

    int encryptSize = sizeof(encryptOutput) / sizeof(const unsigned char);
    USE_SERIAL.println("Size of AES encrypted output: ");
    USE_SERIAL.println(encryptSize);

    //Base 64 Encrypt
    int inputStringLength = sizeof(encryptOutput);
    int encodedLength = Base64.decodedLength((char *)encryptOutput, inputStringLength);
    char encodedCharArray[encodedLength];
    Base64.encode(encodedCharArray, (char *)encryptOutput, inputStringLength);
    //Send to server
    USE_SERIAL.print("Sending to server.");
    int httpResponseCode = http.POST(encodedCharArray);

    String payload = "{}";

    if (httpResponseCode > 0)
    {
      //Retrieve server response
      payload = http.getString();
    }
    // Free resources
    http.end();
  }
  WiFi.disconnect();
}
</code>```

Working Java code:

```public static String decrypt(String strToDecrypt, String key) {</p>

```    byte[] encryptionKeyBytes = key.getBytes();
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/ECB/NoPadding");
        SecretKey secretKey = new SecretKeySpec(encryptionKeyBytes, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt.getBytes("UTF-8"))));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
```

<p>Working on the return process now. </p>

<p>You call the Java side with this code:</p>

<code>final String decryptedText = AES.decrypt(encryptedStr, "12345678123456781234567812345678");
System.out.println("Decrypted AES ECB String: ");
System.out.println(decryptedText);
</code>```

Wanted to provide this for any poor slob who finds him/herself in the same boat : )

Hope this helps!

Body:
I want to encrypt a text using Arduino and decrypt it using Java. I tried this code from this link but without success.

I am using this Arduino library for encryption on the Arduino and the Java Cryptographic Extension (JCE) framework for the Java side.

This the Arduino code:

#include <AESLib.h>  //replace the ( with < to compile (forum posting issue)
#include <Base64.h>

void setup() {
  Serial.begin(9600);
  uint8_t key[] = {50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50};
  //expressed in 16 unsigned in characters, be careful not to typecast this as a char in a decrypter
  //16- 50's (uint8) is the way to express 16 2's in ASCII, the encryption matches to what will show up on http://aesencryption.net/
  char data[] = "0123456789012345";
  //The message to encrypt, 16 chars == 16 bytes, no padding needed as frame is 16 bytes
  char encryptedData[100];
  int *size;
  Serial.print("Message:");
  Serial.println(data);
  aes128_enc_single(key, data);
  Serial.print("encrypted:");
  Serial.println(data);
  int inputLen = sizeof(data);
  int encodedLen = base64_enc_len(inputLen);
  char encoded[encodedLen];
  base64_encode(encoded, data, inputLen);
  Serial.print("encrypted(base64):"); //used
  Serial.println(encoded);
  Serial.println("***********Decrypter************");
  int input2Len = sizeof(encoded);
  int decodedLen = base64_dec_len(encoded, input2Len);
  char decoded[decodedLen];
  base64_decode(decoded, encoded, input2Len);
  Serial.print("encrypted (returned from Base64):");
  Serial.println(decoded);
  Serial.print("decrypted:");
  Serial.println(decoded);
}

void loop() {
}

This is the Java code:

package main;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class ForTest {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        String message= "0123456789012345";//Message to encode
        String key = "2222222222222222";
        // 128 bit key  -this key is processed as ASCII values
        System.out.println("Processing 3.0 AES-128 ECB Encryption/Decryption Example");
        System.out.println("++++++++++++++++++++++++++++++++");
        System.out.println("Original Message: " + message);
        System.out.println("Key: " + key);
        System.out.println("key in bytes: "+key.getBytes("UTF-8"));
        System.out.println("==========================");
        //Encrypter
        SecretKeySpec skeySpec_encode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_encode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_encode = Cipher.getInstance("AES/ECB/PKCS5PADDING"); //AES-CBC with IV encoding, ECB is used without the IV, example shown on http://aesencryption.net/
        cipher_encode.init(Cipher.ENCRYPT_MODE, skeySpec_encode);
        byte[] encrypted = cipher_encode.doFinal(message.getBytes());
        System.out.println("Encrypted String (base 64): "
                + DatatypeConverter.printBase64Binary(encrypted));
        //encode without padding: Base64.getEncoder().withoutPadding().encodeToString(encrypted));
        //encode with padding:  Base64.getEncoder().encodeToString(encrypted));
        String base64_encrypted = DatatypeConverter.printBase64Binary(encrypted);
        //Decrypter
        SecretKeySpec skeySpec_decode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_decode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_decode = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher_decode.init(Cipher.DECRYPT_MODE, skeySpec_decode);
        System.out.println("length: "+"Ouril+UTDF8htLzE".length());
        byte[] decrypted_original = cipher_decode.doFinal(DatatypeConverter.parseBase64Binary("Ouril+UTDF8htLzEhiRj7wA="));
        String decrypt_originalString = new String(decrypted_original);
        System.out.println("Decrypted String: " + decrypt_originalString);
    }
}

In Java when I try to decrypt the encoded String by Arduino I get this:

Processing 3.0 AES-128 ECB Encryption/Decryption Example
++++++++++++++++++++++++++++++++
Original Message: 0123456789012345
Key: 2222222222222222
key in bytes: [B@2a139a55
==========================
Encrypted String (base 64): Ouril+UTDF8htLzEhiRj7w==
length: 16
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1016)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at main.ForTest.main(ForTest.java:46)

Any ideas?
Thanks!

Body:
I was able to get this working after like a week - working Arduino documentation on integration with other systems is crap : )

Working Arduino code:

#include "mbedtls/aes.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <base64.h>

void makeUpdateAPICall()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http;

    // Your Domain name with URL path or IP address with path
    http.begin(serverName);

    // Specify content-type header
    http.addHeader("Content-Type", "text/plain");
    http.addHeader("Authorization", "Bearer XXXXXXXX [whatever your web token is]");
    http.addHeader("X-Content-Type-Options", "nosniff");
    http.addHeader("X-XSS-Protection", "1; mode=block");

    //AES Encrypt
    esp_aes_context aesOutgoing;
    unsigned char key[32] = "1234567812345678123456781234567" ;
    key[31] = '8';   // we replace the 32th (index 31) which contains '/0' with the '8' char.

    char *input = "Tech tutorials x";
    unsigned char encryptOutput[16];

    mbedtls_aes_init(&aesOutgoing);
    mbedtls_aes_setkey_enc(&aesOutgoing, key, 256);
    int encryptAttempt = mbedtls_aes_crypt_ecb(&aesOutgoing, MBEDTLS_AES_ENCRYPT, (const unsigned char *)input, encryptOutput);
    USE_SERIAL.println();
    USE_SERIAL.println("MBEDTLS_AES_EBC encryption result:\t ");
    USE_SERIAL.print(encryptAttempt); //0 means that the encrypt/decrypt function was successful
    USE_SERIAL.println();
    mbedtls_aes_free(&aesOutgoing);

    int encryptSize = sizeof(encryptOutput) / sizeof(const unsigned char);
    USE_SERIAL.println("Size of AES encrypted output: ");
    USE_SERIAL.println(encryptSize);

    //Base 64 Encrypt
    int inputStringLength = sizeof(encryptOutput);
    int encodedLength = Base64.decodedLength((char *)encryptOutput, inputStringLength);
    char encodedCharArray[encodedLength];
    Base64.encode(encodedCharArray, (char *)encryptOutput, inputStringLength);
    //Send to server
    USE_SERIAL.print("Sending to server.");
    int httpResponseCode = http.POST(encodedCharArray);

    String payload = "{}";

    if (httpResponseCode > 0)
    {
      //Retrieve server response
      payload = http.getString();
    }
    // Free resources
    http.end();
  }
  WiFi.disconnect();
}

Working Java code:

public static String decrypt(String strToDecrypt, String key) {

    byte[] encryptionKeyBytes = key.getBytes();
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/ECB/NoPadding");
        SecretKey secretKey = new SecretKeySpec(encryptionKeyBytes, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt.getBytes("UTF-8"))));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

Working on the return process now.

You call the Java side with this code:

final String decryptedText = AES.decrypt(encryptedStr, "12345678123456781234567812345678");
System.out.println("Decrypted AES ECB String: ");
System.out.println(decryptedText);

Wanted to provide this for any poor slob who finds him/herself in the same boat : )

Hope this helps!


问:
JS, how to launch app on a specific monitor?
i chose and read a PPT file from an html page on a Windows 10 computer with dual monitors, this is the code:

```<code><script>
    function read() {
        var x = document.getElementById("input").files[0].name;
        window.location = x;
    }
</code>```

Is there a way to force the display of the ppt reader always on the same monitor. I know that if you close the window in a monitor, it will reopen on the same, but i looking for a more reliable solution. Thanks for your informations

答:
Opening an app in a particular window is a feature of the operating system. It cannot be controlled in browser.

In a multi-screen setup, Windows 10 remembers the monitor on which a specific application (Example: Powerpoint) was opened recently, and tries to open the next file in the same monitor again.

Therefore, if there are 2 monitors, and if any powerpoint file is manually moved to monitor # 2 once, then Windows will continue to use monitor #2 for all PPT files opened subsequently.

More information:
https://windowsreport.com/move-apps-between-monitors-windows-10/


问:
Randomised Queue implementation - ideas for randomness
I am taking the Algorithms course in coursera. One of the assignments is the following:

Randomized queue. A randomized queue is similar to a stack or queue,
  except that the item removed is chosen uniformly at random among items
  in the data structure.

I am trying to find a way to implement dequeue (randomly removing an item) in a constant amount of time. I have thought of an idea to do this recquiring a deque (which supports removing and adding an item from the front and back in constant time). My idea is as follows:

Use a deque as an underlying data structure inside the randomized queue

Enqueue - use a library function to generate an integer between 0 and 1 inclusive. If the integer is 0, add the item to the front of the deque. Otherwise, add it to the back.

Dequeue - any direction would be fine.

The reason why the randomness happens in enqueue rather than in dequeue is because I find it to be not exactly random (E.G. n calls to enqueue will have dequeue only return either the first or nth item). So to be sure the items are being removed randomly, I decided to enqueue them randomly.

This idea seems good to me because I cannot find holes in it, but the problem is I cannot prove that my idea would really work. I don't know much about randomness. In fact, this is only the 5th time I am working with random data structures.

Is my idea correct? Will it generate a data structure that removes items at random?

答:
I don't think your proposed approach will work because of the uniformity requirement.  Uniformity means that every item in the queue has an equal likelihood of being dequeued.  Your proposal always adds elements to one of the ends, and dequeues from one end or the other.  Consequently, on any given dequeue request the non-end elements have zero probability of being selected.

An alternative might be to use an array-based stack.  Add elements at the end of the stack, but for dequeueing choose an element at random, swap it with the last element, and then pop it.  That will have uniformity of selection, and all of the component operations are constant time.


问:
How to get the percentile from the dataset?
I processed the dataset.

```<code>df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')

df$countryName = as.character(df$countryName)
</code>```

Considering the new cases announced, the top 3 countries that explained the most cases explained what% of the total cases. can we find it?

答:
Here is one way to do this with Base R. Since the statistics are cumulative for each country by day, we subset to the most recent day's data with the [ form of the extract operator, sort by descending confirmed cases, calculate and sum the percentages for the first 3 rows.

```<code>df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
df$countryName = as.character(df$countryName)
# subset to max(day)

today <- df[df$day == max(df$day),]
today <- today[order(today$confirmed,decreasing=TRUE),]
today$pct <- today$confirmed / sum(today$confirmed)
paste("top 3 countries percentage as of",today$day[1],"is:",
  sprintf("%3.2f%%",sum(today$pct[1:3]*100)))
</code>```

...and the output:

```<code>> paste("top 3 countries percentage as of",today$day[1],"is:",
+       sprintf("%3.2f%%",sum(today$pct[1:3]*100)))
[1] "top 3 countries percentage as of 2020/05/30 is: 44.09%"
</code>```

We can print selected data for the top 3 countries as follows.

```<code>today[1:3,colList]
        countryName        day confirmed        pct
26000 United States 2020/05/30   1816117 0.29531640
3640         Brazil 2020/05/30    498440 0.08105067
21710        Russia 2020/05/30    396575 0.06448654
>
</code>```

Body:
I processed the dataset.

df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')

df$countryName = as.character(df$countryName)

Considering the new cases announced, the top 3 countries that explained the most cases explained what% of the total cases. can we find it?

Body:
Here is one way to do this with Base R. Since the statistics are cumulative for each country by day, we subset to the most recent day's data with the [ form of the extract operator, sort by descending confirmed cases, calculate and sum the percentages for the first 3 rows.

df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
df$countryName = as.character(df$countryName)
# subset to max(day)

today <- df[df$day == max(df$day),]
today <- today[order(today$confirmed,decreasing=TRUE),]
today$pct <- today$confirmed / sum(today$confirmed)
paste("top 3 countries percentage as of",today$day[1],"is:",
  sprintf("%3.2f%%",sum(today$pct[1:3]*100)))

...and the output:

> paste("top 3 countries percentage as of",today$day[1],"is:",
+       sprintf("%3.2f%%",sum(today$pct[1:3]*100)))
[1] "top 3 countries percentage as of 2020/05/30 is: 44.09%"

We can print selected data for the top 3 countries as follows.

today[1:3,colList]
        countryName        day confirmed        pct
26000 United States 2020/05/30   1816117 0.29531640
3640         Brazil 2020/05/30    498440 0.08105067
21710        Russia 2020/05/30    396575 0.06448654
>