问:
Converting input string to hex does not produce correct size
I am trying to convert input string from pipe to hexadecimal, the input is 8KB but converted hex is just 6KB, I print out normal input and the correct lines are coming. I also try to write that hex string to shared memory, maybe my problem is the memory pointer but I'm not sure.

But, it prints out hex correctly for small inputs, I am stuck.

String to hex:

```<code>void stringtohex(char *input, char *output) {
    int loop;
    int i;

    i = 0;
    loop = 0;

    while (input[loop] != '\0') {
        sprintf((char*)(output + i), "%02X", input[loop]);
        loop += 1;
        i += 2;
    }
    //insert NULL at the end of the output string
    output[i++] = '\0';
}
</code>```

Reading part:

```<code>    int num;
    char s[BUFFER_SIZE];
    while ((num = read(fd, s, BUFFER_SIZE)) > 0) {
        //fprintf(stderr, "input: \n%s\n", s);
        int len = strlen(s);
        char hex[(len * 2) + 1];
        stringtohex(s, hex);
        sprintf(ptr_child_2, "%s", hex);
        ptr_child_2 += strlen(hex);
    }
</code>```

here ptr is a void * mapped to shared memory.

答:
Using read to read data into s and then treat s as if it is a string (e.g. you are calling strlen(s);) is wrong. The function read have no knowledge of strings. It simply tries to read BUFFER_SIZE bytes. So you may get less than a string or multiple strings into s in a single read but it's unlikely that you'll get exactly one string (as your code assumes).

Also notice that you never use num in your code. That's also strange as num holds the number of bytes that were actually stored in s. Consider using num to control the number of bytes to convert.

Or if you really want to operate on strings, take a look at fgets instead.

BTW: Check what sprintf returns... you'll find it useful ;-)

BTW: You could also consider strcat instead of sprintf

The correct solution may depend on the input data but something like this:

```<code>char* stringtohex(char* input, char* output, int num)
{
    int loop=0;

    while(loop < num)
    {
        sprintf(output, "%02X", input[loop]);
        loop+=1;
        output += 2;
    }

    //insert NULL at the end of the output string
    *output = '\0';
    return output;
}
</code>```

Reading part note: ptr_child_2 must point to an empty string to start with:

```<code>        char RESULT[SOME_SUFFICIENT_BIG_NUMBER] = ""; // Or dynamic allocation
        char* ptr_child_2 = RESULT;
        int num;
        char s[BUFFER_SIZE];
        while((num = read(fd, s, BUFFER_SIZE)) > 0)
        {
            ptr_child_2 = stringtohex(s, ptr_child_2, num);
        }
        printf("%s\n", RESULT);
</code>```

Body:
I am trying to convert input string from pipe to hexadecimal, the input is 8KB but converted hex is just 6KB, I print out normal input and the correct lines are coming. I also try to write that hex string to shared memory, maybe my problem is the memory pointer but I'm not sure.

But, it prints out hex correctly for small inputs, I am stuck.

String to hex:

void stringtohex(char *input, char *output) {
    int loop;
    int i;

    i = 0;
    loop = 0;

    while (input[loop] != '\0') {
        sprintf((char*)(output + i), "%02X", input[loop]);
        loop += 1;
        i += 2;
    }
    //insert NULL at the end of the output string
    output[i++] = '\0';
}

Reading part:

    int num;
    char s[BUFFER_SIZE];
    while ((num = read(fd, s, BUFFER_SIZE)) > 0) {
        //fprintf(stderr, "input: \n%s\n", s);
        int len = strlen(s);
        char hex[(len * 2) + 1];
        stringtohex(s, hex);
        sprintf(ptr_child_2, "%s", hex);
        ptr_child_2 += strlen(hex);
    }

here ptr is a void * mapped to shared memory.

Body:
Using read to read data into s and then treat s as if it is a string (e.g. you are calling strlen(s);) is wrong. The function read have no knowledge of strings. It simply tries to read BUFFER_SIZE bytes. So you may get less than a string or multiple strings into s in a single read but it's unlikely that you'll get exactly one string (as your code assumes).

Also notice that you never use num in your code. That's also strange as num holds the number of bytes that were actually stored in s. Consider using num to control the number of bytes to convert.

Or if you really want to operate on strings, take a look at fgets instead.

BTW: Check what sprintf returns... you'll find it useful ;-)

BTW: You could also consider strcat instead of sprintf

The correct solution may depend on the input data but something like this:

char* stringtohex(char* input, char* output, int num)
{
    int loop=0;

    while(loop < num)
    {
        sprintf(output, "%02X", input[loop]);
        loop+=1;
        output += 2;
    }

    //insert NULL at the end of the output string
    *output = '\0';
    return output;
}

Reading part note: ptr_child_2 must point to an empty string to start with:

        char RESULT[SOME_SUFFICIENT_BIG_NUMBER] = ""; // Or dynamic allocation
        char* ptr_child_2 = RESULT;
        int num;
        char s[BUFFER_SIZE];
        while((num = read(fd, s, BUFFER_SIZE)) > 0)
        {
            ptr_child_2 = stringtohex(s, ptr_child_2, num);
        }
        printf("%s\n", RESULT);


来源: stackexchange

问:
Detecting a Nullable Type via reflection
Surprisingly the following code fails the Assert:

```<code>int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);
</code>```

So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?

答:
Well firstly, Nullable<T> is a struct, so there isn't an object as such. You can't call GetType(), as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).

(Boxing is what's messing up your assertion here - I would assume that IsType accepts object.)

You can use type inference though to get the type of the variable as a type parameter:

```<code>public bool IsNullable<T>(T value)
{
    return Nullable.GetUnderlyingType(typeof(T)) != null;
}
</code>```

That's not a huge amount of use when you know the exact type at compile-time as in your example, but it's useful for generics. (There are alternative ways of implementing it, of course.)

What's your real life situation? I assume it's not an assertion like this, given that you know the answer to this one at compile time.

ContentLicense: CC BY-SA 3.0

Body:
Surprisingly the following code fails the Assert:

int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);

So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?

Body:
Well firstly, Nullable<T> is a struct, so there isn't an object as such. You can't call GetType(), as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).

