问:
Is it possible to hide/remove borders inside of intersected area of multiple divs?
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
  <div class="circle" id="one"></div>
  <div class="circle" id="two"></div>
  <div class="circle" id="three"></div>
</div></code>```

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

答:
As per your first query this is not possible to make intersect border invisible using CSS. However, if you want to achieve above design you can pseudo element trick to achieve this. You can create pseudo element to "#two" id and make it position absolute relative to the height and width of center div. You need to make little bit adjustment for sure. I have added snippet for you. Please try it.

.circle {
            position: absolute;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            border: 1px solid black;
          }

          #two {
            left: 50px;
            background: #fff;
          }

          #two:after {
            content: "";
            background: #fff;
            width: 100%;
            height: 88px;
            top: 6px;
            left: -2px;
            position: absolute;
            z-index: 9;
            -ms-transform: rotate(20deg);
            transform: rotate(.2deg);
          }

          #three {
            left: 100px;
            background: #fff;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
  <div class="circle" id="one"></div>
  <div class="circle" id="two"></div>
  <div class="circle" id="three"></div>
</div></code>```

Body:
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

Body:
As per your first query this is not possible to make intersect border invisible using CSS. However, if you want to achieve above design you can pseudo element trick to achieve this. You can create pseudo element to "#two" id and make it position absolute relative to the height and width of center div. You need to make little bit adjustment for sure. I have added snippet for you. Please try it.

.circle {
            position: absolute;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            border: 1px solid black;
          }

          #two {
            left: 50px;
            background: #fff;
          }

          #two:after {
            content: "";
            background: #fff;
            width: 100%;
            height: 88px;
            top: 6px;
            left: -2px;
            position: absolute;
            z-index: 9;
            -ms-transform: rotate(20deg);
            transform: rotate(.2deg);
          }

          #three {
            left: 100px;
            background: #fff;
          }

<div >
  <div class="circle" id="one"></div>
  <div class="circle" id="two"></div>
  <div class="circle" id="three"></div>
</div>


来源: stackexchange

问:
"if' and "else" being ignored
As per the title, my if/else below are not being considered — not sure why.

Here is my code:

```<code>cursor.execute("SELECT epic, MAX(timestamp) FROM market_data GROUP BY epic")

epics=(
"KA.D.MXUSLN.DAILY.IP",
"CS.D.BITCOIN.TODAY.IP",
"CS.D.CRYPTOB10.TODAY.IP")

for row in cursor:
    for epic in epics:
        # If epic exists in the market_data table then take the max timestamp and request new data with date1=maxtimestamp+1min and date2=now()
        if epic in row['epic']:
            date1 = row['max'] + datetime.timedelta(minutes=1)
            date2 = datetime.datetime.now()
        else:
            # if epic not already in market_data table then fresh new request with date1=now() and date2=now()+1min
            date1 = datetime.datetime.now()
            date2 = datetime.datetime.now() + datetime.timedelta(minutes=1)

            # URL PRODUCTION/LIVE Enviroment - demo most likely throttled and limited
        fmt = "https://example.com/" + str(epic) + "/1/MINUTE/batch/start/{date1:%Y/%m/%d/%H/%M/0/0}/end/{date2:%Y/%m/%d/%H/%M/%S/0}?format=json"
        # while date1 <= date2:
        url = fmt.format(epic, date1=date1, date2=date2)
        resp = requests.get(url, headers=headers)
        print(url)
</code>```

The output of cursor is:

CS.D.BITCOIN.TODAY.IP 2019-05-01 00:00:00
KA.D.MXUSLN.DAILY.IP 2020-02-14 14:26:00
```

<p>The code above outputs this:</p>

<pre class="lang-none prettyprint-override"><code>https://example.com/CS.D.BITCOIN.TODAY.IP/start/2019/05/01/00/01/0/0/end/2020/02/14/15/10/44/0?format=json
https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example/KA.D.MXUSLN.DAILY.IP/start/2020/02/14/14/27/0/0/end/2020/02/14/15/10/44/0?format=json

https://example.com/CS.D.BITCOIN.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json
</code>```

Note - as, epics "KA.D.MXUSLN.DAILY.IP" and "CS.D.BITCOIN.TODAY.IP are already in cursor, I expect the output  to just be:

https://example.com/CS.D.BITCOIN.TODAY.IP/start/2019/05/01/00/01/0/0/end/2020/02/14/15/10/44/0?format=json
https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example/KA.D.MXUSLN.DAILY.IP/start/2020/02/14/14/27/0/0/end/2020/02/14/15/10/44/0?format=json
```

Why aren't my if and else being considered?

答:
It is considered, but then you continue to iterate over the other epics anyway and print those too. You could use next instead of your inner for loop, if you find a match, remove it from the list of epics. and then any remaining epics can be handled afterwards as required

```<code>for row in cursor:
    epic = next(epic for epic in epics if epic in row["epic"])

    if epic is not None:
        date1 = row['max'] + datetime.timedelta(minutes=1)
        date2 = datetime.datetime.now()
        epics.remove(epic)
    else:
        date1 = datetime.datetime.now()
        date2 = datetime.datetime.now() + datetime.timedelta(minutes=1)

    # URL PRODUCTION/LIVE Enviroment - demo most likely throttled and limited
    fmt = "https://example.com/" + str(epic) + "/1/MINUTE/batch/start/{date1:%Y/%m/%d/%H/%M/0/0}/end/{date2:%Y/%m/%d/%H/%M/%S/0}?format=json"
    # while date1 <= date2:
    url = fmt.format(epic, date1=date1, date2=date2)
    resp = requests.get(url, headers=headers)
    print(url)
</code>```

Note: This leaves an issue where your fmt url will contain None, if there are no matches, not sure how you wish to handle this.

ContentLicense: CC BY-SA 4.0

Title: "if' and "else" being ignored

Body:
As per the title, my if/else below are not being considered — not sure why.

Here is my code:

cursor.execute("SELECT epic, MAX(timestamp) FROM market_data GROUP BY epic")

epics=(
"KA.D.MXUSLN.DAILY.IP",
"CS.D.BITCOIN.TODAY.IP",
"CS.D.CRYPTOB10.TODAY.IP")

for row in cursor:
    for epic in epics:
        # If epic exists in the market_data table then take the max timestamp and request new data with date1=maxtimestamp+1min and date2=now()
        if epic in row['epic']:
            date1 = row['max'] + datetime.timedelta(minutes=1)
            date2 = datetime.datetime.now()
        else:
            # if epic not already in market_data table then fresh new request with date1=now() and date2=now()+1min
            date1 = datetime.datetime.now()
            date2 = datetime.datetime.now() + datetime.timedelta(minutes=1)

            # URL PRODUCTION/LIVE Enviroment - demo most likely throttled and limited
        fmt = "https://example.com/" + str(epic) + "/1/MINUTE/batch/start/{date1:%Y/%m/%d/%H/%M/0/0}/end/{date2:%Y/%m/%d/%H/%M/%S/0}?format=json"
        # while date1 <= date2:
        url = fmt.format(epic, date1=date1, date2=date2)
        resp = requests.get(url, headers=headers)
        print(url)

The output of cursor is:

CS.D.BITCOIN.TODAY.IP 2019-05-01 00:00:00
KA.D.MXUSLN.DAILY.IP 2020-02-14 14:26:00

The code above outputs this:

https://example.com/CS.D.BITCOIN.TODAY.IP/start/2019/05/01/00/01/0/0/end/2020/02/14/15/10/44/0?format=json
https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example/KA.D.MXUSLN.DAILY.IP/start/2020/02/14/14/27/0/0/end/2020/02/14/15/10/44/0?format=json

https://example.com/CS.D.BITCOIN.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

Note - as, epics "KA.D.MXUSLN.DAILY.IP" and "CS.D.BITCOIN.TODAY.IP are already in cursor, I expect the output  to just be:

https://example.com/CS.D.BITCOIN.TODAY.IP/start/2019/05/01/00/01/0/0/end/2020/02/14/15/10/44/0?format=json
https://example.com/CS.D.CRYPTOB10.TODAY.IP/start/2020/02/14/15/10/0/0/end/2020/02/14/15/11/44/0?format=json

https://example/KA.D.MXUSLN.DAILY.IP/start/2020/02/14/14/27/0/0/end/2020/02/14/15/10/44/0?format=json

Why aren't my if and else being considered?

Body:
It is considered, but then you continue to iterate over the other epics anyway and print those too. You could use next instead of your inner for loop, if you find a match, remove it from the list of epics. and then any remaining epics can be handled afterwards as required

for row in cursor:
    epic = next(epic for epic in epics if epic in row["epic"])

    if epic is not None:
        date1 = row['max'] + datetime.timedelta(minutes=1)
        date2 = datetime.datetime.now()
        epics.remove(epic)
    else:
        date1 = datetime.datetime.now()
        date2 = datetime.datetime.now() + datetime.timedelta(minutes=1)

    # URL PRODUCTION/LIVE Enviroment - demo most likely throttled and limited
    fmt = "https://example.com/" + str(epic) + "/1/MINUTE/batch/start/{date1:%Y/%m/%d/%H/%M/0/0}/end/{date2:%Y/%m/%d/%H/%M/%S/0}?format=json"
    # while date1 <= date2:
    url = fmt.format(epic, date1=date1, date2=date2)
    resp = requests.get(url, headers=headers)
    print(url)

Note: This leaves an issue where your fmt url will contain None, if there are no matches, not sure how you wish to handle this.


问:
Perl angle brackets in regex substitution
I have encountered the following code:

```<code>my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;
</code>```

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

```<code>$string =~ s/(\d+)/$1\./g;
</code>```

What do angle brackets mean?

答:
The traditional way to change foo to bar in a string is to do this:

```<code>$string =~ s/foo/bar/;
</code>```

This is all well and good, but what if foo and bar contain lots of / characters?  For example, what if you want to change all instances of http:// to https://?  You'd have to escape out the / characters with \, and so you'd see something like this:

```<code>$string =~ s/http:\/\//https:\/\//;
</code>```

You have to admit that the above substitution is not easy on the eyes.  It's not so easy to tell which / belong to s/// and which belong to http://.  And the \ characters used to escape the / characters just make the whole line more difficult to understand.

Some people call this "Leaning Toothpick Syndrome," because all the / and \ characters look like leaning toothpicks.

The good news is that you're not required to use / when using s///.  There are many other characters you can use instead, which make the following lines equivalent to the one above:

```<code> $string =~ s#http://#https://#;
 $string =~ s@http://@https://@;
 $string =~ s!http://!https://!;
 $string =~ s|http://|https://|;
