问:
Go build: build output "api" already exists and is a directory
I am trying to use CompileDaemon to hot reload a go project using Docker.

My folder structure looks like the below

```<code>my-api
 - server
   - main.go
 - Dockerfile
 - docker-compose.yml
 - Makefile
</code>```

This is the error I am getting:

go build github.com/firstApi/test-platform/lib/my-api/server: build output "server" already exists and is a directory

This is what my dockerfile looks like

```<code>FROM golang:1.12-stretch

ENV GO111MODULE=on
WORKDIR /go/src

COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .

RUN ["go", "get", "github.com/githubnemo/CompileDaemon"]

RUN go test ./... \
&& CGO_ENABLED=0 go build -v -a -installsuffix cgo -o /main server/main.go

ENTRYPOINT CompileDaemon -log-prefix=false -build="go build ./server" -command="./main"
</code>```

any ideas what I am doing wrong and what I need to change in order to fix this issue?

UPDATE*****

I tried the solution as suggested by the only answer but I now get the following error:

```<code>Could not start command:%!(EXTRA *errors.errorString=can't start command: fork/exec ./server: permission denied)
</code>```

答: Your default go build is attempting to output the same name as the directory. You could change your build and ENTRYPOINT line to refer to "go build -o apiserver".</p>

Body:
I am trying to use CompileDaemon to hot reload a go project using Docker.

My folder structure looks like the below

my-api
 - server
   - main.go
 - Dockerfile
 - docker-compose.yml
 - Makefile

This is the error I am getting:

go build github.com/firstApi/test-platform/lib/my-api/server: build output "server" already exists and is a directory

This is what my dockerfile looks like

FROM golang:1.12-stretch

ENV GO111MODULE=on
WORKDIR /go/src

COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .

RUN ["go", "get", "github.com/githubnemo/CompileDaemon"]

RUN go test ./... \
&& CGO_ENABLED=0 go build -v -a -installsuffix cgo -o /main server/main.go

ENTRYPOINT CompileDaemon -log-prefix=false -build="go build ./server" -command="./main"

any ideas what I am doing wrong and what I need to change in order to fix this issue?

UPDATE*****

I tried the solution as suggested by the only answer but I now get the following error:

Could not start command:%!(EXTRA *errors.errorString=can't start command: fork/exec ./server: permission denied)


来源: stackexchange

问:
What is the algorithm to compute the Amazon-S3 Etag for a file larger than 5GB?
Files uploaded to Amazon S3 that are smaller than 5GB have an ETag that is simply the MD5 hash of the file, which makes it easy to check if your local files are the same as what you put on S3.

But if your file is larger than 5GB, then Amazon computes the ETag differently.

For example, I did a multipart upload of a 5,970,150,664 byte file in 380 parts. Now S3 shows it to have an ETag of 6bcf86bed8807b8e78f0fc6e0a53079d-380. My local file has an md5 hash of 702242d3703818ddefe6bf7da2bed757. I think the number after the dash is the number of parts in the multipart upload.

I also suspect that the new ETag (before the dash) is still an MD5 hash, but with some meta data included along the way from the multipart upload somehow.

Does anyone know how to compute the ETag using the same algorithm as Amazon S3?

答:
node.js implementation -

const fs = require('fs');
const crypto = require('crypto');

const chunk = 1024 * 1024 * 5; // 5MB

const md5 = data => crypto.createHash('md5').update(data).digest('hex');

const getEtagOfFile = (filePath) => {
  const stream = fs.readFileSync(filePath);
  if (stream.length <= chunk) {
    return md5(stream);
  }
  const md5Chunks = [];
  const chunksNumber = Math.ceil(stream.length / chunk);
  for (let i = 0; i < chunksNumber; i++) {
    const chunkStream = stream.slice(i * chunk, (i + 1) * chunk);
    md5Chunks.push(md5(chunkStream));
  }

  return `${md5(Buffer.from(md5Chunks.join(''), 'hex'))}-${chunksNumber}`;
};

```

ContentLicense: CC BY-SA 4.0


问:
I want to create mutiple turtles in newly created class
I am given a problem where I have to create a simple object-oriented code that creates two turtles moving in opposite directions, but with my trial I am faced with unknown errors

I tried to initialize two variables turtle1 and turtle2 with self because I inherited Turtle and s

```<code>from turtle import *
class moveOpposite(Turtle):
    def __init__(self):
        self.setx=0
        self.sety=0
    def move(self):
        turtle1=self
        turtle2=self
        turtle1.forward(100)
        turtle2.forward(-100)

my_turtle=moveOpposite()
my_turtle.move()
</code>```

I didn't use self._go but my error says I did like this:

```<code>self._go(distance)
</code>```

I also didn't use self._position and etc but it also says I did and gives me an AttributeError

```<code>ende = self._position + self._orient * distance
AttributeError: 'moveOpposite' object has no attribute '_position'
</code>```

答:
I wouldn't inherit from Turtle, i.e. isa, in this situation as your object isn't a turtle but a pair of them.  I'd go with the contains approach instead:

```<code>from turtle import Screen, Turtle

class Zax():  # a la Dr. Suess
    def __init__(self):
        self.east_bound = Turtle('turtle')
        self.west_bound = Turtle('turtle')
        self.west_bound.setheading(180)

    def forward(self, distance):
        self.east_bound.forward(distance)
        self.west_bound.forward(distance)

    def right(self, angle):
        self.east_bound.right(angle)
        self.west_bound.right(angle)

    def left(self, angle):
        self.east_bound.left(angle)
        self.west_bound.left(angle)

screen = Screen()

zaxen = Zax()
zaxen.forward(100)

for _ in range(4):
    zaxen.forward(20)
    zaxen.right(90)

screen.exitonclick()
</code>```

Body:
I am given a problem where I have to create a simple object-oriented code that creates two turtles moving in opposite directions, but with my trial I am faced with unknown errors

I tried to initialize two variables turtle1 and turtle2 with self because I inherited Turtle and s

from turtle import *
class moveOpposite(Turtle):
    def __init__(self):
        self.setx=0
        self.sety=0
    def move(self):
        turtle1=self
        turtle2=self
        turtle1.forward(100)
        turtle2.forward(-100)

my_turtle=moveOpposite()
my_turtle.move()

I didn't use self._go but my error says I did like this:

self._go(distance)

I also didn't use self._position and etc but it also says I did and gives me an AttributeError

ende = self._position + self._orient * distance
AttributeError: 'moveOpposite' object has no attribute '_position'

Body:
I wouldn't inherit from Turtle, i.e. isa, in this situation as your object isn't a turtle but a pair of them.  I'd go with the contains approach instead:

from turtle import Screen, Turtle

class Zax():  # a la Dr. Suess
    def __init__(self):
        self.east_bound = Turtle('turtle')
        self.west_bound = Turtle('turtle')
        self.west_bound.setheading(180)

    def forward(self, distance):
        self.east_bound.forward(distance)
        self.west_bound.forward(distance)

    def right(self, angle):
        self.east_bound.right(angle)
        self.west_bound.right(angle)

    def left(self, angle):
        self.east_bound.left(angle)
        self.west_bound.left(angle)

screen = Screen()

zaxen = Zax()
zaxen.forward(100)

for _ in range(4):
    zaxen.forward(20)
    zaxen.right(90)

screen.exitonclick()


问:
Why doesn't my use of "protected" work?
I have read that a protected member can be accessed from derived classes, but the following does not work.</p>

```<code>class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}
</code>```

答:
I have read that a protected member can be accessed from derived classes. Why my does my use of “protected” not work?

This is illegal because you have not provided a guarantee that you are accessing data of an instance of "B".  Consider this similar case:

```<code>abstract class BankAccount
{
    protected int accountNumber;
}
class SwissBankAccount : BankAccount
{
}
--- in another assembly, evil-doers write ---
class EvilBankAccount : BankAccount
{
    void DoEvil()
    {
        BankAccount b = GetASwissBankAccount();
        int number = b.accountNumber;
    }
}
</code>```

EvilBankAccount does not inherit from SwissBankAccount, so SwissBankAccount's protected member is not allowed to be used inside EvilBankAccount. You're allowed to access the protected members of your "parents", but not your "siblings"! EvilBankAccount can only access protected members of EvilBankAccount (or a type derived from EvilBankAccount). SwissBankAccount's protected members are off-limits.

The rule is that the type of the "receiver" expression that the protected instance member is accessed through has to be at least as derived as the type declaration containing the member access.  For the precise wording of the rule and some illustrative examples see section 3.5.3 of the C# 4.0 specification.

Incidentally, C++ also has this rule.

This rule is frequently misunderstood. For a more in-depth analysis of this rule and some of the other consequences of protected access, see my articles on the subject. The most germane articles I've written on this subject are this one and this one. There are a bunch more articles I've written on related topics here (though some of them wander off the topic of protected access itself and onto the topic of how to use protected access to build a data model with parent references.)

ContentLicense: CC BY-SA 3.0

Title: Why doesn't my use of "protected" work?

Body:
I have read that a protected member can be accessed from derived classes, but the following does not work.

class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}

Body:
I have read that a protected member can be accessed from derived classes. Why my does my use of “protected” not work?

This is illegal because you have not provided a guarantee that you are accessing data of an instance of "B".  Consider this similar case:

abstract class BankAccount
{
    protected int accountNumber;
}
class SwissBankAccount : BankAccount
{
}
--- in another assembly, evil-doers write ---
class EvilBankAccount : BankAccount
{
    void DoEvil()
    {
        BankAccount b = GetASwissBankAccount();
        int number = b.accountNumber;
    }
}

EvilBankAccount does not inherit from SwissBankAccount, so SwissBankAccount's protected member is not allowed to be used inside EvilBankAccount. You're allowed to access the protected members of your "parents", but not your "siblings"! EvilBankAccount can only access protected members of EvilBankAccount (or a type derived from EvilBankAccount). SwissBankAccount's protected members are off-limits.

The rule is that the type of the "receiver" expression that the protected instance member is accessed through has to be at least as derived as the type declaration containing the member access.  For the precise wording of the rule and some illustrative examples see section 3.5.3 of the C# 4.0 specification.

Incidentally, C++ also has this rule.

This rule is frequently misunderstood. For a more in-depth analysis of this rule and some of the other consequences of protected access, see my articles on the subject. The most germane articles I've written on this subject are this one and this one. There are a bunch more articles I've written on related topics here (though some of them wander off the topic of protected access itself and onto the topic of how to use protected access to build a data model with parent references.)


问:
How to get php vars to display in html
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

```<code>    <h4>Conference Registration</h4>
    <p><strong>
        <?php echo $confName $confDate; ?>
    </strong></p>