(Boxing is what's messing up your assertion here - I would assume that IsType accepts object.)

You can use type inference though to get the type of the variable as a type parameter:

public bool IsNullable<T>(T value)
{
    return Nullable.GetUnderlyingType(typeof(T)) != null;
}

That's not a huge amount of use when you know the exact type at compile-time as in your example, but it's useful for generics. (There are alternative ways of implementing it, of course.)

What's your real life situation? I assume it's not an assertion like this, given that you know the answer to this one at compile time.


问:
(Vulkan 1.0 APIs missing from instance) when launching Android Emulator(Q API 29) via Android Studio 3.5 and 3.6 Canary 9
I created three AVDs base on Android Q (API 29), using these system images:

 Android 10(Google Play), Android 10(Google APIs), Android 10.

All of these emulators failed to launch.
With the following error:

```<code>18:38   Emulator: VK_VERSION_1_0 check failed: vkCreateInstance not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceExtensionProperties not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceLayerProperties not found

18:38   Emulator: createOrGetGlobalVkEmulation: Warning: Vulkan 1.0 APIs missing from instance

18:38   Emulator: Process finished with exit code 0
</code>```

I have referred to this link:

Emulator: Unexpected feature list: MultiDisplay VulkanNullOptionalStrings YUV420888toNV21 YUVCache

But this issue is different from my issue.

I tried in Android Studio 3.5, and Android Studio 3.6 Canary 9, the latest version in stable and preview channel. Both end with the same result.

https://source.android.google.cn/devices/graphics/implement-vulkan

According to this page, Vulkan 1.0 should already exists since Android 7.0, I have no idea why Vulkan 1.0 is missing on Android 10.

Or should I just wait for the newer version of system image after Google officially release Android 10?

答:
I had similar issues that were not fixed with the installation hints above.

I finally solved the problem following this instructions to Configure VM acceleration on Linux: https://help.ubuntu.com/community/KVM/Installation

My problem turned out to be wrong user-groups configuration. The following commands finally made it work for me:

$ sudo adduser  libvirtd

$ sudo chown root:libvirtd /dev/kvm

ContentLicense: CC BY-SA 4.0

Body:
I created three AVDs base on Android Q (API 29), using these system images:

 Android 10(Google Play), Android 10(Google APIs), Android 10.

All of these emulators failed to launch.
With the following error:

18:38   Emulator: VK_VERSION_1_0 check failed: vkCreateInstance not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceExtensionProperties not found

18:38   Emulator: VK_VERSION_1_0 check failed: vkEnumerateInstanceLayerProperties not found

18:38   Emulator: createOrGetGlobalVkEmulation: Warning: Vulkan 1.0 APIs missing from instance

18:38   Emulator: Process finished with exit code 0

I have referred to this link:

Emulator: Unexpected feature list: MultiDisplay VulkanNullOptionalStrings YUV420888toNV21 YUVCache

But this issue is different from my issue.

I tried in Android Studio 3.5, and Android Studio 3.6 Canary 9, the latest version in stable and preview channel. Both end with the same result.

https://source.android.google.cn/devices/graphics/implement-vulkan

According to this page, Vulkan 1.0 should already exists since Android 7.0, I have no idea why Vulkan 1.0 is missing on Android 10.

Or should I just wait for the newer version of system image after Google officially release Android 10?


问:
How do I change font size for Tkinter Scrolling Text
I am using this code to make a scrolling text window using Tkinter with python 3.5, and I was curious what I could do to change the font size and color of the scrolling text.</p>

```<code> import tkinter as tk

 root = tk.Tk()
 deli = 100           # milliseconds of delay per character
 svar = tk.StringVar()
 labl = tk.Label(root, textvariable=svar, height=5)

 def shif():
     shif.msg = shif.msg[1:] + shif.msg[0]
     svar.set(shif.msg)
     root.after(deli, shif)

shif.msg = 'Text example: Blah, Blah Blah'
shif()
labl.pack()
root.mainloop()
</code>```

答:
```<code>def create_scrolltext(self):
    F_font = ('bold', 30)
    scroll_w = 30
    scroll_h = 10
    scrollText = scrolledtext.ScrolledText(self, width=scroll_w, height=scroll_h, wrap = tk.WORD, font=F_font)
    scrollText.config(bg='white', fg='blue')
    scrollText.grid(column=0, columnspan=3)
</code>```

Body:
I am using this code to make a scrolling text window using Tkinter with python 3.5, and I was curious what I could do to change the font size and color of the scrolling text.

 import tkinter as tk

 root = tk.Tk()
 deli = 100           # milliseconds of delay per character
 svar = tk.StringVar()
 labl = tk.Label(root, textvariable=svar, height=5)

 def shif():
     shif.msg = shif.msg[1:] + shif.msg[0]
     svar.set(shif.msg)
     root.after(deli, shif)

shif.msg = 'Text example: Blah, Blah Blah'
shif()
labl.pack()
root.mainloop()


问:
There are 100 promises in an array and we need to process 5 at a time in JS. how to achieve this?
There are 100 promises in an array and we need to process 5 at a time in JS. how to achieve this?
(Asked in Microsoft interview)</p>

答:
Use a pool. There are a number of implementations in JS, such as this one that has a nice looking API:

const PromisePool = require("async-promise-pool");

// concurrency is the only option for PromisePool and enables you to
// choose how many promises will run at once
const pool = new PromisePool({ concurrency: 3 });

// elsewhere add functions to the pool that produce promises. We use
// functions here to prevent the promises from immediately executing.
pool.add(() => thingThatReturnsAPromise());

// you can await pool.all to ensure that all promises in the pool are
// resolved before continuing.
await pool.all();
```


问:
Convert List of Lists to Dataframe Based on 1 List - Every List Different
Really struggling to convert a list of lists into a tidy dataframe. I've found various solutions, but none have worked for what I'm specifically trying to do. It also has to be super fast because the dataset is massive.  Here's a snippet of the lists:

```<code>$PMID
[1] "32007943" "32007942" "32007941" "31894091" "31894090"

$Authors
$Authors[[1]]
  LastName  ForeName Initials order
1     Ward  Jordan M       JM     1
2     Hess  Jaclyn N       JN     2
3    Davis Loretta S       LS     3

$Authors[[2]]
  LastName ForeName Initials order
1     Pope  Janet E       JE     1

$Authors[[3]]
  LastName ForeName Initials order
1 Polachek      Ari        A     1
2     Eder     Lihi        L     2

$Authors[[4]]
  LastName ForeName Initials order
1 Milchert   Marcin        M     1
2  Brzosko    Marek        M     2

$Authors[[5]]
  LastName  ForeName Initials order
1  Pascual    Eliseo        E     1
2   Andrés   Mariano        M     2
3   Sivera Francisca        F     3

$Year
[1] 2020 2020 2020 2020 2020

$PublicationType
$PublicationType[[1]]
  PublicationType
"Journal Article"

$PublicationType[[2]]
PublicationType
    "Editorial"

$PublicationType[[3]]
PublicationType
    "Editorial"

$PublicationType[[4]]
  PublicationType
"Journal Article"

$PublicationType[[5]]
PublicationType
    "Editorial"

</code>```

Here is what I want that data to eventually look.  "Authors" should be the observations in the dataframe but it needs to retain the structure, where the group Authors[1] is matched up to PMID[1] and Authors[2] to PMID[2] and so on and so forth.

```<code>
  LastName  ForeName Initials order  PMID      Year  Publication_Type
1     Ward  Jordan M       JM     1  32007943  2020  "Journal Article"
2     Hess  Jaclyn N       JN     2  32007943  2020  "Journal Article"
3    Davis Loretta S       LS     3  32007943  2020  "Journal Article"
4     Pope   Janet E       JE     1  32007942  2020  "Editorial"
5  Polachek      Ari        A     1  32007941  2020  "Editorial"
6      Eder     Lihi        L     2  32007941  2020  "Editorial"
7  Milchert   Marcin        M     1  31894091  2020  "Journal Article"
8   Brzosko    Marek        M     2  31894091  2020  "Journal Article"
9  Pascual    Eliseo        E     1  31894090  2020  "Editorial"
1   Andrés   Mariano        M     2  31894090  2020  "Editorial"
11  Sivera Francisca        F     3  31894090  2020  "Editorial"

</code>```

Would really appreciate any help!

UPDATE UPDATE: A. Suliman posted a really nice solution, but once I go over 100 extractions it crashes. Very confusing. I'm just posting the whole script and the output:

```<code>
#install.packages("RISmed")
library(RISmed)

srch_jrheum2020 <- '("The Journal of rheumatology"[Journal]) AND ("2019/01/01"[Date - Publication] : "2020/01/01"[Date - Publication])'

query_jrheum2020 <- EUtilsSummary(
  srch_jrheum2020,
  retmax=100,
  mindate= 2000,
  maxdate= 2021,
  datetype = "ppdt")

package_jrheum2020 <- EUtilsGet(query_jrheum2020, type = "efetch", db = "pubmed")

list_jrheum2020 <- list('PMID' = PMID(package_jrheum2020),
                        'Authors' = Author(package_jrheum2020),
                        'Year' = YearPubmed(package_jrheum2020),
                        'Month' = MonthPubmed(package_jrheum2020),
                        'Day' = DayPubmed(package_jrheum2020),
                        'Journal' = Title(package_jrheum2020),
                        'PublicationType' = PublicationType(package_jrheum2020))

df_jrheum <- pmap_dfr(list_jrheum2020, ~data.frame(
  .y,
  pmid = .x,
  year = ..3,
  month = ..4,
  day = ..5,
  journal = ..6,
  type = ..7,
  stringsAsFactors = FALSE))

</code>```

So that works beautifully and returns exactly what I want:

```<code>
               LastName          ForeName Initials order     pmid year month day                     journal              type
1               Milchert            Marcin        M     1 31894091 2020     1   3 The Journal of rheumatology   Journal Article
2                Brzosko             Marek        M     2 31894091 2020     1   3 The Journal of rheumatology   Journal Article
3                Pascual            Eliseo        E     1 31894090 2020     1   3 The Journal of rheumatology         Editorial
4                 Andrés           Mariano        M     2 31894090 2020     1   3 The Journal of rheumatology         Editorial
5                 Sivera         Francisca        F     3 31894090 2020     1   3 The Journal of rheumatology         Editorial
6                 Yazici             Yusuf        Y     1 31894089 2020     1   3 The Journal of rheumatology         Editorial
7                 Mankia           Kulveer        K     1 31787610 2019    12   4 The Journal of rheumatology            Letter
8                 Briggs       Christopher        C     2 31787610 2019    12   4 The Journal of rheumatology            Letter
9                  Emery              Paul        P     3 31787610 2019    12   4 The Journal of rheumatology            Letter
10                 Deane           Kevin D       KD     1 31787609 2019    12   4 The Journal of rheumatology   Journal Article
11            Demoruelle         M Kristen       MK     2 31787609 2019    12   4 The Journal of rheumatology   Journal Article
12     Alpizar-Rodriguez           Deshiré        D     1 31787603 2019    12   4 The Journal of rheumatology            Letter
13                Finckh              Axel        A     2 31787603 2019    12   4 The Journal of rheumatology            Letter
14                 Dahal            Lekh N       LN     1 31787598 2019    12   4 The Journal of rheumatology            Letter
15                Barker          Robert N       RN     2 31787598 2019    12   4 The Journal of rheumatology            Letter
16                  Ward           Frank J       FJ     3 31787598 2019    12   4 The Journal of rheumatology            Letter
17                  <NA>              <NA>     <NA>    NA 31787596 2019    12   4 The Journal of rheumatology   Journal Article
18                  <NA>              <NA>     <NA>    NA 31787595 2019    12   4 The Journal of rheumatology   Journal Article
19                  <NA>              <NA>     <NA>    NA 31787595 2019    12   4 The Journal of rheumatology Published Erratum
20                 Rabin            Jeff C       JC     1 31787594 2019    12   4 The Journal of rheumatology   Journal Article
21               Ramirez            Kirsti        K     2 31787594 2019    12   4 The Journal of rheumatology   Journal Article
22                  Owen          Claire E       CE     1 31787593 2019    12   4 The Journal of rheumatology         Editorial
23                  Liew         David F L      DFL     2 31787593 2019    12   4 The Journal of rheumatology         Editorial
24              Buchanan       Russell R C      RRC     3 31787593 2019    12   4 The Journal of rheumatology         Editorial
25             Falasinnu          Titilola        T     1 31787592 2019    12   4 The Journal of rheumatology         Editorial
26                Simard           Julia F       JF     2 31787592 2019    12   4 The Journal of rheumatology         Editorial
27                 Hwang          Steven R       SR     1 31676702 2019    11   5 The Journal of rheumatology            Letter
28              Sawatsky            Adam P       AP     2 31676702 2019    11   5 The Journal of rheumatology            Letter
29             Michelena            Xabier        X     1 31676699 2019    11   5 The Journal of rheumatology            Letter
30         Marco-Pascual             Carla        C     2 31676699 2019    11   5 The Journal of rheumatology            Letter
31      González-Giménez            Xavier        X     3 31676699 2019    11   5 The Journal of rheumatology            Letter
32               Juanola            Xavier        X     4 31676699 2019    11   5 The Journal of rheumatology            Letter

</code>```

For some crazy reason, if I bump the "retmax" part of the EUtilsSummary function past 100 I get this error:

```<code>
> df_jrheum <- pmap_dfr(list_jrheum2020, ~data.frame(
+   .y,
+   pmid = .x,
+   year = ..3,
+   month = ..4,
+   day = ..5,
+   journal = ..6,
+   type = ..7,
+   stringsAsFactors = FALSE))
Error in data.frame(.y, pmid = .x, year = ..3, month = ..4, day = ..5,  :
  arguments imply differing number of rows: 4, 1, 3
In addition: There were 50 or more warnings (use warnings() to see the first 50)
>
> warnings()
Warning messages:
1: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded
2: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded
3: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded

</code>```

There are also the annoying warnings about dropping rows, but that seems less consequential.

答:
Given that the list elements are in the same length we can use purrr::pmap to loop in parallel then bind the elements using data.frame

```<code>purrr::pmap_dfr(lst_tmp, ~data.frame(.y, PMID=.x, year=..3, PublicationType=..4,
                                     stringsAsFactors = FALSE))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb PMID year PublicationType
1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    1 2020 Journal Article
2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4    1 2020 Journal Article
3 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    1 2020 Journal Article
4 15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8    2 2021      Journal Ed
5 21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2    2 2021      Journal Ed
6 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4    3 2022         Journal
7 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4    3 2022         Journal
8 16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3    3 2022         Journal
</code>```

Data

```<code>lst_tmp <- list(PMID=c(1,2,3), Authors=list(head(mtcars, 3), tail(mtcars, 2), mtcars[10:12, ]), year=c(2020,2021,2022),
           PublicationType=list(c(PublicationType="Journal Article"), c(PublicationType="Journal Ed"), c(PublicationType="Journal")))
</code>```

Update:

```<code>#With retmax=200 we got some PublicationType with more than one type, e.g list_jrheum2020$PublicationType[[9]], so we can do
paste(list_jrheum2020$PublicationType[[9]], collapse = "-")
#or if you are interset in the first element
list_jrheum2020$PublicationType[[9]][[1]]

#therefore we can try
pmap_dfr(list_jrheum2020, ~data.frame(
    .y,
    pmid = .x,
    year = ..3,
    month = ..4,
    day = ..5,
    journal = ..6,
    type = paste(..7, collapse = "-"),
    stringsAsFactors = FALSE))
</code>```

Body:
Really struggling to convert a list of lists into a tidy dataframe. I've found various solutions, but none have worked for what I'm specifically trying to do. It also has to be super fast because the dataset is massive.  Here's a snippet of the lists:

$PMID
[1] "32007943" "32007942" "32007941" "31894091" "31894090"

$Authors
$Authors[[1]]
  LastName  ForeName Initials order
1     Ward  Jordan M       JM     1
2     Hess  Jaclyn N       JN     2
3    Davis Loretta S       LS     3

$Authors[[2]]
  LastName ForeName Initials order
1     Pope  Janet E       JE     1

$Authors[[3]]
  LastName ForeName Initials order
1 Polachek      Ari        A     1
2     Eder     Lihi        L     2

$Authors[[4]]
  LastName ForeName Initials order
1 Milchert   Marcin        M     1
2  Brzosko    Marek        M     2

$Authors[[5]]
  LastName  ForeName Initials order
1  Pascual    Eliseo        E     1
2   Andrés   Mariano        M     2
3   Sivera Francisca        F     3

$Year
[1] 2020 2020 2020 2020 2020

$PublicationType
$PublicationType[[1]]
  PublicationType
"Journal Article"

$PublicationType[[2]]
PublicationType
    "Editorial"

$PublicationType[[3]]
PublicationType
    "Editorial"

$PublicationType[[4]]
  PublicationType
"Journal Article"

$PublicationType[[5]]
PublicationType
    "Editorial"

Here is what I want that data to eventually look.  "Authors" should be the observations in the dataframe but it needs to retain the structure, where the group Authors[1] is matched up to PMID[1] and Authors[2] to PMID[2] and so on and so forth.

  LastName  ForeName Initials order  PMID      Year  Publication_Type
1     Ward  Jordan M       JM     1  32007943  2020  "Journal Article"
2     Hess  Jaclyn N       JN     2  32007943  2020  "Journal Article"
3    Davis Loretta S       LS     3  32007943  2020  "Journal Article"
4     Pope   Janet E       JE     1  32007942  2020  "Editorial"
5  Polachek      Ari        A     1  32007941  2020  "Editorial"
6      Eder     Lihi        L     2  32007941  2020  "Editorial"
7  Milchert   Marcin        M     1  31894091  2020  "Journal Article"
8   Brzosko    Marek        M     2  31894091  2020  "Journal Article"
9  Pascual    Eliseo        E     1  31894090  2020  "Editorial"
1   Andrés   Mariano        M     2  31894090  2020  "Editorial"
11  Sivera Francisca        F     3  31894090  2020  "Editorial"

Would really appreciate any help!

UPDATE UPDATE: A. Suliman posted a really nice solution, but once I go over 100 extractions it crashes. Very confusing. I'm just posting the whole script and the output:

#install.packages("RISmed")
library(RISmed)

srch_jrheum2020 <- '("The Journal of rheumatology"[Journal]) AND ("2019/01/01"[Date - Publication] : "2020/01/01"[Date - Publication])'

query_jrheum2020 <- EUtilsSummary(
  srch_jrheum2020,
  retmax=100,
  mindate= 2000,
  maxdate= 2021,
  datetype = "ppdt")

package_jrheum2020 <- EUtilsGet(query_jrheum2020, type = "efetch", db = "pubmed")

list_jrheum2020 <- list('PMID' = PMID(package_jrheum2020),
                        'Authors' = Author(package_jrheum2020),
                        'Year' = YearPubmed(package_jrheum2020),
                        'Month' = MonthPubmed(package_jrheum2020),
                        'Day' = DayPubmed(package_jrheum2020),
                        'Journal' = Title(package_jrheum2020),
                        'PublicationType' = PublicationType(package_jrheum2020))

df_jrheum <- pmap_dfr(list_jrheum2020, ~data.frame(
  .y,
  pmid = .x,
  year = ..3,
  month = ..4,
  day = ..5,
  journal = ..6,
  type = ..7,
  stringsAsFactors = FALSE))

So that works beautifully and returns exactly what I want:

               LastName          ForeName Initials order     pmid year month day                     journal              type
1               Milchert            Marcin        M     1 31894091 2020     1   3 The Journal of rheumatology   Journal Article
2                Brzosko             Marek        M     2 31894091 2020     1   3 The Journal of rheumatology   Journal Article
3                Pascual            Eliseo        E     1 31894090 2020     1   3 The Journal of rheumatology         Editorial
4                 Andrés           Mariano        M     2 31894090 2020     1   3 The Journal of rheumatology         Editorial
5                 Sivera         Francisca        F     3 31894090 2020     1   3 The Journal of rheumatology         Editorial
6                 Yazici             Yusuf        Y     1 31894089 2020     1   3 The Journal of rheumatology         Editorial
7                 Mankia           Kulveer        K     1 31787610 2019    12   4 The Journal of rheumatology            Letter
8                 Briggs       Christopher        C     2 31787610 2019    12   4 The Journal of rheumatology            Letter
9                  Emery              Paul        P     3 31787610 2019    12   4 The Journal of rheumatology            Letter
10                 Deane           Kevin D       KD     1 31787609 2019    12   4 The Journal of rheumatology   Journal Article
11            Demoruelle         M Kristen       MK     2 31787609 2019    12   4 The Journal of rheumatology   Journal Article
12     Alpizar-Rodriguez           Deshiré        D     1 31787603 2019    12   4 The Journal of rheumatology            Letter
13                Finckh              Axel        A     2 31787603 2019    12   4 The Journal of rheumatology            Letter
14                 Dahal            Lekh N       LN     1 31787598 2019    12   4 The Journal of rheumatology            Letter
15                Barker          Robert N       RN     2 31787598 2019    12   4 The Journal of rheumatology            Letter
16                  Ward           Frank J       FJ     3 31787598 2019    12   4 The Journal of rheumatology            Letter
17                  <NA>              <NA>     <NA>    NA 31787596 2019    12   4 The Journal of rheumatology   Journal Article
18                  <NA>              <NA>     <NA>    NA 31787595 2019    12   4 The Journal of rheumatology   Journal Article
19                  <NA>              <NA>     <NA>    NA 31787595 2019    12   4 The Journal of rheumatology Published Erratum
20                 Rabin            Jeff C       JC     1 31787594 2019    12   4 The Journal of rheumatology   Journal Article
21               Ramirez            Kirsti        K     2 31787594 2019    12   4 The Journal of rheumatology   Journal Article
22                  Owen          Claire E       CE     1 31787593 2019    12   4 The Journal of rheumatology         Editorial
23                  Liew         David F L      DFL     2 31787593 2019    12   4 The Journal of rheumatology         Editorial
24              Buchanan       Russell R C      RRC     3 31787593 2019    12   4 The Journal of rheumatology         Editorial
25             Falasinnu          Titilola        T     1 31787592 2019    12   4 The Journal of rheumatology         Editorial
26                Simard           Julia F       JF     2 31787592 2019    12   4 The Journal of rheumatology         Editorial
27                 Hwang          Steven R       SR     1 31676702 2019    11   5 The Journal of rheumatology            Letter
28              Sawatsky            Adam P       AP     2 31676702 2019    11   5 The Journal of rheumatology            Letter
29             Michelena            Xabier        X     1 31676699 2019    11   5 The Journal of rheumatology            Letter
30         Marco-Pascual             Carla        C     2 31676699 2019    11   5 The Journal of rheumatology            Letter
31      González-Giménez            Xavier        X     3 31676699 2019    11   5 The Journal of rheumatology            Letter
32               Juanola            Xavier        X     4 31676699 2019    11   5 The Journal of rheumatology            Letter

For some crazy reason, if I bump the "retmax" part of the EUtilsSummary function past 100 I get this error:

> df_jrheum <- pmap_dfr(list_jrheum2020, ~data.frame(
+   .y,
+   pmid = .x,
+   year = ..3,
+   month = ..4,
+   day = ..5,
+   journal = ..6,
+   type = ..7,
+   stringsAsFactors = FALSE))
Error in data.frame(.y, pmid = .x, year = ..3, month = ..4, day = ..5,  :
  arguments imply differing number of rows: 4, 1, 3
In addition: There were 50 or more warnings (use warnings() to see the first 50)
>
> warnings()
Warning messages:
1: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded
2: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded
3: In data.frame(.y, pmid = .x, year = ..3, month = ..4,  ... :
  row names were found from a short variable and have been discarded

There are also the annoying warnings about dropping rows, but that seems less consequential.

Body:
Given that the list elements are in the same length we can use purrr::pmap to loop in parallel then bind the elements using data.frame

purrr::pmap_dfr(lst_tmp, ~data.frame(.y, PMID=.x, year=..3, PublicationType=..4,
                                     stringsAsFactors = FALSE))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb PMID year PublicationType
1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    1 2020 Journal Article
2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4    1 2020 Journal Article
3 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    1 2020 Journal Article
4 15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8    2 2021      Journal Ed
5 21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2    2 2021      Journal Ed
6 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4    3 2022         Journal
7 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4    3 2022         Journal
8 16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3    3 2022         Journal

Data

lst_tmp <- list(PMID=c(1,2,3), Authors=list(head(mtcars, 3), tail(mtcars, 2), mtcars[10:12, ]), year=c(2020,2021,2022),
           PublicationType=list(c(PublicationType="Journal Article"), c(PublicationType="Journal Ed"), c(PublicationType="Journal")))

Update:

#With retmax=200 we got some PublicationType with more than one type, e.g list_jrheum2020$PublicationType[[9]], so we can do
paste(list_jrheum2020$PublicationType[[9]], collapse = "-")
#or if you are interset in the first element
list_jrheum2020$PublicationType[[9]][[1]]

#therefore we can try
pmap_dfr(list_jrheum2020, ~data.frame(
    .y,
    pmid = .x,
    year = ..3,
    month = ..4,
    day = ..5,
    journal = ..6,
    type = paste(..7, collapse = "-"),
    stringsAsFactors = FALSE))


问:
Heroku: Your account has reached its concurrent build limit
I'm trying to deploy my app to heroku, currently using the free tier. Over the past 5 days I've been redeploying the app as I made changes. I went overzealous with the deploys and now my app is up to version 35 on heroku under the "activity" tab.

Now the error message in the title prevents me from deploying my app. Google search didn't return a thing. If I have reached the deployment limit how do I delete/free up my concurrent build space?

答:
Try this command from your project directory</p>

```<code>heroku restart
</code>```

Body:
Try this command from your project directory

heroku restart


问:
Why out heap of memory, why last item in array don't step + 0.1?
Why out heap of memory, why last item in array don't step + 0.1?</p>

```<code>const array = [];
const step = 0.1;
do {
    const item = array[array.length - 1] ? array[array.length - 1] : 0;
    array.push(item + step);
} while (array[array.length - 1] !== 100);
</code>```

答:
Use less-than instead of not-equal-to e.g. while (array[array.length - 1] < 100), because you will not get EXACTLY 100, due to the nature of floating-point arithmetic.

See the output from the program below.

console.log(generateSequence(0, 100, 0.1));

function generateSequence(start, end, step) {
  let result = [];
  do {
    const prev = result[result.length - 1] ? result[result.length - 1] : 0;
    result.push(prev + step);
  } while (result[result.length - 1] < 100);
  return result;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code>```

Alternatively

You can increase the magnitude of the number, floor it, then divide it.

As you can see it works for multiple precisions.

console.log(generateSequence(0, 100, 1).join(', '));
console.log(generateSequence(0, 100, 10).join(', '));
console.log(generateSequence(0, 100, 0.1).join(', '));
console.log(generateSequence(0, 100, 0.025).join(', '));

function generateSequence(start, end, step) {
  let result = [],
      trueEnd = end / step,
      precision = step < 1 ? 1 / step : 1,
      p2 = Math.pow(precision, 2);
  for (let i = 0; i < trueEnd; i++) {
    result.push(Math.floor(i * precision) / p2);
  }
  return result;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code>```

Body:
Why out heap of memory, why last item in array don't step + 0.1?

const array = [];
const step = 0.1;
do {
    const item = array[array.length - 1] ? array[array.length - 1] : 0;
    array.push(item + step);
} while (array[array.length - 1] !== 100);

Body:
Use less-than instead of not-equal-to e.g. while (array[array.length - 1] < 100), because you will not get EXACTLY 100, due to the nature of floating-point arithmetic.

See the output from the program below.

console.log(generateSequence(0, 100, 0.1));

function generateSequence(start, end, step) {
  let result = [];
  do {
    const prev = result[result.length - 1] ? result[result.length - 1] : 0;
    result.push(prev + step);
  } while (result[result.length - 1] < 100);
  return result;
}

.as-console-wrapper { top: 0; max-height: 100% !important; }

Alternatively

You can increase the magnitude of the number, floor it, then divide it.

As you can see it works for multiple precisions.

console.log(generateSequence(0, 100, 1).join(', '));
console.log(generateSequence(0, 100, 10).join(', '));
console.log(generateSequence(0, 100, 0.1).join(', '));
console.log(generateSequence(0, 100, 0.025).join(', '));

function generateSequence(start, end, step) {
  let result = [],
      trueEnd = end / step,
      precision = step < 1 ? 1 / step : 1,
      p2 = Math.pow(precision, 2);
  for (let i = 0; i < trueEnd; i++) {
    result.push(Math.floor(i * precision) / p2);
  }
  return result;
}

.as-console-wrapper { top: 0; max-height: 100% !important; }


问:
Get changes from master into branch in Git
In my repository I have a branch called aq which I'm working on.

I then committed new work and bugs in master.

What is the best way to get those commits into the aq branch? Create another new branch out of master and merge it with aq?

答:
EDIT:

My answer below documents a way to merge master into aq, where if you view the details of the merge it lists the changes made on aq prior to the merge, not the changes made on master. I've realised that that probably isn't what you want, even if you think it is!

Just:

```<code>git checkout aq
git merge master
</code>```

is fine.

Yes, this simple merge will show that the changes from master were made to aq at that point, not the other way round; but that is okay – since that is what did happen! Later on, when you finally merge your branch into master, that is when a merge will finally show all your changes as made to master (which is exactly what you want, and is the commit where people are going to expect to find that info anyway).

I've checked and the approach below also shows exactly the same changes (all the changes made on aq since the original split between aq and master) as the normal approach above, when you finally merge everything back to master. So I think its only real disadvantage (apart from being over-complex and non-standard... :-/ ) is that if you wind back n recent changes with git reset --hard HEAD~<n> and this goes past the merge, then the version below rolls back down the 'wrong' branch, which you have to fix up by hand (e.g. with git reflog & git reset --hard [sha]).

[So, what I previously thought was that:]

There is a problem with:

```<code>git checkout aq
git merge master
</code>```

because the changes shown in the merge commit (e.g. if you look now or later in Github, Bitbucket or your favourite local git history viewer) are the changes made on master, which may well not be what you want.

On the other hand

```<code>git checkout master
git merge aq
</code>```

shows the changes made in aq, which probably is what you want. (Or, at least, it's often what I want!) But the merge showing the right changes is on the wrong branch!

How to cope?!

The full process, ending up with a merge commit showing the changes made on aq (as per the second merge above), but with the merge affecting the aq branch, is:

```<code>git checkout master
git merge aq
git checkout aq
git merge master
git checkout master
git reset --hard HEAD~1
git checkout aq
</code>```

This: merges aq onto master, fast-forwards that same merge onto aq, undoes it on master, and puts you back on aq again!

I feel like I'm missing something - this seems to be something you'd obviously want, and something that's hard to do.

Also, rebase is NOT equivalent. It loses the timestamps and identity of the commits made on aq, which is also not what I want.

Body:
EDIT:

My answer below documents a way to merge master into aq, where if you view the details of the merge it lists the changes made on aq prior to the merge, not the changes made on master. I've realised that that probably isn't what you want, even if you think it is!

Just:

git checkout aq
git merge master

is fine.

Yes, this simple merge will show that the changes from master were made to aq at that point, not the other way round; but that is okay – since that is what did happen! Later on, when you finally merge your branch into master, that is when a merge will finally show all your changes as made to master (which is exactly what you want, and is the commit where people are going to expect to find that info anyway).

I've checked and the approach below also shows exactly the same changes (all the changes made on aq since the original split between aq and master) as the normal approach above, when you finally merge everything back to master. So I think its only real disadvantage (apart from being over-complex and non-standard... :-/ ) is that if you wind back n recent changes with git reset --hard HEAD~<n> and this goes past the merge, then the version below rolls back down the 'wrong' branch, which you have to fix up by hand (e.g. with git reflog & git reset --hard [sha]).

[So, what I previously thought was that:]

There is a problem with:

git checkout aq
git merge master

because the changes shown in the merge commit (e.g. if you look now or later in Github, Bitbucket or your favourite local git history viewer) are the changes made on master, which may well not be what you want.

On the other hand

git checkout master
git merge aq

shows the changes made in aq, which probably is what you want. (Or, at least, it's often what I want!) But the merge showing the right changes is on the wrong branch!

How to cope?!

The full process, ending up with a merge commit showing the changes made on aq (as per the second merge above), but with the merge affecting the aq branch, is:

git checkout master
git merge aq
git checkout aq
git merge master
git checkout master
git reset --hard HEAD~1
git checkout aq

This: merges aq onto master, fast-forwards that same merge onto aq, undoes it on master, and puts you back on aq again!

I feel like I'm missing something - this seems to be something you'd obviously want, and something that's hard to do.

Also, rebase is NOT equivalent. It loses the timestamps and identity of the commits made on aq, which is also not what I want.


问:
Customize action to be called in a controller from a form in rails 3
I have a model Product that is both used by a general controller products_controller and another one used for administration purposes products_controller in an /admin folder.

Because I wanted to create a form that will be sent via AJAX and depending on whether the product is there or not it will alter between a :create and an :update, I've decided to create a 3rd method that takes care of that; called insert.

```<code>def insert
#blah
end
</code>```

The form tag I'm using for updating is:

```<code><%= form_for(product, :url => admin_product_url(product), :remote => true, :layout => true) do |f| %>
</code>```

So my question is how can I customize the form tag in order to call the insert action I tried:

```<code><%= form_for(product, :url => admin_product_url(product), :action => :insert, :remote => true, :layout => true) do |f| %>
</code>```

and

```<code><%= form_for(product, :url => insert_admin_product_url(product), :remote => true, :layout => true) do |f| %>
</code>```

so far with no luck.

I hope someone could show me the way to go.
Thanks

答:
you should have to add below route in route file under the admin name space</p>

```<code>match 'products/insert', :to =>'products#insert', :as => 'admin_products_insert'
</code>```

Body:
I have a model Product that is both used by a general controller products_controller and another one used for administration purposes products_controller in an /admin folder.

Because I wanted to create a form that will be sent via AJAX and depending on whether the product is there or not it will alter between a :create and an :update, I've decided to create a 3rd method that takes care of that; called insert.

def insert
#blah
end

The form tag I'm using for updating is:

<%= form_for(product, :url => admin_product_url(product), :remote => true, :layout => true) do |f| %>

So my question is how can I customize the form tag in order to call the insert action I tried:

<%= form_for(product, :url => admin_product_url(product), :action => :insert, :remote => true, :layout => true) do |f| %>

and

<%= form_for(product, :url => insert_admin_product_url(product), :remote => true, :layout => true) do |f| %>

so far with no luck.

I hope someone could show me the way to go.
Thanks

Body:
you should have to add below route in route file under the admin name space

match 'products/insert', :to =>'products#insert', :as => 'admin_products_insert'


问:
How to convert formatted text to html tag in Google-apps-script?
I want to convert a formatted text in a cell to html but I don't know how to read the format of the text.

Let's say that I have the following text in a cell:
A text with a bold word.

And I would like to convert it in an other cell to:
A text with a bold word.

How can I do that?

I didn't find anything useful in the Spreadsheet API to read format info...Does anyone have any tips?
Thanks.

EDIT: I've created a feature request. Please vote to have the feature.

答:
My Google Script

```<code>/**
 * Rich Text to HTML.
 * @param {string} qRange Input text.
 * @returns {string} Text as HTML.
 * @customfunction
 */
function RICHTEXT_TO_HTML(qRange) {
  var indexBool = false;
  var indexItalic = false;
  var indexUnderline = false;
  var indexStrikethrough = false;

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(qRange);
  var cell = range;
  var cellValue = cell.getRichTextValue();
  var txt = String(cell.getDisplayValue());
  var styles = cell.getTextStyles();
  var result = '';

  for (var i = 0; i < txt.length; i++) {
    var style = cellValue.getTextStyle(i, i + 1);

    if (!indexStrikethrough && style.isStrikethrough()) {
      indexStrikethrough = true;
      result += '<strike>';
    } else if (indexStrikethrough && !style.isStrikethrough()) {
      indexStrikethrough = false;
      result += '</strike>';
    }

    if (!indexUnderline && style.isUnderline()) {
      indexUnderline = true;
      result += '<u>';
    } else if (indexUnderline && !style.isUnderline()) {
      indexUnderline = false;
      result += '</u>';
    }

    if (!indexBool && style.isBold()) {
      indexBool = true;
      result += '<b>';
    } else if (indexBool && !style.isBold()) {
      indexBool = false;
      result += '</b>';
    }

    if (!indexItalic && style.isItalic()) {
      indexItalic = true;
      result += '<i>';
    } else if (indexItalic && !style.isItalic()) {
      indexItalic = false;
      result += '</i>';
    }

    result += txt[i];
  }

  if (indexStrikethrough) {
    result += '</strike>';
  }

  if (indexUnderline) {
    result += '</u>';
  }

  if (indexBool) {
    result += '</b>';
  }

  if (indexItalic) {
    result += '</i>';
  }

  return result;
}
</code>```

Usage

A1 = "My formatted example!!!"

A2 = =RICHTEXT_TO_HTML("A1")

A2 Result = My formatted example!!!

Working example

https://docs.google.com/spreadsheets/d/1mVvE8AdXYKSnaSIfRBrjfOeXxmTkVZovhguMZ3sc47M/edit?usp=sharing

Body:
My Google Script

/**
 * Rich Text to HTML.
 * @param {string} qRange Input text.
 * @returns {string} Text as HTML.
 * @customfunction
 */
function RICHTEXT_TO_HTML(qRange) {
  var indexBool = false;
  var indexItalic = false;
  var indexUnderline = false;
  var indexStrikethrough = false;

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(qRange);
  var cell = range;
  var cellValue = cell.getRichTextValue();
  var txt = String(cell.getDisplayValue());
  var styles = cell.getTextStyles();
  var result = '';

  for (var i = 0; i < txt.length; i++) {
    var style = cellValue.getTextStyle(i, i + 1);

    if (!indexStrikethrough && style.isStrikethrough()) {
      indexStrikethrough = true;
      result += '<strike>';
    } else if (indexStrikethrough && !style.isStrikethrough()) {
      indexStrikethrough = false;
      result += '</strike>';
    }

    if (!indexUnderline && style.isUnderline()) {
      indexUnderline = true;
      result += '<u>';
    } else if (indexUnderline && !style.isUnderline()) {
      indexUnderline = false;
      result += '</u>';
    }

    if (!indexBool && style.isBold()) {
      indexBool = true;
      result += '<b>';
    } else if (indexBool && !style.isBold()) {
      indexBool = false;
      result += '</b>';
    }

    if (!indexItalic && style.isItalic()) {
      indexItalic = true;
      result += '<i>';
    } else if (indexItalic && !style.isItalic()) {
      indexItalic = false;
      result += '</i>';
    }

    result += txt[i];
  }

  if (indexStrikethrough) {
    result += '</strike>';
  }

  if (indexUnderline) {
    result += '</u>';
  }

  if (indexBool) {
    result += '</b>';
  }

  if (indexItalic) {
    result += '</i>';
  }

  return result;
}

Usage

A1 = "My formatted example!!!"

A2 = =RICHTEXT_TO_HTML("A1")

A2 Result = My <i>formatted</i> <b>example</b>!!!

Working example

https://docs.google.com/spreadsheets/d/1mVvE8AdXYKSnaSIfRBrjfOeXxmTkVZovhguMZ3sc47M/edit?usp=sharing


问:
How can I make a Java thread do a different task rather than block if a semaphore lock acquire/tryAcquire fails?
I've been learning concurrency in java and was looking at java semaphores and ran into a problem. I have multiple threads trying to acquire one of multiple locks to access a critical section protected by a semaphore and want my all threads who have failed to acquire the lock to do a specific task and then attempt to reacquire the lock. Every time the acquisition fails I want the thread to do the waiting task I have made and when it's done try again. repeat until acquired. Looking at the java docs for the java semaphore class, all the acquire methods seem to do some form of blocking one way or another. How can I accomplish what I want?</p>

答:
Use tryAcquire:

```<code>while(!done) {
  if(sem.tryAcquire()) {
     // semaphore acquired
     done=true
  } else {
   // Semaphore not acquired, do something else
  }
}
</code>```

There is another variant of tryAcquire with a timeout and you can use that if you want to wait a while and then continue.

Body:
Use tryAcquire:

while(!done) {
  if(sem.tryAcquire()) {
     // semaphore acquired
     done=true
  } else {
   // Semaphore not acquired, do something else
  }
}

There is another variant of tryAcquire with a timeout and you can use that if you want to wait a while and then continue.


问:
Difference between the reference types of derived and base classes
Guys i want your help please.

We Have This Code:

```<code>class Program
{

    static void Main(string[] args)
    {
        Animal pig = new Pig();

        Pig pig2 = new Pig();

        List<Animal> Animals = new List<Animal>();
        Animals.Add(pig);
        Animals.Add(pig2);

        foreach(Animal a in Animals)
        {
            Animal.AnimalSound();
        }
    }
}

class Animal
{
    public virtual void AnimalSound()
    {
        Console.WriteLine("AnimalSound");
    }
}

class Pig : Animal
{
    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}
</code>```

My Question is as i instantiate variables pig and pig2 what's the difference Animal pig = new Pig(); and Pig pig2 = new Pig();

Why not declare them both as ReferenceType Pig since Pig is as always Animal????

答:
So you have base class Animal and derived class Pig. So our question can be concluded to what's difference between base and derived classes:

Base class is a class from which other classes are derived.

Derived class is a class that is created on the basis of an existing class. Some features of derived class:

The derived class inherits almost all of the properties of the base class. Private properties are not accessible due to the accessibility level, however you can use reflection to read their values.

The derived class can add new members to itself or change base class members.

Body:
Guys i want your help please.

We Have This Code:

class Program
{

    static void Main(string[] args)
    {
        Animal pig = new Pig();

        Pig pig2 = new Pig();

        List<Animal> Animals = new List<Animal>();
        Animals.Add(pig);
        Animals.Add(pig2);

        foreach(Animal a in Animals)
        {
            Animal.AnimalSound();
        }
    }
}

class Animal
{
    public virtual void AnimalSound()
    {
        Console.WriteLine("AnimalSound");
    }
}

class Pig : Animal
{
    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}

My Question is as i instantiate variables pig and pig2 what's the difference Animal pig = new Pig(); and Pig pig2 = new Pig();

Why not declare them both as ReferenceType Pig since Pig is as always Animal????


问:
PHP How to hit a url and download its xml
I am trying to send this query:

```<code>http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK
</code>```

To a web service and pull down and parse a bunch of fields there, namely these:

```<code>// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.
</code>```

I am doing this:

```<code>$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
</code>```

Could someone please provide the right code to loop through the results and get values?

答:
fopen will give you a resource, no the file.  Since you're doing a json decode, you'll want to just the whole thing as a string.  Easiest way to do this is file_get_contents.</p>

```<code>$query = 'http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK';
$response = file_get_contents($query);
// You really should do error handling on the response here.
$decoded = json_decode($response, true);
echo '<p>Decoded: '.$decoded['lat'].'</p>';
</code>```

Body:
I am trying to send this query:

http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK

To a web service and pull down and parse a bunch of fields there, namely these:

// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.

I am doing this:

$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";

Could someone please provide the right code to loop through the results and get values?

Body:
fopen will give you a resource, no the file.  Since you're doing a json decode, you'll want to just the whole thing as a string.  Easiest way to do this is file_get_contents.

$query = 'http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK';
$response = file_get_contents($query);
// You really should do error handling on the response here.
$decoded = json_decode($response, true);
echo '<p>Decoded: '.$decoded['lat'].'</p>';


问:
Hide player controls on fullscreen
I implemented some custom controls for my player and I need to hide the player controls that
appear when I move to fullscreen and show my custom controls. How can I achieve this?</p>

```<code>onFullScreenClick() {
   var elem = document.getElementById('video');

   if (elem.requestFullscreen) {
     elem.requestFullscreen();
   } else if (elem.mozRequestFullScreen) {
     elem.mozRequestFullScreen();
   } else if (elem.webkitRequestFullscreen) {
     elem.webkitRequestFullscreen();
   } else if (elem.msRequestFullscreen) {
     elem.msRequestFullscreen();
   }
}

 <div
    className={'video-player'}
    onMouseEnter={this.enterVideoArea}
    onMouseLeave={this.leaveVideoArea}
  >
    <video
      ref={'video'}
      id={'video'}
      width={'640'}
      className="react-video-player"
      controls={false}
      loop
      autoPlay
      onClick={this.togglePlay}
    />
    <div
</code>```

答:
You can hide all media-controls from video tags like that</p>

```<code>video::-webkit-media-controls {
  display:none !important;
}
</code>```

Title: Hide player controls on fullscreen

Body:
I implemented some custom controls for my player and I need to hide the player controls that
appear when I move to fullscreen and show my custom controls. How can I achieve this?

onFullScreenClick() {
   var elem = document.getElementById('video');

   if (elem.requestFullscreen) {
     elem.requestFullscreen();
   } else if (elem.mozRequestFullScreen) {
     elem.mozRequestFullScreen();
   } else if (elem.webkitRequestFullscreen) {
     elem.webkitRequestFullscreen();
   } else if (elem.msRequestFullscreen) {
     elem.msRequestFullscreen();
   }
}

    <video
      ref={'video'}
      id={'video'}
      width={'640'}
      className="react-video-player"
      controls={false}
      loop
      autoPlay
      onClick={this.togglePlay}
    />
    <div

Body:
You can hide all media-controls from video tags like that

video::-webkit-media-controls {
  display:none !important;
}


问:
React-Lightbox Image
How do I have it so that when I click on an image it opens up lightbox with the current image that I just clicked on? Right now, if i click the second image tag, it always shows the first picture in lightbox instead of the image I just clicked.
this is what I'm trying to use: http://jossmac.github.io/react-images/</p>

```<code>export default class Home extends Component {

 constructor() {
    super();
    this.state = {
      lightboxIsOpen: false,
      currentImage: 0,
    }
    this.closeLightbox = this.closeLightbox.bind(this);
    this.gotoNext = this.gotoNext.bind(this);
    this.gotoPrevious = this.gotoPrevious.bind(this);

  }
  openLightbox (index, event) {
    event.preventDefault();
    this.setState({
      currentImage: index,
      lightboxIsOpen: true,
    });
  }
  closeLightbox () {
    this.setState({
      currentImage: 0,
      lightboxIsOpen: false,
    });
  }
  gotoPrevious () {
    this.setState({
      currentImage: this.state.currentImage - 1,
    });
  }
  gotoNext () {
    this.setState({
      currentImage: this.state.currentImage + 1,
    });
  }
  gotoImage (index) {
    this.setState({
      currentImage: index,
    });
  }
  handleClickImage () {
    if (this.state.currentImage === this.props.images.length - 1) return;

    this.gotoNext();
  }
  renderGallery () {
    const { images } = this.props;

    if (!images) return;

    const gallery = images.filter(i => i.useForDemo).map((obj, i) => {
      return (
        <a
          href={obj.src}
          className={css(classes.thumbnail, classes[obj.orientation])}
          key={i}
          onClick={(e) => this.openLightbox(i, e)}
        >
          <img src={obj.thumbnail} className={css(classes.source)} />
        </a>
      );
    });
  }

    render() {
            const {
            photoIndex,
            lightboxIsOpen,
            currentImage,
        } = this.state;

  return(
    <div>

<Grid>
  <Row>
   <Col md={6} md={4} >
      <img src="https://docs.google.com/uc?id=0B0huBtqYaof7WVNjMjNMZTY3UDg" onClick={() => this.setState({ lightboxIsOpen: true })} />
      {lightboxIsOpen &&
        <Lightbox
        images={[{ src: 'https://docs.google.com/uc?id=0B0huBtqYaof7WVNjMjNMZTY3UDg' }, { src: 'https://docs.google.com/uc?id=0B0huBtqYaof7c0dpVFdGbGl0MWs' }]}
        currentImage={this.state.currentImage}
        onClickImage={this.handleClickImage}
        isOpen={this.state.lightboxIsOpen}
        onClickPrev={this.gotoPrevious}
        onClickNext={this.gotoNext}
        onClose={this.closeLightbox}

      />

                }
    </Col>
    <img src="https://docs.google.com/uc?id=0B0huBtqYaof7c0dpVFdGbGl0MWs" onClick={() => this.setState({ lightboxIsOpen: true })} />
  </Row>

</Grid>
</div>

    )
}
}
</code>```

答:
You should use map function</p>

```<code>const imgs = [
    "//docs.google.com/uc?id=0B0huBtqYaof7WVNjMjNMZTY3UDg",
    "//docs.google.com/uc?id=0B0huBtqYaof7c0dpVFdGbGl0MWs"
]
const i;
imgs.map((entry, index) => i=index );
//then update your cunstructor
 constructor(props) {
        super(props);

        this.state = {
            photoIndex:i,
            isOpen: false
        };
    }

</code>```

Title: React-Lightbox Image

Body:
How do I have it so that when I click on an image it opens up lightbox with the current image that I just clicked on? Right now, if i click the second image tag, it always shows the first picture in lightbox instead of the image I just clicked.
this is what I'm trying to use: http://jossmac.github.io/react-images/

export default class Home extends Component {

 constructor() {
    super();
    this.state = {
      lightboxIsOpen: false,
      currentImage: 0,
    }
    this.closeLightbox = this.closeLightbox.bind(this);
    this.gotoNext = this.gotoNext.bind(this);
    this.gotoPrevious = this.gotoPrevious.bind(this);

  }
  openLightbox (index, event) {
    event.preventDefault();
    this.setState({
      currentImage: index,
      lightboxIsOpen: true,
    });
  }
  closeLightbox () {
    this.setState({
      currentImage: 0,
      lightboxIsOpen: false,
    });
  }
  gotoPrevious () {
    this.setState({
      currentImage: this.state.currentImage - 1,
    });
  }
  gotoNext () {
    this.setState({
      currentImage: this.state.currentImage + 1,
    });
  }
  gotoImage (index) {
    this.setState({
      currentImage: index,
    });
  }
  handleClickImage () {
    if (this.state.currentImage === this.props.images.length - 1) return;

    this.gotoNext();
  }
  renderGallery () {
    const { images } = this.props;

    if (!images) return;

    const gallery = images.filter(i => i.useForDemo).map((obj, i) => {
      return (
         this.openLightbox(i, e)}
        >

      );
    });
  }

    render() {
            const {
            photoIndex,
            lightboxIsOpen,
            currentImage,
        } = this.state;

  return(

<Grid>
  <Row>
   <Col md={6} md={4} >
       this.setState({ lightboxIsOpen: true })} />
      {lightboxIsOpen &&
        <Lightbox
        images={[{ src: 'https://docs.google.com/uc?id=0B0huBtqYaof7WVNjMjNMZTY3UDg' }, { src: 'https://docs.google.com/uc?id=0B0huBtqYaof7c0dpVFdGbGl0MWs' }]}
        currentImage={this.state.currentImage}
        onClickImage={this.handleClickImage}
        isOpen={this.state.lightboxIsOpen}
        onClickPrev={this.gotoPrevious}
        onClickNext={this.gotoNext}
        onClose={this.closeLightbox}

      />

                }
    </Col>
     this.setState({ lightboxIsOpen: true })} />
  </Row>

</Grid>

    )
}
}

Body:
You should use map function

const imgs = [
    "//docs.google.com/uc?id=0B0huBtqYaof7WVNjMjNMZTY3UDg",
    "//docs.google.com/uc?id=0B0huBtqYaof7c0dpVFdGbGl0MWs"
]
const i;
imgs.map((entry, index) => i=index );
//then update your cunstructor
 constructor(props) {
        super(props);

        this.state = {
            photoIndex:i,
            isOpen: false
        };
    }


问:
AWS CloudTrail Lookup Events API
I am trying to use LookupEvents API using Postman as the user agent.
When I set filter in Body as raw Json, I am still getting all logs instead of just one. Any Idea how to do this?
Method: Post
Content-type: application/json
or
Content-type: application/x-amz-json-1.0
I also tried raw body to as text/json.</p>

```<code>{
    "LookupAttributes": [
      {
         "AttributeKey": "EventName",
         "AttributeValue": "ConsoleLogin"
      }
    ],
    "MaxResults": 1
}
</code>```

答:
What a poorly documented API!  I eventually got this working, but the steps weren't easy to find.

Make sure your request:

Method is POST.

Has no query string parameters

Includes Content-Type of application/x-amz-json-1.1.

Contains an x-amz-target header with value com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.LookupEvents.

The "Common Parameters" documentation is a little misleading, as it seems to imply that Action belongs in the query string.  It does not.

In practice, having Action in the query string seems to bring back events with any EventName, and does not restrict the number of results.  It's as if the entire request body is ignored.

cURL command, with AWS signature stuff removed:

```<code>curl --location --request POST 'https://cloudtrail.us-east-1.amazonaws.com' \
--header 'Content-Type: application/x-amz-json-1.1' \
--header 'Accept: application/json' \
--header 'x-amz-target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.LookupEvents' \
--data-raw '{
    "LookupAttributes": [
      {
         "AttributeKey": "EventName",
         "AttributeValue": "ConsoleLogin"
      }
    ],
    "MaxResults": 2
}'
</code>```

I couldn't find the x-amz-target documented anywhere.  To get the value, I set up mitmproxy and looked at the calls generated by CLI commands.

Title: AWS CloudTrail Lookup Events API

Body:
I am trying to use LookupEvents API using Postman as the user agent.
When I set filter in Body as raw Json, I am still getting all logs instead of just one. Any Idea how to do this?
Method: Post
Content-type: application/json
or
Content-type: application/x-amz-json-1.0
I also tried raw body to as text/json.

{
    "LookupAttributes": [
      {
         "AttributeKey": "EventName",
         "AttributeValue": "ConsoleLogin"
      }
    ],
    "MaxResults": 1
}

Body:
What a poorly documented API!  I eventually got this working, but the steps weren't easy to find.

Make sure your request:

Method is POST.

Has no query string parameters

Includes Content-Type of application/x-amz-json-1.1.

Contains an x-amz-target header with value com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.LookupEvents.

The "Common Parameters" documentation is a little misleading, as it seems to imply that Action belongs in the query string.  It does not.

In practice, having Action in the query string seems to bring back events with any EventName, and does not restrict the number of results.  It's as if the entire request body is ignored.

cURL command, with AWS signature stuff removed:

curl --location --request POST 'https://cloudtrail.us-east-1.amazonaws.com' \
--header 'Content-Type: application/x-amz-json-1.1' \
--header 'Accept: application/json' \
--header 'x-amz-target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.LookupEvents' \
--data-raw '{
    "LookupAttributes": [
      {
         "AttributeKey": "EventName",
         "AttributeValue": "ConsoleLogin"
      }
    ],
    "MaxResults": 2
}'

I couldn't find the x-amz-target documented anywhere.  To get the value, I set up mitmproxy and looked at the calls generated by CLI commands.


问:
How do I apply a mask to an image in a tf.data pipeline?
My tensorflow input pipeline is reading in images for use in a demosaicing network. Given an image tensor of dimension (H, W, 3), I want to produce a "mosaiced" image of dimension (H, W, 3) with 2/3 of the original information zeroed out. This means that I'd like to apply a mask to the array of image data. For example, a 2x2 image

```<code>[[ [R_11, G_11, B_11], [R_12, G_12, B_12] ],
 [ [R_21, G_21, B_21], [R_22, G_22, B_22] ]]
</code>```

should become

```<code>[[ [R_11, 0, 0], [0, G_12, 0] ],
 [ [0, G_21, 0], [0, 0, B_22] ]]
</code>```

via the element-wise mask

```<code>[[ [1, 0, 0], [0, 1, 0] ],
 [ [0, 1, 0], [0, 0, 1] ]].
</code>```

Of course, I'm not just dealing with 2x2 images, but with much larger images. The mask I'd like to apply is just a tiling of the 2x2 mask to meet the dimensions of the image. This is not hard to do in numpy, but when I try to operate on the tensors in my tf.data pipeline I get the error:

```<code>NotImplementedError: Cannot convert a symbolic Tensor (args_0:0) to a numpy array.
</code>```

from the following code:

```<code>def bayerize_3d(t_img):
    """
    Inputs:
        img: tensor of dimension [H, W, 3], where H and W are divisible by 2, color channels are RGB
    Outputs:
        bayer: bayerized version of img, a tensor of dimension [H, W, 3] (1/3 of the former information)
    """
    np_mask = np.zeros_like(t_img)
    np_mask[0::2, 0::2, 0] = 1
    np_mask[0::2, 1::2, 1] = 1
    np_mask[1::2, 0::2, 1] = 1
    np_mask[1::2, 1::2, 2] = 1
    t_mask = tf.convert_to_tensor(np_mask)

    t_bayer = tf.math.multiply(t_img, t_mask)

    return t_bayer
</code>```

For context, I'm using tensorflow 2, and I call bayerize_3d from the following:

```<code>def decode_img(img):
    """Taken from https://www.tensorflow.org/tutorials/load_data/images"""
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(img, channels=3)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    return img

def load_vimeo_data(data_dir, dir_list, bayer_option='3d'):
    """Loads Vimeo-90K training / test data as tensorflow dataset, returns tuple of x and y datasets
    data_dir - path to vimeo90k training / test dataset directory
    dir_list - path to file containing relative directory paths to use for this dataset
    bayerize - either '3d' or '4d' - should """
    # ugly python 3.5 workaround
    target_dir = str( pathlib.Path(data_dir) / 'sequences' )
    #directories = list(map(lambda x: str(x), target_dir.glob('*/*')))

    directories = []
    with open(dir_list, 'rt') as f:
        for line in f:
            directories.append(str(pathlib.Path(target_dir) / line.strip()))

    im1str = tf.constant('/im1.png')
    im2str = tf.constant('/im2.png')
    im3str = tf.constant('/im3.png')

    bayerize = None
    if bayer_option == '3d':
        bayerize = bayerize_3d
    elif bayer_option == '4d':
        bayerize = bayerize_4d

    def process_dir(dir_path):
        im1 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im1str])))
        im2 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im2str])))
        im3 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im3str])))
        return im1, im2, im3

    def bayerize_stack(im1, im2, im3):
        b_im1 = bayerize(im1)
        b_im2 = bayerize(im2)
        b_im3 = bayerize(im3)
        return tf.stack([b_im1, b_im2, b_im3], axis=0)

    def extract_middle(im1, im2, im3):
        im2 = tf.stack([im2], axis=0)
        return im2

    def process_stack(im1, im2, im3):
        return bayerize_stack(im1, im2, im3), extract_middle(im1, im2, im3)

    dirs = tf.data.Dataset.from_tensor_slices(directories)
    dirs_dataset = dirs.map(process_dir)
    # dataset is bayerized stack "labeled" with true middle frame
    dataset = dirs_dataset.map(process_stack)
    return dataset