</code>```

Because the regular expression delimiter is no longer the default /, you no longer have to escape out the /, making the whole line much easier to read.

You would have to escape out whichever delimiter you use, so to avoid "Leaning Toothpick Syndrome" I would advise using a delimiter that does not appear in your expression.

There are many characters you can use as delimiters; I won't list them here.  However, there are four special bracket delimiters that come in pairs and surround your expressions, much like parentheses do.  They are:  ( and ), [ and ], { and }, and finally, < and >.  You use them like this:

```<code>$string =~ s(http://)(https://);
$string =~ s<foo><bar>g;
</code>```

A bit easier to read without all those toothpicks, isn't it?

Your substitution expression will be easier to read if the delimiter you use doesn't exist in the expression itself.  (Otherwise, you will have to escape it out with \.)

What's a little strange with the example you gave:

```<code>$string =~ s<(\d+)><$1\.>g;
</code>```

Is that there are no / characters anywhere in the expression, so presumably it's not any clearer than:

```<code>$string =~ s/(\d+)/$1\./g;
</code>```

However, maybe the original coder thought that the two \ characters would contrast with the / characters, and so wanted to avoid the / delimiters altogether.

Note:  You didn't ask about this, but the $1\. part of the substitution needlessly escapes out the . character.  You don't need the \ there, because the second part of a s/// substitution is not a regular expression -- it is only the replacement, and the . is never used there to match a character.  So there's no point in escaping it in your case, as . always means a literal . there.

So the above line would be better written as:

```<code>$string =~ s/(\d+)/$1./g;
</code>```

I hope this helps!

Body:
I have encountered the following code:

my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

$string =~ s/(\d+)/$1\./g;

What do angle brackets mean?

Body:
The traditional way to change foo to bar in a string is to do this:

$string =~ s/foo/bar/;

This is all well and good, but what if foo and bar contain lots of / characters?  For example, what if you want to change all instances of http:// to https://?  You'd have to escape out the / characters with \, and so you'd see something like this:

$string =~ s/http:\/\//https:\/\//;

You have to admit that the above substitution is not easy on the eyes.  It's not so easy to tell which / belong to s/// and which belong to http://.  And the \ characters used to escape the / characters just make the whole line more difficult to understand.

Some people call this "Leaning Toothpick Syndrome," because all the / and \ characters look like leaning toothpicks.

The good news is that you're not required to use / when using s///.  There are many other characters you can use instead, which make the following lines equivalent to the one above:

 $string =~ s#http://#https://#;
 $string =~ s@http://@https://@;
 $string =~ s!http://!https://!;
 $string =~ s|http://|https://|;

Because the regular expression delimiter is no longer the default /, you no longer have to escape out the /, making the whole line much easier to read.

You would have to escape out whichever delimiter you use, so to avoid "Leaning Toothpick Syndrome" I would advise using a delimiter that does not appear in your expression.

There are many characters you can use as delimiters; I won't list them here.  However, there are four special bracket delimiters that come in pairs and surround your expressions, much like parentheses do.  They are:  ( and ), [ and ], { and }, and finally, < and >.  You use them like this:

$string =~ s(http://)(https://);
$string =~ s<foo><bar>g;

A bit easier to read without all those toothpicks, isn't it?

Your substitution expression will be easier to read if the delimiter you use doesn't exist in the expression itself.  (Otherwise, you will have to escape it out with \.)

What's a little strange with the example you gave:

$string =~ s<(\d+)><$1\.>g;

Is that there are no / characters anywhere in the expression, so presumably it's not any clearer than:

$string =~ s/(\d+)/$1\./g;

However, maybe the original coder thought that the two \ characters would contrast with the / characters, and so wanted to avoid the / delimiters altogether.

Note:  You didn't ask about this, but the $1\. part of the substitution needlessly escapes out the . character.  You don't need the \ there, because the second part of a s/// substitution is not a regular expression -- it is only the replacement, and the . is never used there to match a character.  So there's no point in escaping it in your case, as . always means a literal . there.

So the above line would be better written as:

$string =~ s/(\d+)/$1./g;

I hope this helps!


问:
Using awt.Robot with Tomcat service
I am trying to simulate user input (keyboard) using Robot library from java.awt, and it is working on my development enviroment, but when deploying to Tomcat (installed as a service on a different machine), it wont work at all. My OS is Windows.

Is there any configuration that I am missing? I already tried "let tomcat interact with the desktop" option, changing users to run the service, changing java used by tomcat (from jre/ to jdk/jre/..), but still I can't make it work.

Also, if it is not possible, is there another way to achieve this?

答:
I finally solved this, not in the best way I guess.

I stopped Tomcat Service, and then started it from CMD as the current user.

Steps to open tomcat from cmd:

Open cmd.exe

Path-to-tomcat\bib\tomcat7.exe

And then opened my browser, went to the application, tried the proccess and the robot worked correctly!

I know this is not the best way as it can led to security issues, but I couldn't make it work using it as a Service because the different user sessiones (Session 0).

Title: Using awt.Robot with Tomcat service


问:
How to access Response Headers in the get api call - Angular 7
I'm trying to download the .csv file coming from the backend with specific filename. How can i access the filename from the api Response Header using Angular 7

my service (api call):

```<code> public getDownloadFile(masterDistributorId: number, runDate: string) {
    return this.http.get
      (`${environment.apiUrl}command-center/report/download/?
         masterDistributorId=${masterDistributorId}&runDate=${runDate}`, {
        headers: new HttpHeaders().append('Content-Type', 'application/csv'),
        responseType: 'blob',
        observe: 'response'
      }
      );
  }
</code>```

my subscribe call:

```<code> public Download(row: DistributorItem) {
    console.log(row.masterDistributorId);
    console.log(this.RunDate);
    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      console.log(res.headers);
      this.SaveFile(res);
    });
  }
</code>```

答:
Get response header value: Reading the full response

```<code>key = 'content-disposition';
contentDisposition = response.headers.get(key)
</code>```

Split header content disposition string: String.prototype.split()

```<code>filename = contentDisposition.split("=")[1];
</code>```

Your case:

```<code>    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      let filename = res.headers.get('content-disposition').split("=")[1];
      console.log(filename);
      this.SaveFile(res);
    });