</code>```

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

答:
Use the concatenation operator .

```<code><?php echo $confName.$confDate; ?>
</code>```

Title: How to get php vars to display in html

Body:
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

Conference Registration

        <?php echo $confName $confDate; ?>

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

Body:
Use the concatenation operator .

<?php echo $confName.$confDate; ?>


问:
I have a race program in C that always has the same winner no matter what
The following program is controlled by named semaphores and is supposed to do this:

The main process creates N_PROC children and an id is assigned to each child (0 for the first child that has been created,1 for the second one and so on).

Each children waits for a signal from their father by using pause().

The main process sends his children a SIGUSR1 signal.

Each child repeats this until they die: they open a file (the same file for all children), write their id, close the file and then sleep during a random number of milliseconds between 1 and 100.

Each second, the main process opens the same file as his children, counts the number of times each id is present (printing them as he reads them) and, if a child has written its id 20 times, declares that child the winner, sends a SIGTERM to all his children, waits for them to finish and then deletes the semaphores.

My problem is that no matter how many times I recompile or rerun the program the parent always prints the same thing and thus child number 2 is always the winner.

Thank you in advance.

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <fcntl.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#define SEM1 "/example_sem1"
#define SEM2 "/example_sem2"
#define SEM3 "/example_sem3"

#define FFILE "ejercicio9.txt"

#define N_PROC 3

int valor_semaforo(sem_t *sem) {
    int sval;

    if (sem_getvalue(sem, &sval) == -1) {
        perror("sem_getvalue");
        sem_unlink(SEM1);
        sem_unlink(SEM2);
        sem_unlink(SEM3);
        exit(EXIT_FAILURE);
    }
    return sval;
}

int main(void) {
    sem_t *sem_write = NULL, *sem_read = NULL, *sem_count = NULL;
    pid_t pid[N_PROC];
    int i, numero, num[N_PROC], t;
    struct sigaction act;
    FILE *fp;
    srand(time(NULL) + getpid());

    if ((sem_write = sem_open(SEM1, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1)) == SEM_FAILED) {
        perror("sem_open");
        exit(EXIT_FAILURE);
    }
    if ((sem_read = sem_open(SEM2, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1)) == SEM_FAILED) {
        perror("sem_open");
        exit(EXIT_FAILURE);
    }
    if ((sem_count = sem_open(SEM3, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED) {
        perror("sem_open");
        exit(EXIT_FAILURE);
    }

    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    act.sa_handler = SIG_IGN;
    if (sigaction(SIGUSR1, &act, NULL) < 0) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < N_PROC; i++) {
        num[i] = 0;
        pid[i] = fork();
        if (pid[i] < 0) {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        if (pid[i] == 0) {
            pause();
            while (1) {
                sem_wait(sem_write);
                fp = fopen(FFILE, "a+");
                fprintf(fp, "%d ", i);
                fclose(fp);
                sem_post(sem_write);
                usleep(1 + (rand() % 100));
            }
        }
    }

    kill(0, SIGUSR1);
    while (1) {
        sleep(1);
        sem_wait(sem_read);
        sem_post(sem_count);
        if (valor_semaforo(sem_count) == 1)
            sem_wait(sem_write);
        sem_post(sem_read);

        fp = fopen(FFILE, "r");
        while (fscanf(fp, "%d", &numero) > 0) {
            printf("%d ", numero);
            fflush(stdout);
            for (i = 0; i < N_PROC; i++) {
                if (numero == i)
                    (num[i])++;
                if (num[i] == 20) {
                    printf("\nHa finalizado la carrera: el ganador es el proceso %d\n", i);
                    fflush(stdout);

                    act.sa_handler = SIG_IGN;
                    if (sigaction(SIGTERM, &act, NULL) < 0) {
                        perror("sigaction");
                        exit(EXIT_FAILURE);
                    }

                    kill(0, SIGTERM);
                    while (wait(NULL) > 0);
                    sem_close(sem_write);
                    sem_close(sem_read);
                    sem_close(sem_count);
                    sem_unlink(SEM1);
                    sem_unlink(SEM2);
                    sem_unlink(SEM3);
                    fclose(fp);
                    exit(EXIT_SUCCESS);
                }
            }
        }
    }

    printf("\n");
    fflush(stdout);
    fp = fopen(FFILE, "w+");
    fclose(fp);

    sem_wait(sem_read);
    sem_wait(sem_count);
    if (valor_semaforo(sem_count) == 0)
        sem_post(sem_write);
    sem_post(sem_read);
}
```

答:
You do not reset the num array before scanning the file. It happens that on your system the third child writes to the file first.

You should clear this array before parsing the file with:

```<code>memset(num, 0, sizeof num);
</code>```

Or

```<code>for (i = 0; i < N_PROC; i++)
    num[i] = 0;
</code>```

Body:
You do not reset the num array before scanning the file. It happens that on your system the third child writes to the file first.