</code>```

Surely there is an appropriate way to do this?

答:
The problem appears to come from trying to create the numpy array from the tensor.

My suggestion is to explicitly pass the image shape into your dataset pipeline and generate the numpy array with these known dimensions.

Alternatively you can set the shape of your input tensor e.g.

```<code>h = 500
w = 500
t_img.set_shape(h, w, 3)
np_mask = np.zeros(t_img.shape)
</code>```

Body:
My tensorflow input pipeline is reading in images for use in a demosaicing network. Given an image tensor of dimension (H, W, 3), I want to produce a "mosaiced" image of dimension (H, W, 3) with 2/3 of the original information zeroed out. This means that I'd like to apply a mask to the array of image data. For example, a 2x2 image

[[ [R_11, G_11, B_11], [R_12, G_12, B_12] ],
 [ [R_21, G_21, B_21], [R_22, G_22, B_22] ]]

should become

[[ [R_11, 0, 0], [0, G_12, 0] ],
 [ [0, G_21, 0], [0, 0, B_22] ]]

via the element-wise mask

[[ [1, 0, 0], [0, 1, 0] ],
 [ [0, 1, 0], [0, 0, 1] ]].

Of course, I'm not just dealing with 2x2 images, but with much larger images. The mask I'd like to apply is just a tiling of the 2x2 mask to meet the dimensions of the image. This is not hard to do in numpy, but when I try to operate on the tensors in my tf.data pipeline I get the error:

NotImplementedError: Cannot convert a symbolic Tensor (args_0:0) to a numpy array.

from the following code:

def bayerize_3d(t_img):
    """
    Inputs:
        img: tensor of dimension [H, W, 3], where H and W are divisible by 2, color channels are RGB
    Outputs:
        bayer: bayerized version of img, a tensor of dimension [H, W, 3] (1/3 of the former information)
    """
    np_mask = np.zeros_like(t_img)
    np_mask[0::2, 0::2, 0] = 1
    np_mask[0::2, 1::2, 1] = 1
    np_mask[1::2, 0::2, 1] = 1
    np_mask[1::2, 1::2, 2] = 1
    t_mask = tf.convert_to_tensor(np_mask)

    t_bayer = tf.math.multiply(t_img, t_mask)

    return t_bayer

For context, I'm using tensorflow 2, and I call bayerize_3d from the following:

def decode_img(img):
    """Taken from https://www.tensorflow.org/tutorials/load_data/images"""
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(img, channels=3)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    return img

def load_vimeo_data(data_dir, dir_list, bayer_option='3d'):
    """Loads Vimeo-90K training / test data as tensorflow dataset, returns tuple of x and y datasets
    data_dir - path to vimeo90k training / test dataset directory
    dir_list - path to file containing relative directory paths to use for this dataset
    bayerize - either '3d' or '4d' - should """
    # ugly python 3.5 workaround
    target_dir = str( pathlib.Path(data_dir) / 'sequences' )
    #directories = list(map(lambda x: str(x), target_dir.glob('*/*')))

    directories = []
    with open(dir_list, 'rt') as f:
        for line in f:
            directories.append(str(pathlib.Path(target_dir) / line.strip()))

    im1str = tf.constant('/im1.png')
    im2str = tf.constant('/im2.png')
    im3str = tf.constant('/im3.png')

    bayerize = None
    if bayer_option == '3d':
        bayerize = bayerize_3d
    elif bayer_option == '4d':
        bayerize = bayerize_4d

    def process_dir(dir_path):
        im1 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im1str])))
        im2 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im2str])))
        im3 = decode_img(tf.io.read_file(tf.strings.join([dir_path, im3str])))
        return im1, im2, im3

    def bayerize_stack(im1, im2, im3):
        b_im1 = bayerize(im1)
        b_im2 = bayerize(im2)
        b_im3 = bayerize(im3)
        return tf.stack([b_im1, b_im2, b_im3], axis=0)

    def extract_middle(im1, im2, im3):
        im2 = tf.stack([im2], axis=0)
        return im2

    def process_stack(im1, im2, im3):
        return bayerize_stack(im1, im2, im3), extract_middle(im1, im2, im3)

    dirs = tf.data.Dataset.from_tensor_slices(directories)
    dirs_dataset = dirs.map(process_dir)
    # dataset is bayerized stack "labeled" with true middle frame
    dataset = dirs_dataset.map(process_stack)
    return dataset

Surely there is an appropriate way to do this?

Body:
The problem appears to come from trying to create the numpy array from the tensor.

My suggestion is to explicitly pass the image shape into your dataset pipeline and generate the numpy array with these known dimensions.

Alternatively you can set the shape of your input tensor e.g.

h = 500
w = 500
t_img.set_shape(h, w, 3)
np_mask = np.zeros(t_img.shape)


问:
How To Assign A Number To A Line From An Array Using PHP
Here is the script as I am using it now:

```<code><?php
echo '<html><body>';