</code>```

Body:
I'm trying to download the .csv file coming from the backend with specific filename. How can i access the filename from the api Response Header using Angular 7

my service (api call):

 public getDownloadFile(masterDistributorId: number, runDate: string) {
    return this.http.get
      (`${environment.apiUrl}command-center/report/download/?
         masterDistributorId=${masterDistributorId}&runDate=${runDate}`, {
        headers: new HttpHeaders().append('Content-Type', 'application/csv'),
        responseType: 'blob',
        observe: 'response'
      }
      );
  }

my subscribe call:

 public Download(row: DistributorItem) {
    console.log(row.masterDistributorId);
    console.log(this.RunDate);
    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      console.log(res.headers);
      this.SaveFile(res);
    });
  }

Body:
Get response header value: Reading the full response

key = 'content-disposition';
contentDisposition = response.headers.get(key)

Split header content disposition string: String.prototype.split()

filename = contentDisposition.split("=")[1];

Your case:

    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      let filename = res.headers.get('content-disposition').split("=")[1];
      console.log(filename);
      this.SaveFile(res);
    });


问:
find() blogs by category in mongoose not working with NodeJs
I'm making a blog application with mongodb database using mongoose framework, nodeJs with express and angular on front. Now I'm trying to create a component where all the blog categories from a category schema are fetched and then on clicking them all the blogs on blog schema having that categoryId on their category field should come up. When checking on db as db.blogs.find({'categoryId': 'TRxtZfez'}) all blogs having this particular categoryId are showing up nicely. But while checking on node controller function result.categoryId is fetching undefined

Node Function:

```<code>app.get(baseUrl+'view/by/category/:categoryId', (req, res) => {
    BlogModel.find({ 'categoryId': req.params.categoryId }, (err, result) => {
        if (err) {console.log(err)
            let apiResponse = response.generate(true, 'Failed to find category details', 500, null)
            res.send(apiResponse)
        } else if (result == undefined || result == null || result == '') {
            console.log('No Blog Found')
            let apiResponse = response.generate(true, 'No such category Found', 404, null)
            res.send(apiResponse)
        } else { let apiResponse = response.generate(false, 'All Blogs with category :: found Successfully', 200, result)
            console.log('BBB'+result.categoryId)  //getting undefined
            res.send(apiResponse)}})})