You should clear this array before parsing the file with:

memset(num, 0, sizeof num);

Or

for (i = 0; i < N_PROC; i++)
    num[i] = 0;


问:
Insert new rows based on conditions - Oracle SQL
I have a table:

table1

```<code>unique_id       col_id      col_nm      col_val     sequ
1               1           testq 1     100         1
1               2           testc 1     abc         1
1               1           testq 1     101         2
1               2           testc 1     xyz         2
1               5           test 5      10          1
1               8           test 6      100         1

2               1           testq 1     100         1
2               2           testc 1     pqr         1
2               1           testq 1     101         2
2               2           testc 1     xxy         2
2               5           test 5      qqw         1
2               8           test 6      100         1
</code>```

I need to insert new rows in the table based on the following condition:

Find unique_id and sequ of col_id = 1 and col_nm = 'testq 1' and col_val = 100

Find col_val of col_id = 2 and col_nm = 'testc 1' and sequ = {sequ of step 1} and unique_id = {unique_id of step 1}.

Insert a new row for the corresponding unique_id, with col_id = 100, col_nm = 'test q100c', col_val = {col_val found in step 2}, sequ = {sequ found in step 2}

The output would be:

```<code>unique_id       col_id      col_nm      col_val     sequ
1               1           testq 1     100         1
1               2           testc 1     abc         1
1               1           testq 1     101         2
1               2           testc 1     xyz         2
1               5           test 5      10          1
1               8           test 6      100         1
1               100         test q100c  abc         1

2               1           testq 1     100         2
2               2           testc 1     pqr         2
2               1           testq 1     101         2
2               2           testc 1     xxy         2
2               5           test 5      qqw         1
2               8           test 6      100         1
2               100         test q100c  pqr         2
</code>```

Is there anyway in SQL to achieve this?

答:
We can use WITH clause in an INSERT … SELECT construct. So something like this?

```<code>insert into table1
with s1 as (
  select t.unique_id
         , t.sequ
  from table1 t
  where t.col_id = 1
  and t.col_nm = 'testq 1'
  and t.col_val = 100 )
  , s2 as (
     select s1.*
            , t.col_val
      from s1
           join table1 t
              on t.sequ = s1.sequ
              and t.unique_id = s1.unique_id
  where t.col_id = 2
  and t.col_nm = 'testc 1'
)
select s2.unique_id
       ,100 as col_id
       ,'test q100c' as col_nm
       ,s2.col_val
       ,s2.sequ
from s2
/
</code>```

I'm not sure I have entirely understood your rules - I used the col_val from step #2 (which is what your expected output shows) rather than the value from step #1 as your rule 3 states - but I hope this gives you a start. Also, this may not be a very efficient approach. I offer no guarantees regarding performance over a large volume of data.

Body:
I have a table:

table1

unique_id       col_id      col_nm      col_val     sequ
1               1           testq 1     100         1
1               2           testc 1     abc         1
1               1           testq 1     101         2
1               2           testc 1     xyz         2
1               5           test 5      10          1
1               8           test 6      100         1

2               1           testq 1     100         1
2               2           testc 1     pqr         1
2               1           testq 1     101         2
2               2           testc 1     xxy         2
2               5           test 5      qqw         1
2               8           test 6      100         1

I need to insert new rows in the table based on the following condition:

Find unique_id and sequ of col_id = 1 and col_nm = 'testq 1' and col_val = 100

Find col_val of col_id = 2 and col_nm = 'testc 1' and sequ = {sequ of step 1} and unique_id = {unique_id of step 1}.

Insert a new row for the corresponding unique_id, with col_id = 100, col_nm = 'test q100c', col_val = {col_val found in step 2}, sequ = {sequ found in step 2}

The output would be:

unique_id       col_id      col_nm      col_val     sequ
1               1           testq 1     100         1
1               2           testc 1     abc         1
1               1           testq 1     101         2
1               2           testc 1     xyz         2
1               5           test 5      10          1
1               8           test 6      100         1
1               100         test q100c  abc         1

2               1           testq 1     100         2
2               2           testc 1     pqr         2
2               1           testq 1     101         2
2               2           testc 1     xxy         2
2               5           test 5      qqw         1
2               8           test 6      100         1
2               100         test q100c  pqr         2

Is there anyway in SQL to achieve this?

Body:
We can use WITH clause in an INSERT … SELECT construct. So something like this?

insert into table1
with s1 as (
  select t.unique_id
         , t.sequ
  from table1 t
  where t.col_id = 1
  and t.col_nm = 'testq 1'
  and t.col_val = 100 )
  , s2 as (
     select s1.*
            , t.col_val
      from s1
           join table1 t
              on t.sequ = s1.sequ
              and t.unique_id = s1.unique_id
  where t.col_id = 2
  and t.col_nm = 'testc 1'
)
select s2.unique_id
       ,100 as col_id
       ,'test q100c' as col_nm
       ,s2.col_val
       ,s2.sequ
from s2
/

I'm not sure I have entirely understood your rules - I used the col_val from step #2 (which is what your expected output shows) rather than the value from step #1 as your rule 3 states - but I hope this gives you a start. Also, this may not be a very efficient approach. I offer no guarantees regarding performance over a large volume of data.


问:
Ignore specific CSP error when using sentry
I am using hash-based script-src CSP(v2), together with Sentry's report-uri in my site.

Recently I am getting lots of CSP violation report, specifically from latest version of Firefox (version 66 as of writing), creating lots of noise.

```<code>Recently Blocked 'script' from 'inline:'
</code>```

Testing with a firefox installation on my own computer, I found out that many addons actually inject inline script into DOM, thus triggering CSP error.

It is possible to ignore/mitigate this problem via CSP rule, or can I ignore all these firefox entries somehow via sdk or dashboard settings?

答: You can allow 'unsafe-inline' as a source, although doing so significantly weakens the security offered by CSP.  (If you need to use unsafe-inline, I believe you have to NOT use the hash, as the hash supersedes the 'inline' directive.)

Body:
I am using hash-based script-src CSP(v2), together with Sentry's report-uri in my site.

Recently I am getting lots of CSP violation report, specifically from latest version of Firefox (version 66 as of writing), creating lots of noise.

Recently Blocked 'script' from 'inline:'

Testing with a firefox installation on my own computer, I found out that many addons actually inject inline script into DOM, thus triggering CSP error.

It is possible to ignore/mitigate this problem via CSP rule, or can I ignore all these firefox entries somehow via sdk or dashboard settings?


问:
Importing multiple sheets from an excel file into multiple tables by sheet name
Hi there and thanks for your help. I'm putting together a seemingly simple Access data management solution for use in our office here and I'm having trouble as my background in vba is minimal at best.

What I have here are two related but disconnected Access 2007 applications and I need a system for the user to easily import and export this information. I've got a script working now to export all the tables from the application into a single excel file with each table as a different worksheet, the issue is that when I go to import it only seems to find the first sheet for import.

What I'm hoping to find is a method to iterate over each worksheet, grab the sheet name, and then merge that data into the table based on the sheet name.

To clarify:

Multiple copies of App A are sent to various departments

App A: Users enter information into the tables

App A: Users press command to run export macro

Excel file is created with each table as a sheet with matching names (e.g. tblCourse, tblStudent, tblFaculty, etc.)

Users of App B receive excel spreadsheet