// Data from a flat file
$dataArray = file('text.dat');

// Get the current page
if (isset($_REQUEST['page'])) {
    $currentPage = $_REQUEST['page'];
} else {
    $currentPage = 'some default value';
}

// Pagination settings
$perPage = 3;
$numPages = ceil(count($dataArray) / $perPage);
if(!$currentPage || $currentPage > $numPages)
    $currentPage = 0;
$start = $currentPage * $perPage;
$end = ($currentPage * $perPage) + $perPage;

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}

if($currentPage > 0 && $currentPage < $numPages)
    echo '<a href="?page=' . ($currentPage - 1) . '">« Previous page</a><br>';
if($numPages > $currentPage && ($currentPage + 1) < $numPages)
    echo '<a href="?page=' . ($currentPage + 1) . '" class="right">Next page »</a><br>';

echo '</body></html>';
?>
</code>```

And here is the contents of text.dat

```<code>Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html
</code>```

Here is my question. There are Seven lines in this array. How can I display the line number (I think it is $key) next to my displayed link? I should end up a list of links, each with it own number like:

```<code>LINE NUMBER - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br />
</code>```

Thanks for any assistance.....

答:
I'm assuming you want the line number from the file and not the line number of the output.  If so, then change this:

```<code>// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}
</code>```

to something like this:

```<code>// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[$key] = $dataArray[$key];
}