</code>```

How my blog database looks:

```<code>    {
        "error": false,
        "message": "All Blogs found Successfully",
        "status": 200,
        "data": [
            {
                "title": "MongoDB",
                "description": "MongoDB is a cross-platform document-oriented database program.",
                "imagePath": "uploads\\1581692172205slider2.png",
                "blogId": "K0llE03j",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            },
            {
                "title": "NodeJs",
                "imagePath": "uploads\\1581692310094shutterstock_339911378-350x350[1].jpg",
                "blogId": "zHi_CUpN",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            },
            {
                "title": "Angular",
                "description": "Angular is a platform for building mobile and desktop web applications.",
                "imagePath": "uploads\\1581692361330mp,550x550,gloss,ffffff,t.3u1[1].jpg",
                "blogId": "ft4w9LVY",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            }
</code>```

Category Database:

```<code>            "categoryName": "Sports",
            "categoryId": "rtBg1LCZ"
        },
        {
            "categoryName": "Movies",
            "categoryId": "zihrNEOP"
        },
        {
            "categoryName": "Technology",
            "categoryId": "TRxtZfez"
        }
</code>```

答:
If you are getting the result then to access categoryId, you should do:</p>

```<code>result.data[0].categoryId
//this will give you first object in the array.
</code>```

Body:
I'm making a blog application with mongodb database using mongoose framework, nodeJs with express and angular on front. Now I'm trying to create a component where all the blog categories from a category schema are fetched and then on clicking them all the blogs on blog schema having that categoryId on their category field should come up. When checking on db as db.blogs.find({'categoryId': 'TRxtZfez'}) all blogs having this particular categoryId are showing up nicely. But while checking on node controller function result.categoryId is fetching undefined

Node Function:

app.get(baseUrl+'view/by/category/:categoryId', (req, res) => {
    BlogModel.find({ 'categoryId': req.params.categoryId }, (err, result) => {
        if (err) {console.log(err)
            let apiResponse = response.generate(true, 'Failed to find category details', 500, null)
            res.send(apiResponse)
        } else if (result == undefined || result == null || result == '') {
            console.log('No Blog Found')
            let apiResponse = response.generate(true, 'No such category Found', 404, null)
            res.send(apiResponse)
        } else { let apiResponse = response.generate(false, 'All Blogs with category :: found Successfully', 200, result)
            console.log('BBB'+result.categoryId)  //getting undefined
            res.send(apiResponse)}})})

How my blog database looks:

    {
        "error": false,
        "message": "All Blogs found Successfully",
        "status": 200,
        "data": [
            {
                "title": "MongoDB",
                "description": "MongoDB is a cross-platform document-oriented database program.",
                "imagePath": "uploads\\1581692172205slider2.png",
                "blogId": "K0llE03j",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            },
            {
                "title": "NodeJs",
                "imagePath": "uploads\\1581692310094shutterstock_339911378-350x350[1].jpg",
                "blogId": "zHi_CUpN",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            },
            {
                "title": "Angular",
                "description": "Angular is a platform for building mobile and desktop web applications.",
                "imagePath": "uploads\\1581692361330mp,550x550,gloss,ffffff,t.3u1[1].jpg",
                "blogId": "ft4w9LVY",
                "categoryName": "Technology",
                "categoryId": "TRxtZfez"
            }

Category Database:

            "categoryName": "Sports",
            "categoryId": "rtBg1LCZ"
        },
        {
            "categoryName": "Movies",
            "categoryId": "zihrNEOP"
        },
        {
            "categoryName": "Technology",
            "categoryId": "TRxtZfez"
        }

Body:
If you are getting the result then to access categoryId, you should do:

result.data[0].categoryId
//this will give you first object in the array.


问:
How to easily merge a table to unique elements of itself?
I have this data frame:

```<code>df <- data.frame(group=rep(1:3,each=3),
                 question=c("1.1.1. question 1","1.1.1.1. question1 with conditional","2.2.2.2. question2 with condtional", "2.2.2. question2","1.1.1.10. question 1 with conditional","3.3.3. question 3","3.3.3.2. question 3 with conditional","2.2.2.1. question 2 with conditional","3.3.3. Descirbe section 2.8"),
                 answer=c("yes","no","text","no","text","hello","yes","text","yes"),
                 parent_question=c("1.1.1. question 1","1.1.1. question 1","2.2.2. question2","2.2.2. question2","1.1.1. question 1","3.3.3. question 3","3.3.3. question 3","2.2.2. question2","3.3.3. Descirbe section 2.8"),
                 answer_parent=c("yes","yes","","","","","yes","","yes"))
</code>```

What I want to do is create two new columns, called parent_question, and parent_answer.

So the parent_question to 1.1.1. is 1.1.1. and the parent question to 1.1.1.1. is 1.1.1. I know how do this by creating a parent_question dictionary and then merging it with this data set. And the parent_answer 1.1.1.1. is the answer to the parent_question 1.1.1. Is there an easy way to do this without creating a separate table for parent questions and parent answers and then merging them with the data?

答:
We can extract the pattern of numbers 1.1.1 or 1.1.1.1 from the start of the string with str_extract, create a logical 'flag', grouped by main question '1.1.1', '2.2.2', etc ('grp1'), create the 'p_q', 'p_a', by extracting the 'question/answer' where the 'flag' is TRUE.  If they are all FALSE, then return blank ("")

```<code>library(dplyr)
library(stringr)
out <- df %>%
   mutate(grp1 = str_extract(question, "^([0-9]+\\.){2}[0-9]+"),
         grp2 = str_remove(str_extract(question, "^[0-9.]+"), "\\.$"),
          flag = grp1 == grp2) %>%
   group_by(grp1) %>%
   mutate(parent_questionNew = question[which(flag)[1]]) %>%
   group_by(group, add = TRUE) %>%
   mutate(answer_parentNew = if(any(flag)) answer[which(flag & answer == "yes")[1]]
         else replace(as.character(answer), answer != "yes", "")) %>%
   ungroup
out %>%
 select(matches('parent'))
# A tibble: 9 x 4
#  parent_question             answer_parent parent_questionNew answer_parentNew
#  <fct>                       <fct>         <fct>              <chr>
#1 1.1.1. question 1           "yes"         1.1.1. question 1  "yes"
#2 1.1.1. question 1           "yes"         1.1.1. question 1  "yes"
#3 2.2.2. question2            ""            2.2.2. question2   ""
#4 2.2.2. question2            ""            2.2.2. question2    <NA>
#5 1.1.1. question 1           ""            1.1.1. question 1  ""
#6 3.3.3. question 3           ""            3.3.3. question 3   <NA>
#7 3.3.3. question 3           "yes"         3.3.3. question 3  "yes"
#8 2.2.2. question2            ""            2.2.2. question2   ""
#9 3.3.3. Descirbe section 2.8 "yes"         3.3.3. question 3  "yes"
</code>```

Body:
I have this data frame:

df <- data.frame(group=rep(1:3,each=3),
                 question=c("1.1.1. question 1","1.1.1.1. question1 with conditional","2.2.2.2. question2 with condtional", "2.2.2. question2","1.1.1.10. question 1 with conditional","3.3.3. question 3","3.3.3.2. question 3 with conditional","2.2.2.1. question 2 with conditional","3.3.3. Descirbe section 2.8"),
                 answer=c("yes","no","text","no","text","hello","yes","text","yes"),
                 parent_question=c("1.1.1. question 1","1.1.1. question 1","2.2.2. question2","2.2.2. question2","1.1.1. question 1","3.3.3. question 3","3.3.3. question 3","2.2.2. question2","3.3.3. Descirbe section 2.8"),
                 answer_parent=c("yes","yes","","","","","yes","","yes"))

What I want to do is create two new columns, called parent_question, and parent_answer.

So the parent_question to 1.1.1. is 1.1.1. and the parent question to 1.1.1.1. is 1.1.1. I know how do this by creating a parent_question dictionary and then merging it with this data set. And the parent_answer 1.1.1.1. is the answer to the parent_question 1.1.1. Is there an easy way to do this without creating a separate table for parent questions and parent answers and then merging them with the data?

Body:
We can extract the pattern of numbers 1.1.1 or 1.1.1.1 from the start of the string with str_extract, create a logical 'flag', grouped by main question '1.1.1', '2.2.2', etc ('grp1'), create the 'p_q', 'p_a', by extracting the 'question/answer' where the 'flag' is TRUE.  If they are all FALSE, then return blank ("")

library(dplyr)
library(stringr)
out <- df %>%
   mutate(grp1 = str_extract(question, "^([0-9]+\\.){2}[0-9]+"),
         grp2 = str_remove(str_extract(question, "^[0-9.]+"), "\\.$"),
          flag = grp1 == grp2) %>%
   group_by(grp1) %>%
   mutate(parent_questionNew = question[which(flag)[1]]) %>%
   group_by(group, add = TRUE) %>%
   mutate(answer_parentNew = if(any(flag)) answer[which(flag & answer == "yes")[1]]
         else replace(as.character(answer), answer != "yes", "")) %>%
   ungroup
out %>%
 select(matches('parent'))
# A tibble: 9 x 4
#  parent_question             answer_parent parent_questionNew answer_parentNew
#  <fct>                       <fct>         <fct>              <chr>
#1 1.1.1. question 1           "yes"         1.1.1. question 1  "yes"
#2 1.1.1. question 1           "yes"         1.1.1. question 1  "yes"
#3 2.2.2. question2            ""            2.2.2. question2   ""
#4 2.2.2. question2            ""            2.2.2. question2    <NA>
#5 1.1.1. question 1           ""            1.1.1. question 1  ""
#6 3.3.3. question 3           ""            3.3.3. question 3   <NA>
#7 3.3.3. question 3           "yes"         3.3.3. question 3  "yes"
#8 2.2.2. question2            ""            2.2.2. question2   ""
#9 3.3.3. Descirbe section 2.8 "yes"         3.3.3. question 3  "yes"


问:
There is already an object named in the database
Update-Database failed from Package Manager Console.
I've used Entity Framework 6.x and code-first approach.
Error is

"There is already an object named 'AboutUs' in the database."

How can I solve this problem?

```<code>internal sealed class Configuration
    : DbMigrationsConfiguration<Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext context)
    {

    }
}
</code>```

My DbContext is:

```<code>public class JahanBlogDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
{
    public JahanBlogDbContext()
        : base("name=JahanBlogDbConnectionString")
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<JahanBlogDbContext>());
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Comment>().HasRequired(t => t.Article).WithMany(t => t.Comments).HasForeignKey(d => d.ArticleId).WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
    }

    public virtual DbSet<Article> Articles { get; set; }
    public virtual DbSet<ArticleLike> ArticleLikes { get; set; }
    public virtual DbSet<ArticleTag> ArticleTags { get; set; }
    public virtual DbSet<AttachmentFile> AttachmentFiles { get; set; }
    public virtual DbSet<Comment> Comments { get; set; }
    public virtual DbSet<CommentLike> CommentLikes { get; set; }
    public virtual DbSet<CommentReply> CommentReplies { get; set; }
    public virtual DbSet<ContactUs> ContactUs { get; set; }
    public virtual DbSet<Project> Projects { get; set; }
    public virtual DbSet<ProjectState> ProjectStates { get; set; }
    public virtual DbSet<ProjectTag> ProjectTags { get; set; }
    public virtual DbSet<Rating> Ratings { get; set; }
    public virtual DbSet<Tag> Tags { get; set; }
    public virtual DbSet<AboutUs> AboutUs { get; set; }
}
</code>```

Package Manage Console:

```<code>PM> update-database -verbose -force
Using StartUp project 'Jahan.Blog.Web.Mvc'.
Using NuGet project 'Jahan.Blog.Web.Mvc'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Jahan-Blog' (DataSource: (local), Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201410101740197_AutomaticMigration.
CREATE TABLE [dbo].[AboutUs] (
    [Id] [int] NOT NULL IDENTITY,
    [Description] [nvarchar](max),
    [IsActive] [bit] NOT NULL,
    [CreatedDate] [datetime],
    [ModifiedDate] [datetime],
    CONSTRAINT [PK_dbo.AboutUs] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'AboutUs' in the database.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:88b66414-8776-45cd-a211-e81b2711c94b
There is already an object named 'AboutUs' in the database.
PM>
</code>```

答:
I was facing the same issue. I tried below solution :
1. deleted create table code from Up() and related code from Down() method
2. Run update-database command in Package Manager Consol

this solved my problem

ContentLicense: CC BY-SA 3.0

Body:
Update-Database failed from Package Manager Console.
I've used Entity Framework 6.x and code-first approach.
Error is

"There is already an object named 'AboutUs' in the database."

How can I solve this problem?

internal sealed class Configuration
    : DbMigrationsConfiguration<Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext context)
    {

    }
}

My DbContext is:

public class JahanBlogDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
{
    public JahanBlogDbContext()
        : base("name=JahanBlogDbConnectionString")
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<JahanBlogDbContext>());
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Comment>().HasRequired(t => t.Article).WithMany(t => t.Comments).HasForeignKey(d => d.ArticleId).WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
    }

    public virtual DbSet
 Articles { get; set; }
    public virtual DbSet<ArticleLike> ArticleLikes { get; set; }
    public virtual DbSet<ArticleTag> ArticleTags { get; set; }
    public virtual DbSet<AttachmentFile> AttachmentFiles { get; set; }
    public virtual DbSet<Comment> Comments { get; set; }
    public virtual DbSet<CommentLike> CommentLikes { get; set; }
    public virtual DbSet<CommentReply> CommentReplies { get; set; }
    public virtual DbSet<ContactUs> ContactUs { get; set; }
    public virtual DbSet<Project> Projects { get; set; }
    public virtual DbSet<ProjectState> ProjectStates { get; set; }
    public virtual DbSet<ProjectTag> ProjectTags { get; set; }
    public virtual DbSet<Rating> Ratings { get; set; }
    public virtual DbSet<Tag> Tags { get; set; }
    public virtual DbSet<AboutUs> AboutUs { get; set; }
}

Package Manage Console:

PM> update-database -verbose -force
Using StartUp project 'Jahan.Blog.Web.Mvc'.
Using NuGet project 'Jahan.Blog.Web.Mvc'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Jahan-Blog' (DataSource: (local), Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201410101740197_AutomaticMigration.
CREATE TABLE [dbo].[AboutUs] (
    [Id] [int] NOT NULL IDENTITY,
    [Description] [nvarchar](max),
    [IsActive] [bit] NOT NULL,
    [CreatedDate] [datetime],
    [ModifiedDate] [datetime],
    CONSTRAINT [PK_dbo.AboutUs] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'AboutUs' in the database.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:88b66414-8776-45cd-a211-e81b2711c94b
There is already an object named 'AboutUs' in the database.
PM>


问:
How to add a Vertical Divider between Widget on Column in Flutter?
Good day.

I've surfed on this website about how to add a Vertical Divider between Widget on Column in Flutter? but I got nothing.

here what I want

I already make the horizontal divider. but when I try to make a vertical divider that separating between 2 objects (text | image), I got nothing.

here are the code:

```<code>Row(children: <Widget>[
                Expanded(
                  child: new Container(
                      margin: const EdgeInsets.only(left: 10.0, right: 20.0),
                      child: Divider(
                        color: Colors.black,
                        height: 36,
                      )),
                ),
                Text("OR"),
                Expanded(
                  child: new Container(
                      margin: const EdgeInsets.only(left: 20.0, right: 10.0),
                      child: Divider(
                        color: Colors.black,
                        height: 36,
                      )),
                ),
              ]),
</code>```

code above is for horizontal

```<code>Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Row(
              children: <Widget>[
                Image.asset('images/makanan.png', width: 30,),
                Text('Diskon 20%', style: TextStyle(fontSize: 5, color: Colors.green),)
              ],
            ),
            VerticalDivider(
              color: Colors.red,
              width: 20,
            ),
            Row(
              children: <Widget>[
                Image.asset('images/makanan.png', width: 30,),
                Text('Diskon 20%', style: TextStyle(fontSize: 5, color: Colors.green),)
              ],
            ),
          ],
        ),