App B: Users press command to run import script (This is the solution I'm looking for)

User is prompted for file location

Import script opens excel workbook

Script iterates over each sheet, reads name, and imports data to table of matching name

Thanks in advance for any help you can  provide, much appreciated.

Edit

Working script (Thanks greatly to grahamj42's help here):

```<code>Private Sub Command101_Click()

'Dim excelapp As New Excel.Application
Dim excelApp As Object
Set excelApp = CreateObject("Excel.Application")
'Dim excelbook As New Excel.Workbook
Dim excelbook As Object
Set excelbook = excelApp.Workbooks.Add
'Dim excelsheet As New Excel.Worksheet
'Dim excelsheet As Object
'Set excelsheet = excelbook.Sheets
Dim intNoOfSheets As Integer, intCounter As Integer
Dim strFilePath As String, strLastDataColumn As String
Dim strLastDataRow As String, strLastDataCell As String

strFilePath = "C:\Users\UserName\Documents\Export\DatabaseExport03-28-2013.xlsx"

Set excelbook = excelApp.Workbooks.Open(strFilePath)

 intNoOfSheets = excelbook.worksheets.Count

 Dim CurrSheetName As String

 For intCounter = 1 To intNoOfSheets
  excelbook.worksheets(intCounter).Activate
   DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, ActiveSheet.Name, _
   strFilePath, True, _
   excelbook.Worksheets(intCounter).Name & "!" & _
   Replace(excelbook.Worksheets(intCounter).UsedRange.Address, "$", "")
 Next

excelbook.Close
excelApp.Quit
Set excelApp = Nothing

End Sub
</code>```

Note that in the DoCmd.TransferSpreadsheet command there is a HasFieldNames property that is set to 'True' here because my spreadsheets export with the field names as column headers.

答:
I did a little combining of two different pieces of code, as I didn't want to hard code the location or file name. </p>

```<code>Dim excelApp As Object
Dim excelbook As Object
Dim dlg As FileDialog
Dim StrFileName As String, intcounter, intNoOfSheets As Integer

Set excelApp = CreateObject("Excel.Application")
Set dlg = Application.FileDialog(msoFileDialogFilePicker)

With dlg
    .Title = "Select the Excel file to import"
    .AllowMultiSelect = False
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsx", 1
    .Filters.Add "All Files", "*.*", 2

    If .Show = -1 Then

        StrFileName = .SelectedItems(1)
        Set excelbook = excelApp.Workbooks.Open(StrFileName)
        intNoOfSheets = excelbook.worksheets.Count
        'DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "COR Daily",     StrFileName, True
        For intcounter = 1 To intNoOfSheets
            excelbook.worksheets(intcounter).Activate
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8,     excelbook.Activesheet.Name, StrFileName, True, _
            excelbook.worksheets(intcounter).Name & "!" & _
            Replace(excelbook.worksheets(intcounter).UsedRange.Address, "$", "")

        Next

    Else
        Exit Function

    End If

End With
End Function
</code>```

Body:
Hi there and thanks for your help. I'm putting together a seemingly simple Access data management solution for use in our office here and I'm having trouble as my background in vba is minimal at best.

What I have here are two related but disconnected Access 2007 applications and I need a system for the user to easily import and export this information. I've got a script working now to export all the tables from the application into a single excel file with each table as a different worksheet, the issue is that when I go to import it only seems to find the first sheet for import.

What I'm hoping to find is a method to iterate over each worksheet, grab the sheet name, and then merge that data into the table based on the sheet name.

To clarify:

Multiple copies of App A are sent to various departments

App A: Users enter information into the tables

App A: Users press command to run export macro

Excel file is created with each table as a sheet with matching names (e.g. tblCourse, tblStudent, tblFaculty, etc.)

Users of App B receive excel spreadsheet

App B: Users press command to run import script (This is the solution I'm looking for)

User is prompted for file location

Import script opens excel workbook

Script iterates over each sheet, reads name, and imports data to table of matching name

Thanks in advance for any help you can  provide, much appreciated.

Edit

Working script (Thanks greatly to grahamj42's help here):

Private Sub Command101_Click()

'Dim excelapp As New Excel.Application
Dim excelApp As Object
Set excelApp = CreateObject("Excel.Application")
'Dim excelbook As New Excel.Workbook
Dim excelbook As Object
Set excelbook = excelApp.Workbooks.Add
'Dim excelsheet As New Excel.Worksheet
'Dim excelsheet As Object
'Set excelsheet = excelbook.Sheets
Dim intNoOfSheets As Integer, intCounter As Integer
Dim strFilePath As String, strLastDataColumn As String
Dim strLastDataRow As String, strLastDataCell As String

strFilePath = "C:\Users\UserName\Documents\Export\DatabaseExport03-28-2013.xlsx"

Set excelbook = excelApp.Workbooks.Open(strFilePath)

 intNoOfSheets = excelbook.worksheets.Count

 Dim CurrSheetName As String

 For intCounter = 1 To intNoOfSheets
  excelbook.worksheets(intCounter).Activate
   DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, ActiveSheet.Name, _
   strFilePath, True, _
   excelbook.Worksheets(intCounter).Name & "!" & _
   Replace(excelbook.Worksheets(intCounter).UsedRange.Address, "$", "")
 Next

excelbook.Close
excelApp.Quit
Set excelApp = Nothing

End Sub

Note that in the DoCmd.TransferSpreadsheet command there is a HasFieldNames property that is set to 'True' here because my spreadsheets export with the field names as column headers.

Body:
I did a little combining of two different pieces of code, as I didn't want to hard code the location or file name.

Dim excelApp As Object
Dim excelbook As Object
Dim dlg As FileDialog
Dim StrFileName As String, intcounter, intNoOfSheets As Integer

Set excelApp = CreateObject("Excel.Application")
Set dlg = Application.FileDialog(msoFileDialogFilePicker)

With dlg
    .Title = "Select the Excel file to import"
    .AllowMultiSelect = False
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsx", 1
    .Filters.Add "All Files", "*.*", 2

    If .Show = -1 Then

        StrFileName = .SelectedItems(1)
        Set excelbook = excelApp.Workbooks.Open(StrFileName)
        intNoOfSheets = excelbook.worksheets.Count
        'DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "COR Daily",     StrFileName, True
        For intcounter = 1 To intNoOfSheets
            excelbook.worksheets(intcounter).Activate
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8,     excelbook.Activesheet.Name, StrFileName, True, _
            excelbook.worksheets(intcounter).Name & "!" & _
            Replace(excelbook.worksheets(intcounter).UsedRange.Address, "$", "")

        Next

    Else
        Exit Function

    End If

End With
End Function


问:
Save a model with keras
I use the method save_model and load_mode but it don't work.

I have an error : AttributeError: 'GridSearchCV' object has no attribute 'get_config'
I don't know if I use correctly this method. I show my code for take an example:

```<code>gridSearch = GridSearchCV(estimator = classifier,
                          param_grid = parameters,
                          scoring = "accuracy",
                          cv = 10)
gridSearch.fit(X_train, y_train)
save_model(gridSearch, filepath = 'monModele.h5')
</code>```

The result is the error attribute Error. Can you help me to find a solution for this problem or to find an other method to save and load a keras model.

答:
That is because GridSearchCV is not a Keras model, but a module from sklearn that also has a fit function with a similar API.

In order to use save_model and load_model you need the actual Keras model, my guess is it is your classifier. Specifically, an instance of the Model class from Keras.

Title: Save a model with keras

Body:
I use the method save_model and load_mode but it don't work.

I have an error : AttributeError: 'GridSearchCV' object has no attribute 'get_config'
I don't know if I use correctly this method. I show my code for take an example:

gridSearch = GridSearchCV(estimator = classifier,
                          param_grid = parameters,
                          scoring = "accuracy",
                          cv = 10)
gridSearch.fit(X_train, y_train)
save_model(gridSearch, filepath = 'monModele.h5')

The result is the error attribute Error. Can you help me to find a solution for this problem or to find an other method to save and load a keras model.


问:
Bulk Text Editing
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

```<code>Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh
</code>```

Expected---------------

```<code>Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh
</code>```

答:
You task is possible using macro that will do the following.

From current row. Go to start of line (HOME).

Go down 10 rows (down arrow 10 times)

Mark all line (SHIFT-END)

Copy all line (CTRL-C)

Go back to origin line (up arrow 10 times)

Go to end of line. (END)

Add SPACE and paste marked data. ( SPACE CTRL-V)

Go down to beginning of next line. (down arrow, HOME)

Save the macro.

Run the macro again till satisfied.

Title: Bulk Text Editing

Body:
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh

Expected---------------

Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh


问:
How to predict with Word2Vec?
I'm doing arabic dialect text classification and I've used Word2Vec to train the model, I got this so far:

```<code> def read_input(input_file):

    with open (input_file, 'rb') as f:
        for i, line in enumerate (f):
            yield gensim.utils.simple_preprocess (line)

documents = list (read_input (data_file))
logging.info ("Done reading data file")

model = gensim.models.Word2Vec (documents, size=150, window=10, min_count=2, workers=10)
model.train(documents,total_examples=len(documents),epochs=10)
</code>```

What do I do now to predict a new text if it's of any of the 5 dialects I have?

Also, I looked around and found this code:

```<code># load the pre-trained word-embedding vectors
embeddings_index = {}
for i, line in enumerate(open('w2vmodel.vec',encoding='utf-8')):
    values = line.split()
    embeddings_index[values[0]] = numpy.asarray(values[1:], dtype='float32')

# create a tokenizer
token = text.Tokenizer()
token.fit_on_texts(trainDF['text'])
word_index = token.word_index

# convert text to sequence of tokens and pad them to ensure equal length vectors
train_seq_x = sequence.pad_sequences(token.texts_to_sequences(train_x), maxlen=70)
valid_seq_x = sequence.pad_sequences(token.texts_to_sequences(valid_x), maxlen=70)

# create token-embedding mapping
embedding_matrix = numpy.zeros((len(word_index) + 1, 300))
for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if embedding_vector is not None:
        embedding_matrix[i] = embedding_vector
</code>```

But it gives me this error when I run it and load my trained word2vec model:

```<code>ValueError: could not convert string to float: '\x00\x00\x00callbacksq\x04)X\x04\x00\x00\x00loadq\x05cgensim.utils'
</code>```

Note:

Actually, there's another code that I didn't post here, I wanted to use word2vec with neural networks, I have the code for neural network, but I don't know how to make the features I got from word2vec to be as an input to the neural net and with labels as output. Is it possible to connect word2vec to a deep neural net and how?

答:
Word2vec alone isn't something that would classify texts into dialects, so you haven't sketched out a plausible full approach here.

What made you think word2vec could or should be used as part of this task? (If there's a motivating theory-of-operation, or some other published precedent for this approach that gave you the idea, that could help guide what else should be done.)

What is your training data like?

If it's a large number of example texts, with accurate labels as to which dialect each text is from, have you tried classifiers working on simple bag-of-words or bag-of-character-n-grams representations of the texts? (By discovering relationships between the dialects, and the exact words, groups-of-words, or word-fragments in the texts, such a classifier might work far better than word2vec. Word2vec ignores word fragments, and drives the vectors of similar-meaning words close together, obscuring small differences in word-spelling or word-choice.)

You might also try:

FastText in classification mode, in which the word-vectors (and optionally, word-fragment-vectors) are trained to specifically be good at classifying amongst a set of known labels (rather than just to be good at predicting nearby words, as in classic word2vec

the technique of using multiple word2vec-models (one per dialect) as classifiers, as demonstrated in a notebook included with gensim: Deep Inverse Regression with Yelp Reviews

(Separately regarding your shown code:

you don't need to call train(documents,...) if you already supplied documents to the class-instantiation call – that will have already done training, as enabling INFO logging and watching the logs should make clear

you shouldn't need to use such code that tries to open/read your w2vmodel.vec file directly, because gensim includes methods for reading such files directly, such as .load_word2vec_format() or (if a full model was natively .save()d from gensim), just .load().

)

Title: How to predict with Word2Vec?

Body:
I'm doing arabic dialect text classification and I've used Word2Vec to train the model, I got this so far:

 def read_input(input_file):

    with open (input_file, 'rb') as f:
        for i, line in enumerate (f):
            yield gensim.utils.simple_preprocess (line)

documents = list (read_input (data_file))
logging.info ("Done reading data file")

model = gensim.models.Word2Vec (documents, size=150, window=10, min_count=2, workers=10)
model.train(documents,total_examples=len(documents),epochs=10)

What do I do now to predict a new text if it's of any of the 5 dialects I have?

Also, I looked around and found this code:

# load the pre-trained word-embedding vectors
embeddings_index = {}
for i, line in enumerate(open('w2vmodel.vec',encoding='utf-8')):
    values = line.split()
    embeddings_index[values[0]] = numpy.asarray(values[1:], dtype='float32')

# create a tokenizer
token = text.Tokenizer()
token.fit_on_texts(trainDF['text'])
word_index = token.word_index

# convert text to sequence of tokens and pad them to ensure equal length vectors
train_seq_x = sequence.pad_sequences(token.texts_to_sequences(train_x), maxlen=70)
valid_seq_x = sequence.pad_sequences(token.texts_to_sequences(valid_x), maxlen=70)

# create token-embedding mapping
embedding_matrix = numpy.zeros((len(word_index) + 1, 300))
for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if embedding_vector is not None:
        embedding_matrix[i] = embedding_vector

But it gives me this error when I run it and load my trained word2vec model:

ValueError: could not convert string to float: '\x00\x00\x00callbacksq\x04)X\x04\x00\x00\x00loadq\x05cgensim.utils'

Note:

Actually, there's another code that I didn't post here, I wanted to use word2vec with neural networks, I have the code for neural network, but I don't know how to make the features I got from word2vec to be as an input to the neural net and with labels as output. Is it possible to connect word2vec to a deep neural net and how?


问:
Text in front and image at background at back inside the specific div
I'm trying to create a div where it has front text and background image.

So far, here's my basic html

Hello World

```

Here is what the result I get.

But I want something like this from Microsoft word.

I hope somebody helps me. Thank you in advance

答:
Here is a way to do it with background-image and a single html element.

.footer-field {
    width: 190px;
    height: 190px;
    display: grid;
    align-items: center;
    text-align: center;
    color: red;
    background-size: cover;
    background-image: url(https://images.unsplash.com/photo-1559157693-c34156e0f8c3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-field">Centered Text</div></code>```

Body:
I'm trying to create a div where it has front text and background image.

So far, here's my basic html

Hello World

Here is what the result I get.

But I want something like this from Microsoft word.

I hope somebody helps me. Thank you in advance

Body:
Here is a way to do it with background-image and a single html element.

.footer-field {
    width: 190px;
    height: 190px;
    display: grid;
    align-items: center;
    text-align: center;
    color: red;
    background-size: cover;
    background-image: url(https://images.unsplash.com/photo-1559157693-c34156e0f8c3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80);
}

<div class="footer-field">Centered Text</div>


问:
Loading class through Jars in scala
I am trying to load a class from target Jar, I saw some examples and tried to replicate, but unfortunately i couldn't.

What am I doing wrong here:

```<code>import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)
</code>```

The class that is inside of jar is the following:

```<code>package typeLoader.testJars

class DummySimpleClass {

  def printer(): Unit = println("Hello World!")

}
</code>```

And the error that I got is:

```<code>java.lang.ClassNotFoundException: scala.typeLoader.testJars.DummySimpleClass.scala
  at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at efeawfew.JavaTest$.<init>(JavaTest.scala:13)
</code>```

Any ideas?

Edited: Added the jar path

答: According to your screenshot, your JAR file is not valid, it contains .scala file. Actual JAR file must contain .class file.

Title: Loading class through Jars in scala

Body:
I am trying to load a class from target Jar, I saw some examples and tried to replicate, but unfortunately i couldn't.

What am I doing wrong here:

import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)

The class that is inside of jar is the following:

package typeLoader.testJars

class DummySimpleClass {

  def printer(): Unit = println("Hello World!")

}

And the error that I got is:

java.lang.ClassNotFoundException: scala.typeLoader.testJars.DummySimpleClass.scala
  at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at efeawfew.JavaTest$.<init>(JavaTest.scala:13)

Any ideas?

Edited: Added the jar path


问:
Parse record (PCF) from Kafka using Kafka Kusto Sink
I've set-up my environment using docker based on this guide.

On kafka-console-producer I will send this line:

```<code>Hazriq|27|Undegrad|UNITEN
</code>```

I want this data to be ingested to Kusto like this:

```<code>+--------+-----+----------------+------------+
| Name   | Age | EducationLevel | University |
+--------+-----+----------------+------------+
| Hazriq | 27  | Undegrad       | UNITEN     |
+--------+-----+----------------+------------+

</code>```

Can this be handled by Kusto using the mapping (which I'm still trying to understand) or this should be catered by Kafka?

Tried @daniel suggestion:

```<code>.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.create table ParsedTable ingestion csv mapping 'ParsedTableMapping' '[{ "Name" : "name", "Ordinal" : 0},{ "Name" : "age", "Ordinal" : 1 },{ "Name" : "educationLevel", "Ordinal" : 2},{ "Name" : "univ", "Ordinal" : 3}]'

</code>```

```<code>kusto.tables.topics_mapping=[{'topic': 'kafkatopiclugiaparser','db': 'kusto-test', 'table': 'ParsedTable','format': 'psv', 'mapping':'ParsedTableMapping'}]
value.converter=org.apache.kafka.connect.storage.StringConverter
key.converter=org.apache.kafka.connect.storage.StringConverter
</code>```

but getting this instead:

```<code>+----------------------------+-----+----------------+------+
| Name                       | Age | EducationLevel | Univ |
+----------------------------+-----+----------------+------+
| Hazriq|27|Undergrad|UNITEN |     |                |      |
+----------------------------+-----+----------------+------+
</code>```

答:
ingestion of data as you've shown using the psv format is supported (see below) - it's probably just a matter of debugging why your client-side invocation of the underlying commands aren't yielding the expected result. if you could share the full flow and code, including parameters, it may be helpful.

```<code>.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.ingest inline into table ParsedTable with(format=psv) <| Hazriq|27|Undegrad|UNITEN

ParsedTable:

| name   | age | educationLevel | univ   |
|--------|-----|----------------|--------|
| Hazriq | 27  | Undegrad       | UNITEN |
</code>```

Body:
I've set-up my environment using docker based on this guide.

On kafka-console-producer I will send this line:

Hazriq|27|Undegrad|UNITEN

I want this data to be ingested to Kusto like this:

+--------+-----+----------------+------------+
| Name   | Age | EducationLevel | University |
+--------+-----+----------------+------------+
| Hazriq | 27  | Undegrad       | UNITEN     |
+--------+-----+----------------+------------+

Can this be handled by Kusto using the mapping (which I'm still trying to understand) or this should be catered by Kafka?

Tried @daniel suggestion:

.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.create table ParsedTable ingestion csv mapping 'ParsedTableMapping' '[{ "Name" : "name", "Ordinal" : 0},{ "Name" : "age", "Ordinal" : 1 },{ "Name" : "educationLevel", "Ordinal" : 2},{ "Name" : "univ", "Ordinal" : 3}]'

kusto.tables.topics_mapping=[{'topic': 'kafkatopiclugiaparser','db': 'kusto-test', 'table': 'ParsedTable','format': 'psv', 'mapping':'ParsedTableMapping'}]
value.converter=org.apache.kafka.connect.storage.StringConverter
key.converter=org.apache.kafka.connect.storage.StringConverter

but getting this instead:

+----------------------------+-----+----------------+------+
| Name                       | Age | EducationLevel | Univ |
+----------------------------+-----+----------------+------+
| Hazriq|27|Undergrad|UNITEN |     |                |      |
+----------------------------+-----+----------------+------+

Body:
ingestion of data as you've shown using the psv format is supported (see below) - it's probably just a matter of debugging why your client-side invocation of the underlying commands aren't yielding the expected result. if you could share the full flow and code, including parameters, it may be helpful.

.create table ParsedTable (name: string, age: int, educationLevel: string, univ:string)

.ingest inline into table ParsedTable with(format=psv) <| Hazriq|27|Undegrad|UNITEN

ParsedTable:

| name   | age | educationLevel | univ   |
|--------|-----|----------------|--------|
| Hazriq | 27  | Undegrad       | UNITEN |


问:
facebook customer chat messenger positioning
So i've installed the facebook customer chat messenger plugin on my website and it works fine, but i need to align it to the left of the website and if possible also change the size of the button (it's huge).

my code is:

```<code><script>(function(d, s, id) {
              var js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) return;
              js = d.createElement(s); js.id = id;
              js.src = 'https://connect.facebook.net/pt_PT/sdk/xfbml.customerchat.js';
              fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));</script>

<div class="fmessengerBtn">
<script>
    window.fbAsyncInit = function() {
        FB.init({
            xfbml: true,
            version : "v3.2"
        });
    };
    </script>
    <div id="fb-root"></div>
    <div class="fb-customerchat"
        attribution=setup_tool
        page_id="372545293082246"
        theme_color="#0b9bb8"
        greeting_dialog_display="fade"
        greeting_dialog_delay="60"
        ref="home"
        logged_in_greeting="Fale conosco"
        logged_out_greeting="Fale conosco">
    </div>
    </div>
</code>```

i've tried just using CSS to align the container div but then the chat window will stay on the right side of the website... Is there some sort of attribute or option to set the thing to go to the left side instead? Surely this is something lots of other people have needed to do

also, the greeting_dialog_delay option doesn't seem to be working

答:
I tweaked the code a bit in case you want to keep the widget on the bottom right but just move it over to the left some (e.g., it is blocking another element)

.fb_dialog.fb_dialog_advanced {
    right: 18pt;
  margin-right: 50px;
}
iframe.fb_customer_chat_bounce_in_v2 {
    right: 9pt;
   margin-right: 50px;
}
iframe.fb_customer_chat_bounce_out_v2 {
    right: 9pt;
   margin-right: 50px;
}```

Body:
So i've installed the facebook customer chat messenger plugin on my website and it works fine, but i need to align it to the left of the website and if possible also change the size of the button (it's huge).

my code is:

i've tried just using CSS to align the container div but then the chat window will stay on the right side of the website... Is there some sort of attribute or option to set the thing to go to the left side instead? Surely this is something lots of other people have needed to do

also, the greeting_dialog_delay option doesn't seem to be working


问:
How-to Keep an Android Activity Running when hitting the back key
I have an activity that essentially launches a CountDownTimer.  I need this to continue running while using other Android apps, such as Gmail, and media players etc.

When I hit the back button, my Activity seems to quit.  What do I need to do to keep it running when the user clicks the back/home keys etc.

答:
Activities are not supposed to be doing anything when they are not visible. They are basically UI components.

You should be looking into services. These can run as a background process nd contain no UI.


问:
When to use AWS Lambda and when to use Kubernetes (EKS)?
We are trying to evaluate the best ways to scale our J2EE web application and use hosting services with AWS.  Are there reasons why we would use the Lambda service over Kubernetes (EKS)?  Although it seems that Lambda can scale functional units, I'm not clear why anyone would use that as a substitute for Kubernetes, given Kubernetes can replicate containers based on performance metrics.</p>

答:
They serve different purposes. If you want to have horizontal scalability on a "ec2/pod/container" level and handle the availability yourself (through k8s of course), go for Kubernetes.

If you have a straight forward function doing a particular thing and you don't want to bother yourself with operating costs of having to manage a cluster or packaging it, then you can let Lambda administer it for you (at the time of writing, you would pay 20 US cents per million call). It is just another layer of abstraction on top of a system that is probably similar to Kubernetes, scaling your function per needs.

The goal of these technologies is to remove as much overhead as possible between you and the code and infrastructure can be painful. To summarize, serverless is to Kubernetes what Kubernetes is to containers.

To make a conscious decision, take the following into account:

Does your budget covers operation and maintenance of infrastructure

Do you have the expertise in Kubernetes

How much would it cost to redesign your J2EE app into serverless
ready code

Your timeline (of course...)

Based on the AWS resources you will use, how much do you save or not
by implementing a k8s cluster (database service?, EBS, EC2s, etc.)


问:
Change Order of Created Concatenated Column Variables
Here is my question - is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Below is how I arrived with this question.

I have the following code:

```<code>SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
</code>```

Which produces results that look like the following (this is abbreviated for space reasons):

```<code>[Financial Number] [Depart Date & Time] .. EventDisplay1 RequestedDateTime1
      1              2018-01-01 10:19:11     EP Exam     2018-01-01 11:19
      1              2018-01-01 10:19:11     Discharge   2018-01-01 12:20
      2              2018-01-01 13:49:11     EP Exam     2018-01-01 12:20
</code>```

I then add a query to the data query 1 produces:

```<code>Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RB WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RB WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RO WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RO WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RO WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RM WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RM WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RM WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]
</code>```

This query produces results that concatenate each row so each row is one unique Financial Number; however in doing so it messes up the alignment of the RequestedDateTime1 variable with the EventDisplay1 variable. For example, using the sample data above, the RequestedDateTime1 of 2018-01-01 12:20, which was aligned with DISCHARGE is now aligned with EP EXAM. I believe this is because the code orders the newly created EventDisplay1, EventDisplay2, EventDisplay3 variables in alphabetical order.

Example Results which are incorrect because the Discharge RequestedDateTime1 is aligned with the EP RequestedDateTime1:

```<code> [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11    Discharge         EP Exam 2018-01-01 11:19  2018-01-01 12:20
</code>```

Long story short, is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Desired Results:

```<code>   [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11     EP Exam        Discharge     2018-01-01 11:19  2018-01-01 12:20
</code>```

答:
You're getting mixed up with your row numbering. What you want to do is have one column of ordering - a single ROW_NUMBER statement that will give a number to the row. Then you want to pull all values when this row = 1, all values when this row = 2 etc... This way your data will make sense. All values from rowNumber1 will display as EventDisplay1, RequestedDateTime1 etc.

Updated query:

```<code>Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RN WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RN WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RN WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RN WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RN WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RN WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RN WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RN --choose whichever column you want to determine ordering here...
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]
</code>```

Body:
Here is my question - is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Below is how I arrived with this question.

I have the following code:

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED

Which produces results that look like the following (this is abbreviated for space reasons):

[Financial Number] [Depart Date & Time] .. EventDisplay1 RequestedDateTime1
      1              2018-01-01 10:19:11     EP Exam     2018-01-01 11:19
      1              2018-01-01 10:19:11     Discharge   2018-01-01 12:20
      2              2018-01-01 13:49:11     EP Exam     2018-01-01 12:20

I then add a query to the data query 1 produces:

Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RB WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RB WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RO WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RO WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RO WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RM WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RM WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RM WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]

This query produces results that concatenate each row so each row is one unique Financial Number; however in doing so it messes up the alignment of the RequestedDateTime1 variable with the EventDisplay1 variable. For example, using the sample data above, the RequestedDateTime1 of 2018-01-01 12:20, which was aligned with DISCHARGE is now aligned with EP EXAM. I believe this is because the code orders the newly created EventDisplay1, EventDisplay2, EventDisplay3 variables in alphabetical order.

Example Results which are incorrect because the Discharge RequestedDateTime1 is aligned with the EP RequestedDateTime1:

 [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11    Discharge         EP Exam 2018-01-01 11:19  2018-01-01 12:20

Long story short, is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Desired Results:

   [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11     EP Exam        Discharge     2018-01-01 11:19  2018-01-01 12:20

Body:
You're getting mixed up with your row numbering. What you want to do is have one column of ordering - a single ROW_NUMBER statement that will give a number to the row. Then you want to pull all values when this row = 1, all values when this row = 2 etc... This way your data will make sense. All values from rowNumber1 will display as EventDisplay1, RequestedDateTime1 etc.

Updated query:

Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RN WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RN WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RN WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RN WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RN WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RN WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RN WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RN --choose whichever column you want to determine ordering here...
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]


问:
First Item of fetched dropdown data in React doesn't get posted
Hi I fetch some data and use it to populate my dropdown list and then post it to my backend but I found out that only the first item doesn't get posted, all the other fetched data get posted along with the form.  I suspect it may be because it automatically selects the first value as the placeholder value, since it's only the first value not getting posted.

```<code>//where I fetch the data
 componentDidMount() {
    this.fetchOptions();
  },
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        this.setState({
          obj: json
        });
      });
  },
</code>```

```<code>//the handlechange method for the dropdown
handleCatChange() {
    var value = ReactDOM.findDOMNode(this.refs.categoryId).value;
    this.setState({
      categoryId: parseInt(value)
    });
  },
</code>```

```<code>//the dropdown list
 <div className="drop-down">

              <select
                ref="categoryId"
                onChange={this.handleCatChange}
                style={{ width: "82%" }}
              >
                {this.state.obj.map(obj => {
                  return (
                    <option
                      key={obj.id}
                      value={obj.id}

                    >
                      {obj.categoryName}
                    </option>
                  );
                })}
              </select>
            </div>
</code>```

I expect the first value to be sent to the backend if selected. Any help will be duly appreciated.

答:
I suspect you did not set the default categoryId at constructor

```<code>constructor(props) {
    super(props)
    this.state = {
       // Need to set default value for categoryId
       categoryId: 0  // or whatever value
    }
}
</code>```

handleCatChange() is called ONLY when user changes the dropdown value. If user do not interact with the dropdown, categoryId will remain as the default value.

To overcome this, after fetch API, set category ID using the first item

```<code>componentDidMount() {
  this.fetchOptions();
}
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        // Set the default category ID
        const categoryId = json[0].id
        this.setState({
          obj: json,
          categoryId: categoryId
        });
      });
  }
</code>```

Edit

```<code>//the handlechange method for the dropdown
handleCatChange(e) {
    var id = e.target.value;

    // Print the selected object
    const selectedObj = this.state.obj.find(obj => obj.id == id )
    console.log(selectedObj)

    this.setState({
      categoryId: parseInt(id)
    });
}

render() {
    return(
        <select
            ref="categoryId"
            onChange={this.handleCatChange.bind(this)}
            style={{ width: "82%" }} >
            // options here
        </select>
    )
}

</code>```

Body:
Hi I fetch some data and use it to populate my dropdown list and then post it to my backend but I found out that only the first item doesn't get posted, all the other fetched data get posted along with the form.  I suspect it may be because it automatically selects the first value as the placeholder value, since it's only the first value not getting posted.

//where I fetch the data
 componentDidMount() {
    this.fetchOptions();
  },
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        this.setState({
          obj: json
        });
      });
  },

//the handlechange method for the dropdown
handleCatChange() {
    var value = ReactDOM.findDOMNode(this.refs.categoryId).value;
    this.setState({
      categoryId: parseInt(value)
    });
  },

//the dropdown list

              <select
                ref="categoryId"
                onChange={this.handleCatChange}
                style={{ width: "82%" }}
              >
                {this.state.obj.map(obj => {
                  return (
                    <option
                      key={obj.id}
                      value={obj.id}

                    >
                      {obj.categoryName}
                    </option>
                  );
                })}
              </select>

I expect the first value to be sent to the backend if selected. Any help will be duly appreciated.

Body:
I suspect you did not set the default categoryId at constructor

constructor(props) {
    super(props)
    this.state = {
       // Need to set default value for categoryId
       categoryId: 0  // or whatever value
    }
}

handleCatChange() is called ONLY when user changes the dropdown value. If user do not interact with the dropdown, categoryId will remain as the default value.

To overcome this, after fetch API, set category ID using the first item

componentDidMount() {
  this.fetchOptions();
}
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        // Set the default category ID
        const categoryId = json[0].id
        this.setState({
          obj: json,
          categoryId: categoryId
        });
      });
  }

Edit

//the handlechange method for the dropdown
handleCatChange(e) {
    var id = e.target.value;

    // Print the selected object
    const selectedObj = this.state.obj.find(obj => obj.id == id )
    console.log(selectedObj)

    this.setState({
      categoryId: parseInt(id)
    });
}

render() {
    return(
        <select
            ref="categoryId"
            onChange={this.handleCatChange.bind(this)}
            style={{ width: "82%" }} >
            // options here
        </select>
    )
}


问:
How do you delete a firebase app from a previously deleted project?
I am using the spark plan for firebase, meaning that I have a limited number of apps allowed. I decided to delete the majority of them, but accidentally clicked "delete project" before I clicked "delete app". Now I have a bunch of apps counting toward my limit but no place to delete them from.

I have already tried going into different projects, general settings, and whatnot, as well as googling the problem and checking stack overflow. There doesn't seem to be an easy way to deal with the issue.

答: You could restore your Firebase project, delete the app from it, then delete the project again.  If you have problems with this, you can also reach out to Firebase support directly for assistance.</p>


问:
R troubleshoot script, why NULL
I try to process big file to get serial of total by offset position, all individual pieces work OK, but then I need to write result into file, for this exercise to get more skills I try first to put all of them into df and this doesn't work, I get NULL or other Error, what is wrong, please check my code.
I tried to use df[nrow(df) + 1,] = list( "x")

```<code>#  z <- readLines("C:\\RRR\\CA_Mild1.txt",warn=FALSE)
z <- c("A111111111111110111111711111111111", "B222222222222222222222222222222222")
z    # test sum by offset = OK
cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
cat("F2:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,15,17)))))),big.mark=","))
cat("F3:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,22,24)))))),big.mark=","))

     # trying now to write all results to df  and/or write to file        ERROR !!!
df <- data.frame(Value=character())    # create new df
df
df[nrow(df) + 1,] = list ( cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=",")) )
</code>```

even when I try to store single result in var  I'm getting NULL

```<code>a <- cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
a
> a <- cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
F1:   33
> a
NULL
</code>```

答:
Two changes will fix your code, I believe.

First, instead of cat use paste0. I'm not too familiar with cat, but paste0 will connect your strings together if that's what you want. Until I make that switch I get an error that the replacement has length 0.

Second, add stringsAsFactors = FALSE when you create your data frame:

df <- data.frame(Value=character(), stringsAsFactors = F)
```

<p>Until I do that, I get a second error, <code>invalid factor level, NA generated</code>. Which makes sense, because <code>Value</code> is by default a factor, and it has no levels!</p>

<hr>

<p>To find the <code>cat</code> / <code>paste0</code> issue, I thought I'd look closer at what it was you were trying to add to the data frame. I looked at your final line and ran this:</p>

<pre class="lang-r prettyprint-override"><code>class(
  cat(
    "F1:  ",
    format(
      sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),
      big.mark=","
    )
  )
)
</code>```

You get a really weird response:

```<code>F1:   33[1] "NULL"
</code>```

When we do the same thing with paste0 instead of cat, it's much simpler:

```<code>[1] "character"
</code>```

Title: R troubleshoot script, why NULL

Body:
I try to process big file to get serial of total by offset position, all individual pieces work OK, but then I need to write result into file, for this exercise to get more skills I try first to put all of them into df and this doesn't work, I get NULL or other Error, what is wrong, please check my code.
I tried to use df[nrow(df) + 1,] = list( "x")

#  z <- readLines("C:\\RRR\\CA_Mild1.txt",warn=FALSE)
z <- c("A111111111111110111111711111111111", "B222222222222222222222222222222222")
z    # test sum by offset = OK
cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
cat("F2:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,15,17)))))),big.mark=","))
cat("F3:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,22,24)))))),big.mark=","))

     # trying now to write all results to df  and/or write to file        ERROR !!!
df <- data.frame(Value=character())    # create new df
df
df[nrow(df) + 1,] = list ( cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=",")) )

even when I try to store single result in var  I'm getting NULL

a <- cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
a
> a <- cat("F1:  ", format(sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),big.mark=","))
F1:   33
> a
NULL

Body:
Two changes will fix your code, I believe.

First, instead of cat use paste0. I'm not too familiar with cat, but paste0 will connect your strings together if that's what you want. Until I make that switch I get an error that the replacement has length 0.

Second, add stringsAsFactors = FALSE when you create your data frame:

df <- data.frame(Value=character(), stringsAsFactors = F)

Until I do that, I get a second error, invalid factor level, NA generated. Which makes sense, because Value is by default a factor, and it has no levels!

To find the cat / paste0 issue, I thought I'd look closer at what it was you were trying to add to the data frame. I looked at your final line and ran this:

class(
  cat(
    "F1:  ",
    format(
      sum(as.numeric(sub(' ','0',(sub(' ','0',substr(z,5,6)))))),
      big.mark=","
    )
  )
)

You get a really weird response:

F1:   33[1] "NULL"

When we do the same thing with paste0 instead of cat, it's much simpler:

[1] "character"


问:
std::map<string, int> crashes when doing m[0]
The following crashes:

```<code>  std::map<std::string, int> m1{ {"0", 0}, { "1", 1 }};
  // auto melem = m1["0"]; // OK
  auto melem = m1[0];