foreach($pagedData AS $key => $item) {
    $item = explode('||', $item);
    echo $key+1 . ' - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}
</code>```

Body:
Here is the script as I am using it now:

<?php
echo '';

// Data from a flat file
$dataArray = file('text.dat');

// Get the current page
if (isset($_REQUEST['page'])) {
    $currentPage = $_REQUEST['page'];
} else {
    $currentPage = 'some default value';
}

// Pagination settings
$perPage = 3;
$numPages = ceil(count($dataArray) / $perPage);
if(!$currentPage || $currentPage > $numPages)
    $currentPage = 0;
$start = $currentPage * $perPage;
$end = ($currentPage * $perPage) + $perPage;

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo ''. $item[0] .'
';
}

if($currentPage > 0 && $currentPage < $numPages)
    echo '« Previous page
';
if($numPages > $currentPage && ($currentPage + 1) < $numPages)
    echo 'Next page »
';

echo '';
?>

And here is the contents of text.dat

Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html

Here is my question. There are Seven lines in this array. How can I display the line number (I think it is $key) next to my displayed link? I should end up a list of links, each with it own number like:

LINE NUMBER - '. $item[0] .'

Thanks for any assistance.....

Body:
I'm assuming you want the line number from the file and not the line number of the output.  If so, then change this:

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}

to something like this:

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[$key] = $dataArray[$key];
}

foreach($pagedData AS $key => $item) {
    $item = explode('||', $item);
    echo $key+1 . ' - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}


问:
Android Studio -- Double install the same project in android phone
I have an android studio project, when I connect my phone to the laptop and I install the application, it replace the old one, but I want 2 applications I want to install the new one modified with the old one because I need them both, And even if I try to change the name of the applications they replace the other one!</p>

答:
Android looks to the applicationId to know if you're installing the same application (replace) or not. The easiest way to have the same application installed twice, is to change the applicationId in your build.gradle file.

Reference: https://developer.android.com/studio/build/application-id


问:
How do I avoid ExUnit.start() error when running mix test
When I run mix test on my project, I get the following error and I don't understand why:

```<code>$ mix test
Compiling 2 files (.ex)

== Compilation error in file lib/myproject_web/controllers/email_controller_test.ex ==
** (RuntimeError) cannot use ExUnit.Case without starting the ExUnit application, please call ExUnit.start() or explicitly start the :ex_unit app
    expanding macro: ExUnit.Case.__using__/1
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
    (elixir 1.10.1) expanding macro: Kernel.use/2
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
</code>```

I already have a test_helper.exs file in lib/ which calls ExUnit.start(). My set up is unusual because I want the tests next to the modules rather than in a separate test folder.

答:
If you read the documentation of mix test:

This task starts the current application, loads up
  test/test_helper.exs and then requires all files matching the
  test/**/*_test.exs pattern in parallel.

You were right that .exs files are not compiled, however this is not a problem if they even were compiled. Tests are run as scripts to avoid repeatedly compilation, since they get randomized order every time, having different output compilation.

The task first compiles all the files, then starts the ExUnit and expands all the macros from *_test.exs scripts. To prove this take a look at this piece of code:

```<code>defmacro __using__(opts) do
    unless Process.whereis(ExUnit.Server) do
      raise "cannot use ExUnit.Case without starting the ExUnit application, " <>
              "please call ExUnit.start() or explicitly start the :ex_unit app"
    end
</code>```

This means that in files where you use use ExUnit.Case, the ExUnit server should be up and running at the moment when these scripts are interpreted.

In general in your case, even after changing to .exs your tests shouldn't have worked, since with default configuration the path for tests is:

```<code> defp default_test_paths do
    if File.dir?("test") do
      ["test"]
    else
      []
    end
</code>```

Instead you should have called the tests with:

```<code>mix test test/some/particular/file_test.exs
</code>```

Body:
When I run mix test on my project, I get the following error and I don't understand why:

$ mix test
Compiling 2 files (.ex)

== Compilation error in file lib/myproject_web/controllers/email_controller_test.ex ==
** (RuntimeError) cannot use ExUnit.Case without starting the ExUnit application, please call ExUnit.start() or explicitly start the :ex_unit app
    expanding macro: ExUnit.Case.__using__/1
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
    (elixir 1.10.1) expanding macro: Kernel.use/2
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)

I already have a test_helper.exs file in lib/ which calls ExUnit.start(). My set up is unusual because I want the tests next to the modules rather than in a separate test folder.

Body:
If you read the documentation of mix test:

This task starts the current application, loads up
  test/test_helper.exs and then requires all files matching the
  test/**/*_test.exs pattern in parallel.

You were right that .exs files are not compiled, however this is not a problem if they even were compiled. Tests are run as scripts to avoid repeatedly compilation, since they get randomized order every time, having different output compilation.

The task first compiles all the files, then starts the ExUnit and expands all the macros from *_test.exs scripts. To prove this take a look at this piece of code:

defmacro __using__(opts) do
    unless Process.whereis(ExUnit.Server) do
      raise "cannot use ExUnit.Case without starting the ExUnit application, " <>
              "please call ExUnit.start() or explicitly start the :ex_unit app"
    end

This means that in files where you use use ExUnit.Case, the ExUnit server should be up and running at the moment when these scripts are interpreted.

In general in your case, even after changing to .exs your tests shouldn't have worked, since with default configuration the path for tests is:

 defp default_test_paths do
    if File.dir?("test") do
      ["test"]
    else
      []
    end

Instead you should have called the tests with:

mix test test/some/particular/file_test.exs


问:
MissingMethodException while calling Groovy closure inside closure
I have a groovy script which looks similar like below:

```<code>def clouser = {
    def clouserOne = { _argsA  ->
        def clouserTwo = { _argsB ->
            // Do Something with _argsA and _argsB
            println(_argsA)
            println(_argsB)
        }
    }
}
</code>```

while calling this

```<code>clouser().clouserOne("A").clouserTwo("B")
</code>```

I am getting an error

```<code>groovy.lang.MissingMethodException: No signature of method: Script1.clouserOne() is applicable for argument types: (String) values: [A]
    at Script1.run(Script1.groovy:11)
</code>```

What is the correct way to define this kind of closure inside closure? And how to call it in a proper way?

答:
The problem with the original code is, that you are defining just some
local variables, that never get used.  Instead the assigned closure is
returned directly.

To make your original code work, you can call:

```<code>closure()("A")("B")
</code>```

(Each closure call returns the next closure and you just chain the
calls; of course there is no need to have the def clouserXXX in
there).

If you leave the only def out, you will create "global vars" and that is
most likely not what you want.

If you want to have the names in there, you have to return something
with the names.  One simple example is using maps as the return.  E.g.:

```<code>def closure = { ->
    [closureOne: { _argsA  ->
        [closureTwo: { _argsB ->
            println(_argsA)
            println(_argsB)
        }]
    }]
}

closure().closureOne("A").closureTwo("B")
</code>```

Body:
I have a groovy script which looks similar like below:

def clouser = {
    def clouserOne = { _argsA  ->
        def clouserTwo = { _argsB ->
            // Do Something with _argsA and _argsB
            println(_argsA)
            println(_argsB)
        }
    }
}

while calling this

clouser().clouserOne("A").clouserTwo("B")

I am getting an error

groovy.lang.MissingMethodException: No signature of method: Script1.clouserOne() is applicable for argument types: (String) values: [A]
    at Script1.run(Script1.groovy:11)

What is the correct way to define this kind of closure inside closure? And how to call it in a proper way?

Body:
The problem with the original code is, that you are defining just some
local variables, that never get used.  Instead the assigned closure is
returned directly.

To make your original code work, you can call:

closure()("A")("B")

(Each closure call returns the next closure and you just chain the
calls; of course there is no need to have the def clouserXXX in
there).

If you leave the only def out, you will create "global vars" and that is
most likely not what you want.

If you want to have the names in there, you have to return something
with the names.  One simple example is using maps as the return.  E.g.:

def closure = { ->
    [closureOne: { _argsA  ->
        [closureTwo: { _argsB ->
            println(_argsA)
            println(_argsB)
        }]
    }]
}

closure().closureOne("A").closureTwo("B")


问:
Windows Azure Node JS WEBSOCKET HandShake Fails 503 Error
I've deployed my nodeJS server in windows azure.
My client fails while connecting to server and handle the following error :

```<code>WebSocket connection to 'wss://ooplrfrfranode.azurewebsites.net/socket.io/1/websocket/lHrd-DOydinODjbS7-tc' failed: Error during WebSocket handshake: Unexpected response code: 503.
</code>```

Any Help please.
Thanks.

答:
For students struggling with socket.io on Azure

I've struggled for 2 days with this. I was using a student free tier for the service app and apparently that was part of the problem.

I made a B1 plan app service with my student credits. After uploading my node.js app it worked out of the box.

After that, I downscaled it to a free tier and it still works now(fingers crossed). This might help for students struggling with socket io on azure.

Body:
I've deployed my nodeJS server in windows azure.
My client fails while connecting to server and handle the following error :

WebSocket connection to 'wss://ooplrfrfranode.azurewebsites.net/socket.io/1/websocket/lHrd-DOydinODjbS7-tc' failed: Error during WebSocket handshake: Unexpected response code: 503.

Any Help please.
Thanks.


问:
Importing multiple React components into html
I am trying to inject some React code into an HTML document. I am following React's own documentation and feeding their starter code (a simple like button) into the page. Everything was working great. I changed it to use JSX, changed it to a functional component using hooks instead of a class component with state. No problems.

However, whenever I include an import call and try to bring in another component, the component breaks on the page and stops displaying, but doesn't throw any kind of error I can see.

How do I develop in a "react-y" way with components and modularity while injecting it into an html page?

Here is the code I'm working with at the moment:

HTML document

```<code><body>
  <div id="react-root"></div>

  <!-- inject react, reactDOM and JSX engine -->
  <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <!-- point to component -->
  <script src="transpiled/app.js"></script>
</body>
</code>```

React Component

```<code>'use strict';
import {SecondComponent} from './components/SecondComponent';

const e = React.createElement;

const LikeButton = () => {
  const [liked, setLiked] = React.useState(false);

  if (liked) return 'You liked this functional component.'

  const handleLikeClick = () => {
    setLiked(true);
  }

  return (
    <div>
      <button onClick={handleLikeClick}>new like button with jsx</button>
      {liked && <SecondComponent/>}
    </div>
  )
}

const domContainer = document.querySelector('#react-root');
ReactDOM.render(e(LikeButton), domContainer);
</code>```

Like I said, any sort of import statement seems to be where it breaks. Can't find resources online about it. Thanks in advance for your help!

答:
UPDATE: After a bit of research importing modules between several
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script data-plugins="transform-es2015-modules-umd" type="text/babel" src="./Header.js"></script>
  <script data-plugins="transform-es2015-modules-umd" type="text/babel" src="./App.js"></script>

```

Working Gist Example

Body:
I am trying to inject some React code into an HTML document. I am following React's own documentation and feeding their starter code (a simple like button) into the page. Everything was working great. I changed it to use JSX, changed it to a functional component using hooks instead of a class component with state. No problems.

However, whenever I include an import call and try to bring in another component, the component breaks on the page and stops displaying, but doesn't throw any kind of error I can see.

How do I develop in a "react-y" way with components and modularity while injecting it into an html page?

Here is the code I'm working with at the moment:

HTML document

React Component

'use strict';
import {SecondComponent} from './components/SecondComponent';

const e = React.createElement;

const LikeButton = () => {
  const [liked, setLiked] = React.useState(false);

  if (liked) return 'You liked this functional component.'

  const handleLikeClick = () => {
    setLiked(true);
  }

  return (

      <button onClick={handleLikeClick}>new like button with jsx</button>
      {liked && <SecondComponent/>}

  )
}

const domContainer = document.querySelector('#react-root');
ReactDOM.render(e(LikeButton), domContainer);

Like I said, any sort of import statement seems to be where it breaks. Can't find resources online about it. Thanks in advance for your help!

Body:
UPDATE: After a bit of research importing modules between several <script> tags is now possible.

This can be achieved adding the Babel Plugin attribute data-plugins and setting the value to "transform-es2015-modules-umd" which will enable  the UMD pattern.

You'll also need to set type="text/babel" on each <script> tag.

This will allow you to use the import statements directly inside each file. Like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React</title>
  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>

<body>
  <div id="root"></div>

  <script data-plugins="transform-es2015-modules-umd" type="text/babel" src="./Header.js"></script>
  <script data-plugins="transform-es2015-modules-umd" type="text/babel" src="./App.js"></script>
</body>

</html>

Working Gist Example


问:
Schema Using joigoose and mongoose for validation in node js
I am using @hapi/joi for validation in mongoose schema. I am converting joi object in mongoose schema using joigoose as follows :

import mongoose from 'mongoose';
import joi from '@hapi/joi';
const joigoose = require('joigoose')(mongoose);
let objectId = mongoose.Schema.Types.ObjectId;

let userInfo = joi.object().keys({
    userId: joi.string().required().alphanum().meta({ type: 'objectId' }),
    firstName: joi.string().required().min(4).max(20),
    lastName: joi.string(),
    birthDate: joi.date(),
    email: joi.string().email(),
    mobile: joi.number().max(10),
    isActive: joi.boolean()
})

let userInfoSchema = new mongoose.Schema(joigoose.convert(userInfo));
module.exports = mongoose.model('userInfoModel', userInfoSchema, 'userInfo');
```

This is throwing error as follows:

I am not able to figure out what is the problem.

答:
UPDATE: Joigoose has fixed this error in 7.0.0 version: https://github.com/yoitsro/joigoose/issues/36

Run the command below to list all dependencies of packages in your project's folder

```<code>npm list
</code>```

Find in the tree the joigoose and its dependencies:

```<code>+-- joigoose@6.2.0
| +-- @hapi/hoek@8.5.1 deduped
| `-- @hapi/joi@16.1.8 deduped
</code>```

Install the same version of @hapi/joi, by doing:

```<code>npm install @hapi/joi@16.1.8
</code>```

Unfortunately, until now, the latest version of joigoose is not compatible with @hapi/joi 17.x version.

Link: https://github.com/yoitsro/joigoose/issues

Body:
I am using @hapi/joi for validation in mongoose schema. I am converting joi object in mongoose schema using joigoose as follows :

import mongoose from 'mongoose';
import joi from '@hapi/joi';
const joigoose = require('joigoose')(mongoose);
let objectId = mongoose.Schema.Types.ObjectId;

let userInfo = joi.object().keys({
    userId: joi.string().required().alphanum().meta({ type: 'objectId' }),
    firstName: joi.string().required().min(4).max(20),
    lastName: joi.string(),
    birthDate: joi.date(),
    email: joi.string().email(),
    mobile: joi.number().max(10),
    isActive: joi.boolean()
})

let userInfoSchema = new mongoose.Schema(joigoose.convert(userInfo));
module.exports = mongoose.model('userInfoModel', userInfoSchema, 'userInfo');

This is throwing error as follows:

I am not able to figure out what is the problem.

Body:
UPDATE: Joigoose has fixed this error in 7.0.0 version: https://github.com/yoitsro/joigoose/issues/36

Run the command below to list all dependencies of packages in your project's folder

npm list

Find in the tree the joigoose and its dependencies:

+-- joigoose@6.2.0
| +-- @hapi/hoek@8.5.1 deduped
| `-- @hapi/joi@16.1.8 deduped

Install the same version of @hapi/joi, by doing:

npm install @hapi/joi@16.1.8

Unfortunately, until now, the latest version of joigoose is not compatible with @hapi/joi 17.x version.

Link: https://github.com/yoitsro/joigoose/issues