</code>```

code above I make for Vertical Divider. but failed.

Need your help,
Thank you.

答:
Try this:</p>

```<code>IntrinsicHeight(
    child: new Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: <Widget>[
    Text('Foo'),
    VerticalDivider(),
    Text('Bar'),
    VerticalDivider(),
    Text('Baz'),
  ],
))
</code>```

Body:
Good day.

I've surfed on this website about how to add a Vertical Divider between Widget on Column in Flutter? but I got nothing.

here what I want

I already make the horizontal divider. but when I try to make a vertical divider that separating between 2 objects (text | image), I got nothing.

here are the code:

Row(children: <Widget>[
                Expanded(
                  child: new Container(
                      margin: const EdgeInsets.only(left: 10.0, right: 20.0),
                      child: Divider(
                        color: Colors.black,
                        height: 36,
                      )),
                ),
                Text("OR"),
                Expanded(
                  child: new Container(
                      margin: const EdgeInsets.only(left: 20.0, right: 10.0),
                      child: Divider(
                        color: Colors.black,
                        height: 36,
                      )),
                ),
              ]),

code above is for horizontal

Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Row(
              children: <Widget>[
                Image.asset('images/makanan.png', width: 30,),
                Text('Diskon 20%', style: TextStyle(fontSize: 5, color: Colors.green),)
              ],
            ),
            VerticalDivider(
              color: Colors.red,
              width: 20,
            ),
            Row(
              children: <Widget>[
                Image.asset('images/makanan.png', width: 30,),
                Text('Diskon 20%', style: TextStyle(fontSize: 5, color: Colors.green),)
              ],
            ),
          ],
        ),

code above I make for Vertical Divider. but failed.

Need your help,
Thank you.

Body:
Try this:

IntrinsicHeight(
    child: new Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: <Widget>[
    Text('Foo'),
    VerticalDivider(),
    Text('Bar'),
    VerticalDivider(),
    Text('Baz'),
  ],
))


问:
Superscripts in WPF window title
I need to be able to superscript TM inside the title window of my page.How can i do that in XAML ?</p>

答:
Just use the Unicode trademark symbol, ™, in your window's Title attribute:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Super Awesome Main Window™">
</code>```

Title: Superscripts in WPF window title

Body:
Just use the Unicode trademark symbol, ™, in your window's Title attribute:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Super Awesome Main Window™">


问:
How to configure log4j for a Spark program running inside of Intellij?
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose. </p>

```<code>import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}
</code>```

答:
If you are using slf4j in your application you can use this XML to restrict all the logs</p>

```<code><?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="ERROR">
        <appender-ref ref="STDOUT"/>
    </root>

    <logger name="com.ning.http.client" level="ERROR"/>
</configuration>
</code>```

Body:
I've tried all possible suggestion on google but I still get spark log with INFO level which is too verbose.

import org.apache.log4j.{Level, LogManager, Logger}
import org.apache.spark.sql.SparkSession

object  tmp {

  def main(args: Array[String]): Unit = {
    val spark =  SparkSession.builder()
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    LogManager.getRootLogger.setLevel(Level.ERROR)
    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)

    Logger.getLogger("org").setLevel(Level.OFF)
    Logger.getLogger("akka").setLevel(Level.OFF)

    spark.read.json("/home/white/wk/tmp/people.json").show
  }
}

Body:
If you are using slf4j in your application you can use this XML to restrict all the logs

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="ERROR">
        <appender-ref ref="STDOUT"/>
    </root>

    <logger name="com.ning.http.client" level="ERROR"/>
</configuration>


问:
Resolving service for IHttpClientFactory fails on Azure Function
I am trying to inject IHttpClientFactory service on Azure Function v3, but I keep getting the following erorr saying resolving a service failed.
I use azure-functions-core-tools@v3 to run Azure Function locally.

```<code>[2/14/2020 5:45:19 PM] Executed 'Foo' (Failed, Id=24489b3b-af99-417e-b175-443b76c241d5)
[2/14/2020 5:45:19 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'MyFunction.Function.Foo'.
</code>```

I have a startup class that is supposed to inject a service for IHttpClientFactory.

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

namespace MyFunction
{
    public class Startup : FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
        }
    }
}
```

<p>And below is an azure function class that uses injected service of <code>IHttpClientFactory</code> to create a HTTP client and send a GET request to a server.</p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
    public class Foo
    {
        private readonly HttpClient httpClient;
        public Scrape(IHttpClientFactory httpClientFactory)
        {
            httpClient = httpClientFactory.CreateClient();
        }

        [FunctionName("Foo")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var result = await httpClient.GetAsync("https://google.com");
            var data = await result.Content.ReadAsStringAsync();
            return new OkObjectResult(data);
        }
    }
}
</code>```

Am I missing something?

答:
It looks like your startup.cs class is missing it's assembly reference?

```<code>[assembly: FunctionsStartup(typeof(MyFunction.Startup))]
</code>```

Try adding that to the startup class.  Add it just after your using statements at the top, and before any namespace declaration.

Also, most examples I have seen show the client actually created during function execution, not in the default constructor.

```<code>using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
    public class Foo
    {
        private readonly HttpClient httpClient;
        public Scrape(IHttpClientFactory httpClientFactory)
        {
            factory = httpClientFactory;
        }

        [FunctionName("Foo")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            HttpClient httpClient = factory.CreateClient();
            var result = await httpClient.GetAsync("https://google.com");
            var data = await result.Content.ReadAsStringAsync();
            return new OkObjectResult(data);
        }
    }
}
</code>```

Body:
I am trying to inject IHttpClientFactory service on Azure Function v3, but I keep getting the following erorr saying resolving a service failed.
I use azure-functions-core-tools@v3 to run Azure Function locally.

[2/14/2020 5:45:19 PM] Executed 'Foo' (Failed, Id=24489b3b-af99-417e-b175-443b76c241d5)
[2/14/2020 5:45:19 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'MyFunction.Function.Foo'.

I have a startup class that is supposed to inject a service for IHttpClientFactory.

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

namespace MyFunction
{
    public class Startup : FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
        }
    }
}

And below is an azure function class that uses injected service of IHttpClientFactory to create a HTTP client and send a GET request to a server.

using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
    public class Foo
    {
        private readonly HttpClient httpClient;
        public Scrape(IHttpClientFactory httpClientFactory)
        {
            httpClient = httpClientFactory.CreateClient();
        }

        [FunctionName("Foo")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var result = await httpClient.GetAsync("https://google.com");
            var data = await result.Content.ReadAsStringAsync();
            return new OkObjectResult(data);
        }
    }
}

Am I missing something?

Body:
It looks like your startup.cs class is missing it's assembly reference?

[assembly: FunctionsStartup(typeof(MyFunction.Startup))]

Try adding that to the startup class.  Add it just after your using statements at the top, and before any namespace declaration.

Also, most examples I have seen show the client actually created during function execution, not in the default constructor.

using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
    public class Foo
    {
        private readonly HttpClient httpClient;
        public Scrape(IHttpClientFactory httpClientFactory)
        {
            factory = httpClientFactory;
        }

        [FunctionName("Foo")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            HttpClient httpClient = factory.CreateClient();
            var result = await httpClient.GetAsync("https://google.com");
            var data = await result.Content.ReadAsStringAsync();
            return new OkObjectResult(data);
        }
    }
}