</code>```

Why is that?

答:
Unfortunately (thanks C!) it is "possible" to construct a std::string from the integer 0, because it counts as a null pointer literal.

However, it's not really possible:

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

You got a crash because you tried to create a std::string from a null pointer.

At least with GCC the result of this contract violation is an [unhandled] exception with a descriptive name:

```<code>terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
</code>```

Unfortunately, though, you can't rely on this, and you don't get any warnings during build.

Body:
The following crashes:

  std::map<std::string, int> m1{ {"0", 0}, { "1", 1 }};
  // auto melem = m1["0"]; // OK
  auto melem = m1[0];

Why is that?

Body:
Unfortunately (thanks C!) it is "possible" to construct a std::string from the integer 0, because it counts as a null pointer literal.

However, it's not really possible:

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

You got a crash because you tried to create a std::string from a null pointer.

At least with GCC the result of this contract violation is an [unhandled] exception with a descriptive name:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid

Unfortunately, though, you can't rely on this, and you don't get any warnings during build.


问:
What is the best way to pass contextual information from a web app to bot-framework
I have a web application where users can raise or view IT tickets. I developed a chat bot using  Microsoft Bot Framework and C# to support specific cases. I embedded the bot with my website using an iframe from this documentation. Now i want to pass contextual information to my bot. For example when a user clicks on the web-chat i want to pass the user name and ticket it. What is the best way to do this?

I am aware that you can get specific channel data from several channels such as Slack or Facebook but is there a way to create my own custom channel?

答:
Unfortunately, you can't currently send any hidden information through the Web Chat channel.

What you can do is use the DirectLine channel along with the WebChat web control.  Then you can pass arbitrary data like your name and ticket id in the channel data object like is described in this sign-on experiences example.  Here they are sending an authentication token, but you can put whatever you want in channeldata.  You will need to parse it out in your bot, but it will be available.  This is quite a bit more involved than the WebChat channel, but there isn't currently another way to do it.