答:
```<code>import pandas as pd
d = pd.read_csv('TestingAccommodations.csv', encoding = 'ANSI')
q = dict(tuple(d.groupby('student_id')))

#%%

t1 =[]
t2 = []
t3 =[]
t4 =[]
t5 =[]
t6= []
t11 =[]
t12 =[]
t13 =[]
t14 = []
for k, v in q.items():
    t1.append(k)
    t2.append(v['last_nam'].iloc[0])
    t3.append(v['first_nam'].iloc[0])
    t4.append(v['school_dbn'].iloc[0])
    t5.append(v['official_class'].iloc[0])
    t6.append(v['grade_level'].iloc[0])
    t7 = []
    t8 = []
    t9 =[]
    t10 = []
    for i in v['Accommodation']:
        t7.append(i)
    for j in v['Description']:
        t8.append(j)
    for k in v['SpecificImpRecoms']:
        t9.append(k)
    for l in v['OtherAccommodation']:
        t10.append(l)
    t11.append(t7)
    t12.append(t8)
    t13.append(t9)
    t14.append(t10)
cols = d.columns.to_list()
new = pd.DataFrame({cols[0]:t1, cols[1]:t2,cols[2]:t3,cols[3]:t4,cols[4]:t5,cols[5]:t6,cols[6]:t11,
                    cols[7]:t12,cols[8]:t13,cols[9]:t14})
new.to_excel('new.xlsx',index = False)

#%%

new.columns
f = lambda x: 'Accomodation_{}'.format(x + 1)
op = pd.DataFrame(
    new.Accommodation.values.tolist(),
    new.index, dtype=str).fillna('').rename(columns=f)
f2 = lambda x: 'Description_{}'.format(x + 1)
op2 = pd.DataFrame(
    new.Description.values.tolist(),
    new.index, dtype=str).fillna('').rename(columns=f)
f3 = lambda x: 'SpecificImpRecoms_{}'.format(x + 1)
op3 = pd.DataFrame(
    new.SpecificImpRecoms.values.tolist(),
    new.index, dtype=str).fillna('').rename(columns=f)
f4 = lambda x: 'OtherAccommodation_{}'.format(x + 1)
op4 = pd.DataFrame(
    new.OtherAccommodation.values.tolist(),
    new.index, dtype=str).fillna('').rename(columns=f)

new2 = pd.concat([new,op,op2,op3,op4], axis = 1)
</code>```

Title: Split list into column

Body:
I have a df like

uid                                  services
000c80b7d2b3643689b1e516918ec193    ['A']
001b292c588ec6cc11f57324d40e422d    ['B','A',C']
006696f65899fdd87ba4894c784716f9    ['C','B']

(not ordered list in services column)

I'd like to remap the list in columns

uid                                  services      A   B  C
000c80b7d2b3643689b1e516918ec193    ['A']          1   0  0
001b292c588ec6cc11f57324d40e422d    ['B','A',C']   1   1  1
006696f65899fdd87ba4894c784716f9    ['C','B']      0   1  1

Thank you


问:
Using Log4Net in PowerShell
I am looking for a clear example of using Log4Net in PowerShell to write a local log file.  I have googled it, but the examples I have found (and linked to) have been confusing to me.  I would love to include a specific problem, but since I am looking for a good reference I can’t.

Edit:  Rewritten for clarity… maybe?

答:
Well, seems like I worded my question poorly.
I kept finding this link powershell-logging-using-apache-log4net but found it really hard to read.

So, I took this code and wrote it in friendlier fashion (for me).  The entire ColoredConsoleAppender part can be removed, as it is just for displaying to console.

```<code>#####################################################################################################################
#Load log4net.dll
$DllPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$DllFile = Resolve-Path (Join-Path -Path $DllPath -ChildPath 'log4net.dll')
[Void][Reflection.Assembly]::LoadFile($DllFile)
#####################################################################################################################
#FileAppender
#
#Define Values for FileAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff} (%utcdate{yyyy-MM-dd HH:mm:ss.fff})] [%level] [%message]%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))

$LogPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$LogFile = Join-Path -Path $LogPath -ChildPath $('LogFile_{0:yyyy-MM-dd}_{0:HH-mm-ss}.log' -f (Get-Date))

$AppendToFile = $True

#Load FileAppender Configuration
$FileAppender = new-object log4net.Appender.FileAppender($PatternLayout,$LogFile,$AppendToFile);
$FileAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($FileAppender)
#####################################################################################################################
#ColoredConsoleAppender
#
#Define Values for ColoredConsoleAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff}] %message%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))
$ColoredConsoleAppender = new-object log4net.Appender.ColoredConsoleAppender($PatternLayout)

$ColoredConsoleAppenderLevelAndColors = new-object log4net.Appender.ColoredConsoleAppender+LevelColors

$ColoredConsoleAppenderLevelAndColors.Level = [log4net.Core.Level]::Debug
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::Green
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level = [log4net.Core.Level]::Info
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::White
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Warn
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Yellow
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Error
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Fatal
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::HighIntensity -bxor [log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppender.ActivateOptions()

#Load FileAppender Configuration
$ColoredConsoleAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($ColoredConsoleAppender)
#####################################################################################################################
$Log = [log4net.LogManager]::GetLogger("root")
$Log.Debug(‘Debug message.’)
$Log.Info(‘Info message.’)
$Log.Warn(‘Warn message.’)
$Log.Error(‘Error message.’)
$Log.Fatal(‘Fatal message.’)
[log4net.LogManager]::ResetConfiguration()
</code>```

Title: Using Log4Net in PowerShell

Body:
Well, seems like I worded my question poorly.
I kept finding this link powershell-logging-using-apache-log4net but found it really hard to read.

So, I took this code and wrote it in friendlier fashion (for me).  The entire ColoredConsoleAppender part can be removed, as it is just for displaying to console.

#####################################################################################################################
#Load log4net.dll
$DllPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$DllFile = Resolve-Path (Join-Path -Path $DllPath -ChildPath 'log4net.dll')
[Void][Reflection.Assembly]::LoadFile($DllFile)
#####################################################################################################################
#FileAppender
#
#Define Values for FileAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff} (%utcdate{yyyy-MM-dd HH:mm:ss.fff})] [%level] [%message]%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))

$LogPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$LogFile = Join-Path -Path $LogPath -ChildPath $('LogFile_{0:yyyy-MM-dd}_{0:HH-mm-ss}.log' -f (Get-Date))

$AppendToFile = $True

#Load FileAppender Configuration
$FileAppender = new-object log4net.Appender.FileAppender($PatternLayout,$LogFile,$AppendToFile);
$FileAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($FileAppender)
#####################################################################################################################
#ColoredConsoleAppender
#
#Define Values for ColoredConsoleAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff}] %message%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))
$ColoredConsoleAppender = new-object log4net.Appender.ColoredConsoleAppender($PatternLayout)

$ColoredConsoleAppenderLevelAndColors = new-object log4net.Appender.ColoredConsoleAppender+LevelColors

$ColoredConsoleAppenderLevelAndColors.Level = [log4net.Core.Level]::Debug
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::Green
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level = [log4net.Core.Level]::Info
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::White
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Warn
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Yellow
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Error
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Fatal
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::HighIntensity -bxor [log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppender.ActivateOptions()

#Load FileAppender Configuration
$ColoredConsoleAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($ColoredConsoleAppender)
#####################################################################################################################
$Log = [log4net.LogManager]::GetLogger("root")
$Log.Debug(‘Debug message.’)
$Log.Info(‘Info message.’)
$Log.Warn(‘Warn message.’)
$Log.Error(‘Error message.’)
$Log.Fatal(‘Fatal message.’)
[log4net.LogManager]::ResetConfiguration()


问:
Expected File format for altool upload-app for Mac OS App Store app?
I'm packaging my application for the Mac App Store, using the following command

```<code>xcrun altool --upload-app --file MyApp.??? --type osx <credentials>
</code>```

I see on some examples they are using MyApp.zip as the file, and some it is MyApp.pkg.

altool does not seem happy with simply MyApp.app as a zip file, keeps throwing a lot of errors about the Info.plist which are not accurate.

The most success I've had so far is using productbuild to create a pkg, but now it is demanding that I sign it with my "3rd Party Mac Developer Installer" certificate.

Is it required that you create a signed PKG to deploy to the Mac App Store with altool, or are there any alternatives?

答:
The answer seems to be, Yes, a PKG is required.

It's not well documented, but it would appear that the Mac App Store uses the PKG to install your application upon delivery.

You must create the following:

PKG for delivery

signing certificate for the Mac App

signing certificate for the Mac Installer.

Here's an example of a script that's working for me.

```<code>codesign -vfs "3rd Party Mac Developer Application: MyGreatCompany (XXXXXXXX)" MyApp.app

xcrun productbuild --component MyApp.app /Applications/ myapp.unsigned.pkg

xcrun productsign --sign "3rd Party Mac Developer Installer: MyGreatCompany (XXXXXXXX)" myapp.unsigned.pkg myapp.pkg

xcrun altool --upload-app --file myapp.pkg --type osx
</code>```

Body:
I'm packaging my application for the Mac App Store, using the following command

xcrun altool --upload-app --file MyApp.??? --type osx <credentials>

I see on some examples they are using MyApp.zip as the file, and some it is MyApp.pkg.

altool does not seem happy with simply MyApp.app as a zip file, keeps throwing a lot of errors about the Info.plist which are not accurate.

The most success I've had so far is using productbuild to create a pkg, but now it is demanding that I sign it with my "3rd Party Mac Developer Installer" certificate.

Is it required that you create a signed PKG to deploy to the Mac App Store with altool, or are there any alternatives?

Body:
The answer seems to be, Yes, a PKG is required.

It's not well documented, but it would appear that the Mac App Store uses the PKG to install your application upon delivery.

You must create the following:

PKG for delivery

signing certificate for the Mac App

signing certificate for the Mac Installer.

Here's an example of a script that's working for me.

codesign -vfs "3rd Party Mac Developer Application: MyGreatCompany (XXXXXXXX)" MyApp.app

xcrun productbuild --component MyApp.app /Applications/ myapp.unsigned.pkg

xcrun productsign --sign "3rd Party Mac Developer Installer: MyGreatCompany (XXXXXXXX)" myapp.unsigned.pkg myapp.pkg

xcrun altool --upload-app --file myapp.pkg --type osx


问:
python pandas check value comming under range in another dataframe

my first dataframe

dataframe1=

```<code>id   number  count1 count2
1   5225    10       30
2   2222    3        40
3   7121    30        50
</code>```

second dataframe

dataframe2=

```<code>id  value1  value2
1   4000     6000
3   2500     3300
3   7000     8000
</code>```

output

```<code>id  value1  value2 number count1 count2
1   4000     6000  5225  10       30
3   7000     8000  7121  30       50
</code>```

I tried

```<code>dataframe2['a']=(dataframe1['number']>= dataframe2['value1']) & (dataframe1['number'] <= dataframe2['value2'])
</code>```

it gave True False values in column a, What I want to do is this: For each value in the Dataframe1  "number" column, search if it is equal to or between ANY of the "value1" and "value2" pair values of Dataframe2. Additionally, for this "number1" and "number2" pair values, its respective "id" must match the "id" in Dataframe. If this is all true, then I want to insert along with number, count1 and count2 in dataframe2

答:
```<code>merged = df1.join(df2, on="id", how="inner")
result = merged.query("value1 <= number <= value2")
result

    number  count1  count2  value1  value2
id
1     5225      10      30    4000    6000
3     7121      30      50    7000    8000
</code>```

Body:
my first dataframe

dataframe1=

id   number  count1 count2
1   5225    10       30
2   2222    3        40
3   7121    30        50

second dataframe

dataframe2=

id  value1  value2
1   4000     6000
3   2500     3300
3   7000     8000

output

id  value1  value2 number count1 count2
1   4000     6000  5225  10       30
3   7000     8000  7121  30       50

I tried

dataframe2['a']=(dataframe1['number']>= dataframe2['value1']) & (dataframe1['number'] <= dataframe2['value2'])

it gave True False values in column a, What I want to do is this: For each value in the Dataframe1  "number" column, search if it is equal to or between ANY of the "value1" and "value2" pair values of Dataframe2. Additionally, for this "number1" and "number2" pair values, its respective "id" must match the "id" in Dataframe. If this is all true, then I want to insert along with number, count1 and count2 in dataframe2


问:
Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)"
```<code><?php

session_start();

$mysqli = new mysqli('localhost', 'root', '', 'crud') or die(mysqli_error($mysqli)); //Izveido savienojumu ar datubāzi

//default values
$id = 0;
$update = false;
$name = '';
$age = '';
$mobile = '';
$location = '';

if (isset($_POST['save'])){     //pārbauda vai ir nospiesta save poga
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("INSERT INTO data (name, age, mobile, location) VALUES('$name', '$age', '$mobile', '$location')") or     //ievada datus datubāzē
        die($mysqli->error);

    $_SESSION['message'] = "Record has been saved!";    //iestata sesijas ziņojumu, ja dati tiek saglabāti
    $_SESSION['msg_type'] = "success";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['delete'])){     //pārbauda vai ir nospiesta delete poga
    $id = $_GET['delete'];
    $mysqli->query("DELETE FROM data WHERE id=$id") or die($mysqli->error());       //izdzēš datus no datubāzes

    $_SESSION['message'] = "Record has been deleted!";      //iestata sesijas ziņojumu, ja dati tiek izdzēsti
    $_SESSION['msg_type'] = "danger";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['edit'])){               //pārbauda vai ir nospiesta edit poga
    $id = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error());   //izvēlās datus no datubāzēs
   if(count($result)==1){                  //ja atrod ierakstu datubāzē
        $row = $result->fetch_array();      //atgriež datus no ieraksta
        $name = $row['name'];
        $age = $row['age'];
        $mobile = $row['mobile'];
        $location = $row['location'];
    }
}

if(isset($_POST['update'])){        //pārbauda vai ir nospiesta update poga
    $id = $_POST['id'];
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("UPDATE data SET name='$name', age='$age', mobile='$mobile', location='$location' WHERE id=$id") or      //atjauno vecos datus uz jaunajiem ievadītajiem datiem
        die($mysqli->error);

   $_SESSION['message'] = "Record has been updated!";       //iestata sesijas ziņojumu, ja dati tiek atjaunotie
   $_SESSION['msg_type'] = "warning";

   header('location: crud.php');    //novirza atpakaļ uz crud.php
}
?>
</code>```

It's telling me that Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)", and I can't find the problem for some reason, probably cos i'm a beginner. Anyway this is a CRUD - Create, Read, Update, Delete - and the Update/Edit function is not working so I'm stuck

答:
mysqli_query won't return anything countable, but it's not necessary to count just to see if you have a result or not. Since you're selecting by id, you'll only be able to get a maximum of one row from the query, assuming id is unique.

So you can just check that the query executed successfully and then try to get a row from it.

```<code>if ($result && $row = $result->fetch_array()) { ...
</code>```

If the query failed, $result will be false, and if it was successful but didn't return anything, then $row will be null.

Body:
<?php

session_start();

$mysqli = new mysqli('localhost', 'root', '', 'crud') or die(mysqli_error($mysqli)); //Izveido savienojumu ar datubāzi

//default values
$id = 0;
$update = false;
$name = '';
$age = '';
$mobile = '';
$location = '';

if (isset($_POST['save'])){     //pārbauda vai ir nospiesta save poga
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("INSERT INTO data (name, age, mobile, location) VALUES('$name', '$age', '$mobile', '$location')") or     //ievada datus datubāzē
        die($mysqli->error);

    $_SESSION['message'] = "Record has been saved!";    //iestata sesijas ziņojumu, ja dati tiek saglabāti
    $_SESSION['msg_type'] = "success";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['delete'])){     //pārbauda vai ir nospiesta delete poga
    $id = $_GET['delete'];
    $mysqli->query("DELETE FROM data WHERE id=$id") or die($mysqli->error());       //izdzēš datus no datubāzes

    $_SESSION['message'] = "Record has been deleted!";      //iestata sesijas ziņojumu, ja dati tiek izdzēsti
    $_SESSION['msg_type'] = "danger";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['edit'])){               //pārbauda vai ir nospiesta edit poga
    $id = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error());   //izvēlās datus no datubāzēs
   if(count($result)==1){                  //ja atrod ierakstu datubāzē
        $row = $result->fetch_array();      //atgriež datus no ieraksta
        $name = $row['name'];
        $age = $row['age'];
        $mobile = $row['mobile'];
        $location = $row['location'];
    }
}

if(isset($_POST['update'])){        //pārbauda vai ir nospiesta update poga
    $id = $_POST['id'];
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("UPDATE data SET name='$name', age='$age', mobile='$mobile', location='$location' WHERE id=$id") or      //atjauno vecos datus uz jaunajiem ievadītajiem datiem
        die($mysqli->error);

   $_SESSION['message'] = "Record has been updated!";       //iestata sesijas ziņojumu, ja dati tiek atjaunotie
   $_SESSION['msg_type'] = "warning";

   header('location: crud.php');    //novirza atpakaļ uz crud.php
}
?>

It's telling me that Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)", and I can't find the problem for some reason, probably cos i'm a beginner. Anyway this is a CRUD - Create, Read, Update, Delete - and the Update/Edit function is not working so I'm stuck

Body:
mysqli_query won't return anything countable, but it's not necessary to count just to see if you have a result or not. Since you're selecting by id, you'll only be able to get a maximum of one row from the query, assuming id is unique.

So you can just check that the query executed successfully and then try to get a row from it.

if ($result && $row = $result->fetch_array()) { ...

If the query failed, $result will be false, and if it was successful but didn't return anything, then $row will be null.


问:
Azure Table Storage cheapest way to find out if table has data
Background: As part of our table design for storing logs we are creating new tables each day. A function will run daily to create these tables. However there is no guarantee the tables will be used on that day. Therefore the function will also delete the previous day's table if there are no rows.

What is the cheapest way to check if table has data?
Potential partition and row keys could be quite a lot to check for.

答:
What is the cheapest way to check if table has data? Potential
  partition and row keys could be quite a lot to check for.

You can simply query the table and fetch just a single entity with $top=1.


问:
Is it possible to hide/remove borders inside of intersected area of multiple divs?
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
  <div class="circle" id="one"></div>
  <div class="circle" id="two"></div>
  <div class="circle" id="three"></div>
</div></code>```

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

答:
You can try using mask and adjust the code slightly to have better control. The trick is to use multiple mask where each one will be a circular gradient that will show only the border and each gradient will overlap each circle element. You can control the overlap using margin on the center element:

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid black;
  transition:0.5s;
}

.box {
  display:inline-flex;
  -webkit-mask:
     radial-gradient(50px at 52px              50%,transparent 99%,#fff 100%),
     radial-gradient(50px at 50%               50%,transparent 99%,#fff 100%),
     radial-gradient(50px at calc(100% - 52px) 50%,transparent 99%,#fff 100%);
  mask:
     radial-gradient(50px at 52px              50%,transparent 99%,#fff 100%),
     radial-gradient(50px at 50%               50%,transparent 99%,#fff 100%),
     radial-gradient(50px at calc(100% - 52px) 50%,transparent 99%,#fff 100%);
  -webkit-mask-composite: source-in;
  mask-composite: intersect;
}

body {
  background:linear-gradient(to right,pink,yellow);
}

/* You can also have animation*/
.box:hover .circle{
   margin:0!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -50px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -30px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -70px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -10px;"></div>
  <div class="circle"></div>
</div></code>```

And with CSS variables to have better control:

.circle {
  width: calc(2*var(--r));
  height: calc(2*var(--r));
  border-radius: 50%;
  border: var(--b) solid black;
}

.box {
  --r:50px; /* radius of circles*/
  --b:2px;  /* border length */
  --g:transparent 99%,#fff 100%;

  display:inline-flex;
  -webkit-mask:
     radial-gradient(var(--r) at calc(var(--r) + var(--b))        50%,var(--g)),
     radial-gradient(var(--r) at 50%                              50%,var(--g)),
     radial-gradient(var(--r) at calc(100% - var(--r) - var(--b)) 50%,var(--g));
  mask:
     radial-gradient(var(--r) at calc(var(--r) + var(--b))        50%,var(--g)),
     radial-gradient(var(--r) at 50%                              50%,var(--g)),
     radial-gradient(var(--r) at calc(100% - var(--r) - var(--b)) 50%,var(--g));
  -webkit-mask-composite: source-in;
  mask-composite: intersect;
}

body {
  background:linear-gradient(to right,pink,yellow);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -50px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:40px;--b:5px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -30px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:100px;--b:20px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -70px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:80px;--b:5px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -10px;"></div>
  <div class="circle"></div>
</div></code>```

Body:
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

Body:
You can try using mask and adjust the code slightly to have better control. The trick is to use multiple mask where each one will be a circular gradient that will show only the border and each gradient will overlap each circle element. You can control the overlap using margin on the center element:

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid black;
  transition:0.5s;
}

.box {
  display:inline-flex;
  -webkit-mask:
     radial-gradient(50px at 52px              50%,transparent 99%,#fff 100%),
     radial-gradient(50px at 50%               50%,transparent 99%,#fff 100%),
     radial-gradient(50px at calc(100% - 52px) 50%,transparent 99%,#fff 100%);
  mask:
     radial-gradient(50px at 52px              50%,transparent 99%,#fff 100%),
     radial-gradient(50px at 50%               50%,transparent 99%,#fff 100%),
     radial-gradient(50px at calc(100% - 52px) 50%,transparent 99%,#fff 100%);
  -webkit-mask-composite: source-in;
  mask-composite: intersect;
}

body {
  background:linear-gradient(to right,pink,yellow);
}

/* You can also have animation*/
.box:hover .circle{
   margin:0!important;
}

<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -50px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -30px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -70px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -10px;"></div>
  <div class="circle"></div>
</div>

And with CSS variables to have better control:

.circle {
  width: calc(2*var(--r));
  height: calc(2*var(--r));
  border-radius: 50%;
  border: var(--b) solid black;
}

.box {
  --r:50px; /* radius of circles*/
  --b:2px;  /* border length */
  --g:transparent 99%,#fff 100%;

  display:inline-flex;
  -webkit-mask:
     radial-gradient(var(--r) at calc(var(--r) + var(--b))        50%,var(--g)),
     radial-gradient(var(--r) at 50%                              50%,var(--g)),
     radial-gradient(var(--r) at calc(100% - var(--r) - var(--b)) 50%,var(--g));
  mask:
     radial-gradient(var(--r) at calc(var(--r) + var(--b))        50%,var(--g)),
     radial-gradient(var(--r) at 50%                              50%,var(--g)),
     radial-gradient(var(--r) at calc(100% - var(--r) - var(--b)) 50%,var(--g));
  -webkit-mask-composite: source-in;
  mask-composite: intersect;
}

body {
  background:linear-gradient(to right,pink,yellow);
}

<div class="box">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -50px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:40px;--b:5px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -30px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:100px;--b:20px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -70px;"></div>
  <div class="circle"></div>
</div>
<br>
<div class="box" style="--r:80px;--b:5px;">
  <div class="circle"></div>
  <div class="circle" style="margin:0 -10px;"></div>
  <div class="circle"></div>
</div>


问:
unable to map topics to specified index in kafka elasticsearch connector
tried to map topic "name: localtopic"  to index "name:indexoftopic" ,
its creating two new index in elastic search "localtopic and indexoftopic" and data of topic visible only in topic name index "localtopic", no errors in connector shown ( distributed mode )

my config is

```<code> "config" : {
  "connector.class" : "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
  "tasks.max" : "1",
  "topics" : "localtopic",
  "topic.index.map" : "localtopic:indexoftopic",
  "connection.url" : "aws elasticsearch url",
  "type.name" : "event",
  "key.ignore" : "false",
  "schema.ignore" : "true",
  "schemas.enable" : "false",
  "transforms" : "InsertKey,extractKey",
  "transforms.InsertKey.type" : "org.apache.kafka.connect.transforms.ValueToKey",
  "transforms.InsertKey.fields" : "event-id",
  "transforms.extractKey.type" : "org.apache.kafka.connect.transforms.ExtractField$Key",
  "transforms.extractKey.field" : "event-id"
 }
</code>```

index name:indexoftopic is created in elasticsearch but data is seen by index_name:localtopic
kafkaversion:2.3  connectorversion:5   elasticsearchversion:3.2.0

even in logs INFO -- topics.regex = "", I don't know ihis option, can anyone suggest. how to use this ???

答:
Below worked for me, but, I was mapping only 1 topic to a different index name

```<code>"transforms": "addSuffix",
"transforms.addSuffix.type": "org.apache.kafka.connect.transforms.RegexRouter",
"transforms.addSuffix.regex": "topic1.*",
"transforms.addSuffix.replacement": "index1",
</code>```

so, with above transforms any topic such as topic1, topic1-test, topic1<anystring>
will be mapped to index1

alternately, you can use the topic name in replacement as well, by changing the last 2 lines as below, this will pick

```<code>    "transforms.addSuffix.regex": "topic.*",
    "transforms.addSuffix.replacement": "index$1",
</code>```

basically, you can replace partial or full topic name using regex.

Body:
tried to map topic "name: localtopic"  to index "name:indexoftopic" ,
its creating two new index in elastic search "localtopic and indexoftopic" and data of topic visible only in topic name index "localtopic", no errors in connector shown ( distributed mode )

my config is

 "config" : {
  "connector.class" : "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
  "tasks.max" : "1",
  "topics" : "localtopic",
  "topic.index.map" : "localtopic:indexoftopic",
  "connection.url" : "aws elasticsearch url",
  "type.name" : "event",
  "key.ignore" : "false",
  "schema.ignore" : "true",
  "schemas.enable" : "false",
  "transforms" : "InsertKey,extractKey",
  "transforms.InsertKey.type" : "org.apache.kafka.connect.transforms.ValueToKey",
  "transforms.InsertKey.fields" : "event-id",
  "transforms.extractKey.type" : "org.apache.kafka.connect.transforms.ExtractField$Key",
  "transforms.extractKey.field" : "event-id"
 }

index name:indexoftopic is created in elasticsearch but data is seen by index_name:localtopic
kafkaversion:2.3  connectorversion:5   elasticsearchversion:3.2.0

even in logs INFO -- topics.regex = "", I don't know ihis option, can anyone suggest. how to use this ???

Body:
Below worked for me, but, I was mapping only 1 topic to a different index name

"transforms": "addSuffix",
"transforms.addSuffix.type": "org.apache.kafka.connect.transforms.RegexRouter",
"transforms.addSuffix.regex": "topic1.*",
"transforms.addSuffix.replacement": "index1",

so, with above transforms any topic such as topic1, topic1-test, topic1<anystring>
will be mapped to index1

alternately, you can use the topic name in replacement as well, by changing the last 2 lines as below, this will pick

    "transforms.addSuffix.regex": "topic.*",
    "transforms.addSuffix.replacement": "index$1",

basically, you can replace partial or full topic name using regex.