问:
How would I change the src of an iframe with a text input?
So, Mojang released a version of Minecraft for the browser and I've been trying to add it to my website. I successfully did that with an iframe but people wanted multiplayer. Since multiplayer works through links, the goal would be to input the link they receive from someone else and change the iframe from the standard one to the new multiplayer one.

What I've tried is to get the user input, assign it to a variable, and use document.write to rewrite the existing iframe with the new src.

Here's what I've got. Note: it's in a modal.

input[type=text], input[type=password] {
  width: 300px;
}
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

/* Add Zoom Animation */
.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
.button {
  color: white;
  background-color: #4CAF50;
  border-color: #ccc;
  font-size: 14px;
  font-weight: 400;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  padding: 6px 12px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div align="center"><iframe id="change" name="change" width="800" height="500" src="//classic.minecraft.net"></iframe></div>
 <div>
 <button class="button" id="button"><b>Fullscreen</b> </button>
 <button class="button" id="modal" onclick="document.getElementById('id01').style.display='block'"><b>Multiplayer</b></button>
 </div>
 <script src="/fullscreen.js"></script>
 <script>
   function changeIframe() {
  document.write(" <iframe  id='change' name='change' src='#" + input + "' width='800'  height='500'   allowfullscreen></iframe>");
}
 </script>
 <script>
 var input = document.getElementById("detroit");
 </script>
 <div id="id01" class="sprckn-modal">

<form class="modal-content animate">
    <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>

  <div class="sprckn-modal-content">
    <label for="link"><b>Paste Multiplayer Link Here</b></label>
    <center><input type="text" onsubmit="changeIframe()" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required></center>
  </div>

  <div class="container" style="background-color:#f1f1f1">
    <center><button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button></center>
</form>
  </div>
</div>
`</code>```

Absolutely no part of the iframe changes, but my website url does, with a ?link=(linkhere). It can be better shown off at https://sprocken.com/game/minecraft/.

答:
Change the existing iframe source:

```<code>function changeIframe(url) {
  document.getElementById('change').src = url;
}
</code>```

Use the onchange event instead of onsubmit:

```<code><input type="text" id="minecraftInput" onchange="changeIframe(this.value)" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required>
</code>```

Body:
So, Mojang released a version of Minecraft for the browser and I've been trying to add it to my website. I successfully did that with an iframe but people wanted multiplayer. Since multiplayer works through links, the goal would be to input the link they receive from someone else and change the iframe from the standard one to the new multiplayer one.

What I've tried is to get the user input, assign it to a variable, and use document.write to rewrite the existing iframe with the new src.

Here's what I've got. Note: it's in a modal.

input[type=text], input[type=password] {
  width: 300px;
}
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 40%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

/* Add Zoom Animation */
.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
.button {
  color: white;
  background-color: #4CAF50;
  border-color: #ccc;
  font-size: 14px;
  font-weight: 400;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  padding: 6px 12px;
}

 <button class="button" id="button">Fullscreen </button>
 <button class="button" id="modal" onclick="document.getElementById('id01').style.display='block'">Multiplayer</button>

<form class="modal-content animate">
    ×

    Paste Multiplayer Link Here
    <input type="text" onsubmit="changeIframe()" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required>

    <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</form>

`

Absolutely no part of the iframe changes, but my website url does, with a ?link=(linkhere). It can be better shown off at https://sprocken.com/game/minecraft/.

Body:
Change the existing iframe source:

function changeIframe(url) {
  document.getElementById('change').src = url;
}

Use the onchange event instead of onsubmit:

<input type="text" id="minecraftInput" onchange="changeIframe(this.value)" id="detroit" placeholder="https://classic.minecraft.net/?join=somelettersand#s" name="link" required>


来源: stackexchange

问:
How to increment a MySQL timestamp in PHP?
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

```<code>$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;
</code>```

Thanks

答:
When supplied with a second argument, strtotime() will perform calculations based on this date:

```<code>$mdate = date('F j, Y, g:i a', strtotime('-4 hours', $bm->date_added));
</code>```

strtotime() can perform several calculations base on modifiers like these. Examples from the manual:

```<code><?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;

Thanks

Body:
When supplied with a second argument, strtotime() will perform calculations based on this date:

$mdate = date('F j, Y, g:i a', strtotime('-4 hours', $bm->date_added));

strtotime() can perform several calculations base on modifiers like these. Examples from the manual:

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>


问:
Ignore commas when enclosed in double quotes
I'd like to extend the code below so it can take double quotes. For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19]. Please help. Thanks.

```<code>def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]
</code>```

答:
Solution using CSV:

```<code>$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> from io import StringIO
>>> csv_string = '303,"Candy, Original",45,19'
>>> csv_file = StringIO(csv_string)
>>>
>>> reader = csv.reader(csv_file, delimiter=',')
>>> reader.__next__()
['303', 'Candy, Original', '45', '19']
</code>```

You could then pass each value through an int or float coercion to get the native numerics if needed.

ContentLicense: CC BY-SA 4.0

Body:
I'd like to extend the code below so it can take double quotes. For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19]. Please help. Thanks.

def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]

Body:
Solution using CSV:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> from io import StringIO
>>> csv_string = '303,"Candy, Original",45,19'
>>> csv_file = StringIO(csv_string)
>>>
>>> reader = csv.reader(csv_file, delimiter=',')
>>> reader.__next__()
['303', 'Candy, Original', '45', '19']

You could then pass each value through an int or float coercion to get the native numerics if needed.


问:
How to navigate to custom page when user taps on a Twilio Chat SDK push notification
I have read both the Android and iOS SDK documentation for integrating push notifications into my chat implementation. One topic that I do not see discussed is how to navigate to the correct place in an application when a push notification is tapped on.

For instance when a use taps on a push notification how does an app respond to the event in order to navigate to the view of the channel that received the message?

答:
The documentation Push Notifications on iOS do not reference it but digging into the iOS SDK I found TwilioChatClientDelegate Protocol Reference. It has a delegate that does what I was looking for:

```<code>– chatClient:notificationNewMessageReceivedForChannelSid:messageIndex:
– chatClient:notificationAddedToChannelWithSid:
– chatClient:notificationInvitedToChannelWithSid:
– chatClient:notificationRemovedFromChannelWithSid:
– chatClient:notificationUpdatedBadgeCount:
</code>```

For Android there is com.twilio.chat.NotificationPayload Class Reference which has methods for parsing out the data from the notification payload.

Body:
The documentation Push Notifications on iOS do not reference it but digging into the iOS SDK I found TwilioChatClientDelegate Protocol Reference. It has a delegate that does what I was looking for:

– chatClient:notificationNewMessageReceivedForChannelSid:messageIndex:
– chatClient:notificationAddedToChannelWithSid:
– chatClient:notificationInvitedToChannelWithSid:
– chatClient:notificationRemovedFromChannelWithSid:
– chatClient:notificationUpdatedBadgeCount:

For Android there is com.twilio.chat.NotificationPayload Class Reference which has methods for parsing out the data from the notification payload.


问:
How to fix "Error in eval(predvars, data, env) : numeric 'envir' arg not of length one" in purrr
I'm bootstrapping well known mtcars dataset and applying logistic regression using glm and purrr::map. Howevever I'm getting

```<code>Error in eval(predvars, data, env) :
  numeric 'envir' arg not of length one
</code>```

error

I've already tried to apply glm to a single bootstrapped data and it works fine, but when I apply map function it fails

library(tidyverse)
library(rsample)
library(broom)

sample10 <-
    bootstraps(mtcars, times=10) %>%
    rowwise() %>%
    mutate(data_sample=list(analysis(splits))) %>%
    select(id, data_sample)

sample10

Source: local data frame [10 x 2]
Groups: <by row>

# A tibble: 10 x 2
   id          data_sample
   <chr>       <list>
 1 Bootstrap01 <df[,11] [32 × 11]>
 2 Bootstrap02 <df[,11] [32 × 11]>
 3 Bootstrap03 <df[,11] [32 × 11]>
 4 Bootstrap04 <df[,11] [32 × 11]>
 5 Bootstrap05 <df[,11] [32 × 11]>
 6 Bootstrap06 <df[,11] [32 × 11]>
 7 Bootstrap07 <df[,11] [32 × 11]>
 8 Bootstrap08 <df[,11] [32 × 11]>
 9 Bootstrap09 <df[,11] [32 × 11]>
10 Bootstrap10 <df[,11] [32 × 11]>
```

<p>when I try to fit a model for each bootstrap dataframe :</p>

<pre class="lang-r prettyprint-override"><code>sample10 %>%
    mutate(model_fit = map(data_sample,
                           ~ glm(formula= vs ~ wt + disp,
                                 data=.,
                                 family=binomial)))

Error in eval(predvars, data, env) :
  numeric 'envir' arg not of length one
</code>```

However when I try to fit a glm to single Bootstrap data frame it is all good

glm(formula= vs ~ wt + disp, data=sample10$data_sample[[1]], family=binomial)

Call:  glm(formula = vs ~ wt + disp, family = binomial, data = sample10$data_sample[[1]])

Coefficients:
(Intercept)           wt         disp
    5.54313     -1.19918     -0.01472

Degrees of Freedom: 31 Total (i.e. Null);  29 Residual
Null Deviance:      41.18
Residual Deviance: 16.97    AIC: 22.97

```

The error message is not helpful, and I'm not sure what I'm doing wrong. I feel like it's something with purrr::map function but I'm not sure.

Any help is appreciated.

答:
The issue I think is that the tibble is still grouped by row.  If you add ungroup() as the last step of your chain then the code will work.

```<code>sample10 <- bootstraps(mtcars, times=10) %>%
  rowwise() %>%
  mutate(data_sample=(list(analysis(splits)))) %>%
  select(id, data_sample) %>%
  ungroup()

sample10 %>%
  mutate(model_fit = map(data_sample,
                         ~ glm(formula= vs ~ wt + disp,
                               data=.,
                               family=binomial)))

# A tibble: 10 x 3
   id          data_sample            model_fit
   <chr>       <list>                 <list>
 1 Bootstrap01 <data.frame [32 x 11]> <S3: glm>
 2 Bootstrap02 <data.frame [32 x 11]> <S3: glm>
 3 Bootstrap03 <data.frame [32 x 11]> <S3: glm>
 4 Bootstrap04 <data.frame [32 x 11]> <S3: glm>
 5 Bootstrap05 <data.frame [32 x 11]> <S3: glm>
 6 Bootstrap06 <data.frame [32 x 11]> <S3: glm>
 7 Bootstrap07 <data.frame [32 x 11]> <S3: glm>
 8 Bootstrap08 <data.frame [32 x 11]> <S3: glm>
 9 Bootstrap09 <data.frame [32 x 11]> <S3: glm>
10 Bootstrap10 <data.frame [32 x 11]> <S3: glm>
</code>```

Body:
I'm bootstrapping well known mtcars dataset and applying logistic regression using glm and purrr::map. Howevever I'm getting

Error in eval(predvars, data, env) :
  numeric 'envir' arg not of length one

error

I've already tried to apply glm to a single bootstrapped data and it works fine, but when I apply map function it fails

library(tidyverse)
library(rsample)
library(broom)

sample10 <-
    bootstraps(mtcars, times=10) %>%
    rowwise() %>%
    mutate(data_sample=list(analysis(splits))) %>%
    select(id, data_sample)

sample10

Source: local data frame [10 x 2]
Groups: <by row>

# A tibble: 10 x 2
   id          data_sample
   <chr>       <list>
 1 Bootstrap01 <df[,11] [32 × 11]>
 2 Bootstrap02 <df[,11] [32 × 11]>
 3 Bootstrap03 <df[,11] [32 × 11]>
 4 Bootstrap04 <df[,11] [32 × 11]>
 5 Bootstrap05 <df[,11] [32 × 11]>
 6 Bootstrap06 <df[,11] [32 × 11]>
 7 Bootstrap07 <df[,11] [32 × 11]>
 8 Bootstrap08 <df[,11] [32 × 11]>
 9 Bootstrap09 <df[,11] [32 × 11]>
10 Bootstrap10 <df[,11] [32 × 11]>

when I try to fit a model for each bootstrap dataframe :

sample10 %>%
    mutate(model_fit = map(data_sample,
                           ~ glm(formula= vs ~ wt + disp,
                                 data=.,
                                 family=binomial)))

Error in eval(predvars, data, env) :
  numeric 'envir' arg not of length one

However when I try to fit a glm to single Bootstrap data frame it is all good

glm(formula= vs ~ wt + disp, data=sample10$data_sample[[1]], family=binomial)

Call:  glm(formula = vs ~ wt + disp, family = binomial, data = sample10$data_sample[[1]])

Coefficients:
(Intercept)           wt         disp
    5.54313     -1.19918     -0.01472

Degrees of Freedom: 31 Total (i.e. Null);  29 Residual
Null Deviance:      41.18
Residual Deviance: 16.97    AIC: 22.97

The error message is not helpful, and I'm not sure what I'm doing wrong. I feel like it's something with purrr::map function but I'm not sure.

Any help is appreciated.

Body:
The issue I think is that the tibble is still grouped by row.  If you add ungroup() as the last step of your chain then the code will work.

sample10 <- bootstraps(mtcars, times=10) %>%
  rowwise() %>%
  mutate(data_sample=(list(analysis(splits)))) %>%
  select(id, data_sample) %>%
  ungroup()

sample10 %>%
  mutate(model_fit = map(data_sample,
                         ~ glm(formula= vs ~ wt + disp,
                               data=.,
                               family=binomial)))

# A tibble: 10 x 3
   id          data_sample            model_fit
   <chr>       <list>                 <list>
 1 Bootstrap01 <data.frame [32 x 11]> <S3: glm>
 2 Bootstrap02 <data.frame [32 x 11]> <S3: glm>
 3 Bootstrap03 <data.frame [32 x 11]> <S3: glm>
 4 Bootstrap04 <data.frame [32 x 11]> <S3: glm>
 5 Bootstrap05 <data.frame [32 x 11]> <S3: glm>
 6 Bootstrap06 <data.frame [32 x 11]> <S3: glm>
 7 Bootstrap07 <data.frame [32 x 11]> <S3: glm>
 8 Bootstrap08 <data.frame [32 x 11]> <S3: glm>
 9 Bootstrap09 <data.frame [32 x 11]> <S3: glm>
10 Bootstrap10 <data.frame [32 x 11]> <S3: glm>


问:
How to extract a value from a Pandas data frame from a reference in the frame, then "walk up" the frame to another specified value?
I have the following toy data set:

```<code>import pandas as pd
from StringIO import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()
</code>```

My goals are to:

a) find the most negative value in the "Return" column

b) find the date the this value occurred

c) then "walk up" the "Return" column to find the first instance a specific value (in this case, 0.000000).

d) find the date associated with the value returned in step "c"

The results I'm looking for are:

a) -1.20519

b) March 2, 2009

c) 0.000000

d) February 6, 2009

I can find "a" with the following code:

```<code>max_dd = df['Maximum_Drawdown'].min()
</code>```

To get "b", I tried to use the following code:

```<code>df.loc[df['Return'] == max_dd, 'Date']
</code>```

But, the error message says:

```<code>KeyError: 'Date'
</code>```

Note: I can get "b" to work in this toy example, but the actual data throws the error message.  Here is actual code used to import the data from the csv file:

```<code>df = pd.read_csv(FILE_NAME, parse_dates=True).reset_index()

df.set_index('Date', inplace = True)  <<--- this is causing the problem
</code>```

答:
Filter your dataframe for all rows less than the minimum value in Return and also Return equals zero, than show the last value. </p>

```<code>df.loc[(df.index < df.Return.idxmin()) & (df['Return'] == 0), "Date"].tail(1)
</code>```

Body:
I have the following toy data set:

import pandas as pd
from StringIO import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()

My goals are to:

a) find the most negative value in the "Return" column

b) find the date the this value occurred

c) then "walk up" the "Return" column to find the first instance a specific value (in this case, 0.000000).

d) find the date associated with the value returned in step "c"

The results I'm looking for are:

a) -1.20519

b) March 2, 2009

c) 0.000000

d) February 6, 2009

I can find "a" with the following code:

max_dd = df['Maximum_Drawdown'].min()

To get "b", I tried to use the following code:

df.loc[df['Return'] == max_dd, 'Date']

But, the error message says:

KeyError: 'Date'

Note: I can get "b" to work in this toy example, but the actual data throws the error message.  Here is actual code used to import the data from the csv file:

df = pd.read_csv(FILE_NAME, parse_dates=True).reset_index()

df.set_index('Date', inplace = True)  <<--- this is causing the problem

Body:
Filter your dataframe for all rows less than the minimum value in Return and also Return equals zero, than show the last value.

df.loc[(df.index < df.Return.idxmin()) & (df['Return'] == 0), "Date"].tail(1)


问:
How to use nested group in mongodb?
I have one query where I want to group subdocument. i have try some example but it is not working properly

Query

```<code>db.getCollection("checklistCombination").aggregate([
  {
    "$lookup": {
      "from": "Users",
      "localField": "userId",
      "foreignField": "_id",
      "as": "user"
    }
  },
  {
    "$lookup": {
      "from": "checklist",
      "localField": "checklistId",
      "foreignField": "_id",
      "as": "linkChecklist"
    }
  },
  { "$unwind": "$linkChecklist" },
  {
    "$lookup": {
      "from": "orderDetail",
      "localField": "linkChecklist.product",
      "foreignField": "productRangeId",
      "as": "orderProduct"
    }
  },
  {
    "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
  },
  {
    "$lookup": {
      "from": "companysuppliers",
      "localField": "orderProduct.supplierId",
      "foreignField": "_id",
      "as": "comapnySupplier"
    }
  },
  {
    "$unwind": {
      "path": "$comapnySupplier",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "from": "suppliers",
      "localField": "comapnySupplier.supplierId",
      "foreignField": "_id",
      "as": "supplier"
    }
  },
  { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
  {
    "$project": {
      "_id": 1,
      "name": 1,
      "user": 1,
      "linkChecklist": 1,
      "orderProduct": 1,
      "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
      "comapnySupplier": 1,
      "supplier": 1
    }
  },
  { "$match": { "orderProductStatusIndex": "0" } },
  {
    "$group": {
      "_id": "$_id",
      "name": { "$first": "$name" },
      "supplier": {
        "$push": {
          "supplierId": "$supplier._id",
          "supplierName": "$supplier.name",
          "items": { "$sum": "$orderProduct.quantity" }
        }
      }
    }
  }
])
</code>```

This query return below result

```<code>[{
    "_id" : ObjectId("5cee224b97e765079c8c2839"),
    "name" : "Dairy",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
},
{
    "_id" : ObjectId("5cee1a19a01ad50f5c2229f2"),
    "name" : "dairy/fruit",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 55
        },
        {
            "supplierId" : ObjectId("5cee11f7a01ad50f5c2229a2"),
            "supplierName" : "Agron India PVT. LTD",
            "items" : 55
        },
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
}]
</code>```

In result you can see there are two different results for Bhagwandas Bherumal in dairy/fruit (in array index 1 ). I want to group by this field and sum its items.

Expected Result

```<code>[
{
    "_id" : ObjectId("5cee224b97e765079c8c2839"),
    "name" : "Dairy",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
},
{
    "_id" : ObjectId("5cee1a19a01ad50f5c2229f2"),
    "name" : "dairy/fruit",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 65
        },
        {
            "supplierId" : ObjectId("5cee11f7a01ad50f5c2229a2"),
            "supplierName" : "Agron India PVT. LTD",
            "items" : 55
        }
    ]
}]
</code>```

答:
Hope this solves your problem :</p>

```<code>db.getCollection("checklistCombination").aggregate([
 {
   "$lookup": {
    "from": "Users",
    "localField": "userId",
    "foreignField": "_id",
    "as": "user"
   }
 },
 {
   "$lookup": {
    "from": "checklist",
    "localField": "checklistId",
    "foreignField": "_id",
    "as": "linkChecklist"
   }
 },
 { "$unwind": "$linkChecklist" },
 {
   "$lookup": {
     "from": "orderDetail",
     "localField": "linkChecklist.product",
     "foreignField": "productRangeId",
     "as": "orderProduct"
   }
 },
 {
   "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
 },
 {
   "$lookup": {
     "from": "companysuppliers",
     "localField": "orderProduct.supplierId",
     "foreignField": "_id",
     "as": "comapnySupplier"
    }
 },
 {
   "$unwind": {
    "path": "$comapnySupplier",
    "preserveNullAndEmptyArrays": true
   }
 },
 {
   "$lookup": {
     "from": "suppliers",
     "localField": "comapnySupplier.supplierId",
     "foreignField": "_id",
     "as": "supplier"
   }
 },
 { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
 {
   "$project": {
     "_id": 1,
     "name": 1,
     "user": 1,
     "linkChecklist": 1,
     "orderProduct": 1,
     "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
     "comapnySupplier": 1,
     "supplier": 1
   }
 },
 { "$match": { "orderProductStatusIndex": "0" } },
 { $group : {
    _id : {
      _id :  '$_id',
      name : '$name',
      supplierId : "$supplier._id",
      supplierName : "$supplier.name"
    },
    items  : { "$sum": "$orderProduct.quantity"}
  }
 },
 {
   $group : {
     _id : '$_id._id',
     name : { "$first": "$_id.name" },
     supplier : {
         "$push": {
            "supplierId": "$_id.supplierId",
             "supplierName": "$_id.supplierName",
             "items" : '$items'
         }
     }
   }
 }
])
</code>```

Title: How to use nested group in mongodb?

Body:
I have one query where I want to group subdocument. i have try some example but it is not working properly

Query

db.getCollection("checklistCombination").aggregate([
  {
    "$lookup": {
      "from": "Users",
      "localField": "userId",
      "foreignField": "_id",
      "as": "user"
    }
  },
  {
    "$lookup": {
      "from": "checklist",
      "localField": "checklistId",
      "foreignField": "_id",
      "as": "linkChecklist"
    }
  },
  { "$unwind": "$linkChecklist" },
  {
    "$lookup": {
      "from": "orderDetail",
      "localField": "linkChecklist.product",
      "foreignField": "productRangeId",
      "as": "orderProduct"
    }
  },
  {
    "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
  },
  {
    "$lookup": {
      "from": "companysuppliers",
      "localField": "orderProduct.supplierId",
      "foreignField": "_id",
      "as": "comapnySupplier"
    }
  },
  {
    "$unwind": {
      "path": "$comapnySupplier",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "from": "suppliers",
      "localField": "comapnySupplier.supplierId",
      "foreignField": "_id",
      "as": "supplier"
    }
  },
  { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
  {
    "$project": {
      "_id": 1,
      "name": 1,
      "user": 1,
      "linkChecklist": 1,
      "orderProduct": 1,
      "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
      "comapnySupplier": 1,
      "supplier": 1
    }
  },
  { "$match": { "orderProductStatusIndex": "0" } },
  {
    "$group": {
      "_id": "$_id",
      "name": { "$first": "$name" },
      "supplier": {
        "$push": {
          "supplierId": "$supplier._id",
          "supplierName": "$supplier.name",
          "items": { "$sum": "$orderProduct.quantity" }
        }
      }
    }
  }
])

This query return below result

[{
    "_id" : ObjectId("5cee224b97e765079c8c2839"),
    "name" : "Dairy",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
},
{
    "_id" : ObjectId("5cee1a19a01ad50f5c2229f2"),
    "name" : "dairy/fruit",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 55
        },
        {
            "supplierId" : ObjectId("5cee11f7a01ad50f5c2229a2"),
            "supplierName" : "Agron India PVT. LTD",
            "items" : 55
        },
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
}]

In result you can see there are two different results for Bhagwandas Bherumal in dairy/fruit (in array index 1 ). I want to group by this field and sum its items.

Expected Result

[
{
    "_id" : ObjectId("5cee224b97e765079c8c2839"),
    "name" : "Dairy",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
},
{
    "_id" : ObjectId("5cee1a19a01ad50f5c2229f2"),
    "name" : "dairy/fruit",
    "supplier" : [
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 65
        },
        {
            "supplierId" : ObjectId("5cee11f7a01ad50f5c2229a2"),
            "supplierName" : "Agron India PVT. LTD",
            "items" : 55
        }
    ]
}]

Body:
Hope this solves your problem :

db.getCollection("checklistCombination").aggregate([
 {
   "$lookup": {
    "from": "Users",
    "localField": "userId",
    "foreignField": "_id",
    "as": "user"
   }
 },
 {
   "$lookup": {
    "from": "checklist",
    "localField": "checklistId",
    "foreignField": "_id",
    "as": "linkChecklist"
   }
 },
 { "$unwind": "$linkChecklist" },
 {
   "$lookup": {
     "from": "orderDetail",
     "localField": "linkChecklist.product",
     "foreignField": "productRangeId",
     "as": "orderProduct"
   }
 },
 {
   "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
 },
 {
   "$lookup": {
     "from": "companysuppliers",
     "localField": "orderProduct.supplierId",
     "foreignField": "_id",
     "as": "comapnySupplier"
    }
 },
 {
   "$unwind": {
    "path": "$comapnySupplier",
    "preserveNullAndEmptyArrays": true
   }
 },
 {
   "$lookup": {
     "from": "suppliers",
     "localField": "comapnySupplier.supplierId",
     "foreignField": "_id",
     "as": "supplier"
   }
 },
 { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
 {
   "$project": {
     "_id": 1,
     "name": 1,
     "user": 1,
     "linkChecklist": 1,
     "orderProduct": 1,
     "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
     "comapnySupplier": 1,
     "supplier": 1
   }
 },
 { "$match": { "orderProductStatusIndex": "0" } },
 { $group : {
    _id : {
      _id :  '$_id',
      name : '$name',
      supplierId : "$supplier._id",
      supplierName : "$supplier.name"
    },
    items  : { "$sum": "$orderProduct.quantity"}
  }
 },
 {
   $group : {
     _id : '$_id._id',
     name : { "$first": "$_id.name" },
     supplier : {
         "$push": {
            "supplierId": "$_id.supplierId",
             "supplierName": "$_id.supplierName",
             "items" : '$items'
         }
     }
   }
 }
])


问:
Git shows wrong author after merge
I'm puzzled to see a merge commit in the git log by my colleague Alice, and Bob assures me that it was indeed him who did the merge. I see no other merge commit by Bob, so it looks as if Alice somehow managed to take over Bob's commit.

Alice did indeed also commit something, but her commit activity came likely after Bob's. Alice is using git exclusively through Visual Studio's git ui.

I know that locally commits can be rewritten through rebase operations, but it's my understanding that this isn't normally done for commits that are already pushed. I would assume that a graphical git ui doesn't do anything out of the ordinary.

So why do I see Alice as the author and committer in the git log? What could possibly have happened to cause this?

EDIT: Other commits have sensible authors, so this isn't simply the wrong username being configured.

答:
Every commit object carries both fields, author and committer.  You can inspect the raw commit object using the command-line git cat-file -p operation.  For instance:

```<code>$ git cat-file -p 83232e38648b51abbcbdb56c94632b6906cc85a6 | sed 's/@/ /'
tree 894962f72d565687c409f018060fdefa20e5f3fe
parent aa8c8d914e4ae709e4fd025f359594f62653d9e5
author Junio C Hamano <gitster pobox.com> 1556175832 +0900
committer Junio C Hamano <gitster pobox.com> 1556178085 +0900

The seventh batch

Signed-off-by: Junio C Hamano <gitster pobox.com>
</code>```

Once a commit is made, it cannot be changed: the hash ID of the commit, in this case 83232e38648b51abbcbdb56c94632b6906cc85a6, is a cryptographic checksum of the contents of the commit.  If I took this text, changed the names, and made a new commit from the result, I'd get a different commit hash ID.

Now, I could do that, and having done that, I could then copy all the immediate downstream commits—all the children of 83232e38648b51abbcbdb56c94632b6906cc85a6—to new and different commits that have my new commit as their parent(s).  Then I'd have to copy those commits' children, and their children's children, and so on, all in an effort to make you believe that my copy of 83232e38648b51abbcbdb56c94632b6906cc85a6 is the copy you should use.  If there are any signed commits, or signed annotated tags, in this copied chain, I'd be unable to sign them properly unless I had Junio Hamano's signing key.  So you might be able to tell that I did this—and even if there aren't any signing keys, you'd probably still be able to tell, because the Git repository I offered to you, with these copied replacements, would not match the copy you'd picked up earlier, with the originals in it.

So, the fact that the merge has Alice's name on it—assuming your GUI is not lying to you—means that the merge has Alice's name on it.  That doesn't mean that Alice actually made it, as Bob could have set his Git up to claim to be Alice for the duration of Bob making the merge.  If you want to verify who made the commit, you'll need some kind of digital signature as well, either on the commits, or on annotated tags.  (Signing each commit is a big pain, which is why the Git developers only sign their annotated tags.)

Why and how this happened is not something we can guess.  It's up to you whether to believe Bob when he says that he did not do it as a prank.  You'll have to observe it actually happening and investigate from there.

Title: Git shows wrong author after merge

Body:
Every commit object carries both fields, author and committer.  You can inspect the raw commit object using the command-line git cat-file -p operation.  For instance:

$ git cat-file -p 83232e38648b51abbcbdb56c94632b6906cc85a6 | sed 's/@/ /'
tree 894962f72d565687c409f018060fdefa20e5f3fe
parent aa8c8d914e4ae709e4fd025f359594f62653d9e5
author Junio C Hamano <gitster pobox.com> 1556175832 +0900
committer Junio C Hamano <gitster pobox.com> 1556178085 +0900

The seventh batch

Signed-off-by: Junio C Hamano <gitster pobox.com>

Once a commit is made, it cannot be changed: the hash ID of the commit, in this case 83232e38648b51abbcbdb56c94632b6906cc85a6, is a cryptographic checksum of the contents of the commit.  If I took this text, changed the names, and made a new commit from the result, I'd get a different commit hash ID.

Now, I could do that, and having done that, I could then copy all the immediate downstream commits—all the children of 83232e38648b51abbcbdb56c94632b6906cc85a6—to new and different commits that have my new commit as their parent(s).  Then I'd have to copy those commits' children, and their children's children, and so on, all in an effort to make you believe that my copy of 83232e38648b51abbcbdb56c94632b6906cc85a6 is the copy you should use.  If there are any signed commits, or signed annotated tags, in this copied chain, I'd be unable to sign them properly unless I had Junio Hamano's signing key.  So you might be able to tell that I did this—and even if there aren't any signing keys, you'd probably still be able to tell, because the Git repository I offered to you, with these copied replacements, would not match the copy you'd picked up earlier, with the originals in it.

So, the fact that the merge has Alice's name on it—assuming your GUI is not lying to you—means that the merge has Alice's name on it.  That doesn't mean that Alice actually made it, as Bob could have set his Git up to claim to be Alice for the duration of Bob making the merge.  If you want to verify who made the commit, you'll need some kind of digital signature as well, either on the commits, or on annotated tags.  (Signing each commit is a big pain, which is why the Git developers only sign their annotated tags.)

Why and how this happened is not something we can guess.  It's up to you whether to believe Bob when he says that he did not do it as a prank.  You'll have to observe it actually happening and investigate from there.


问:
How to get the difference between two lines
thanks for help
I have the following table in PostgreSQL

The columns are

```<code>ON = END - START
IDLE = START (LINE 2) - END (LINE 1)
</code>```

I need calculate "idle" using select ... The idle value is obtained using the start of line 2 subtracted from the end of line 1, following the example, the idle value 00:25 is 09:25 - 09:00.

I'm not able to create a logic for this, or the code for calculate it.

Here is my select

```<code>    select st.id,
       st.tvd_unidade,
       st.tvd_pdv,
       st.tvd_cupom,
       st.tvd_operador,
       min(st.tvd_data_hora) as start_at,
       max(en.tvd_data_hora) as end_at,
       max(en.tvd_data_hora) - min(st.tvd_data_hora) as produtivo
  from ger st
 inner join ger en on st.tvd_unidade = en.tvd_unidade and st.tvd_pdv = en.tvd_pdv and st.tvd_cupom = en.tvd_cupom
 where en.tvd_tipo_reg in ('FINN','FINn')
  and st.tvd_tipo_reg in ('INFN','INFn')
 group by 1
</code>```

答:
Before you worry about the maths, you need to be able to see all the data you need on one row. To see data from other rows, you use windowing functions. In this case, you could use the lag windowing function to look at the previous row - something like this

```<code>Select start, end, lag(end) over (order by [your sort key]) as lastEnd
from table
order by [your sort key]
</code>```

should give you the data you need. Once you're sure you've got the right data, then you can start doing the maths calculations for on and idle

Body:
thanks for help
I have the following table in PostgreSQL

The columns are

ON = END - START
IDLE = START (LINE 2) - END (LINE 1)

I need calculate "idle" using select ... The idle value is obtained using the start of line 2 subtracted from the end of line 1, following the example, the idle value 00:25 is 09:25 - 09:00.

I'm not able to create a logic for this, or the code for calculate it.

Here is my select

    select st.id,
       st.tvd_unidade,
       st.tvd_pdv,
       st.tvd_cupom,
       st.tvd_operador,
       min(st.tvd_data_hora) as start_at,
       max(en.tvd_data_hora) as end_at,
       max(en.tvd_data_hora) - min(st.tvd_data_hora) as produtivo
  from ger st
 inner join ger en on st.tvd_unidade = en.tvd_unidade and st.tvd_pdv = en.tvd_pdv and st.tvd_cupom = en.tvd_cupom
 where en.tvd_tipo_reg in ('FINN','FINn')
  and st.tvd_tipo_reg in ('INFN','INFn')
 group by 1

Body:
Before you worry about the maths, you need to be able to see all the data you need on one row. To see data from other rows, you use windowing functions. In this case, you could use the lag windowing function to look at the previous row - something like this

Select start, end, lag(end) over (order by [your sort key]) as lastEnd
from table
order by [your sort key]

should give you the data you need. Once you're sure you've got the right data, then you can start doing the maths calculations for on and idle


问:
How to speed up MPLAB X
MPLAB X takes 50 seconds to build, and more than a minute to program the PIC for debug after having built immediately before. Also seems slow when debugging. Will a multiprocessor pc run this program significantly faster, and what parameters should I look for when buying the pc?

Present arrangement is

HP xw6200, single processor Xeon 3.4GHz

installed ram 4GB

32 bit Windows 7 Professional

Using MPLAB X v3.50, compiler XC16 v1.30. Connected to ICD3 to run PIC24FJ128GA204.

Using 14% (about 12000 words) of PIC program memory.

答:
CONFIGURATION TIPS

To speed up compilation process turn on "parallel make" (Tools -> Options). See image 1 below.

It helps a lot, because if you have multiple source files in your project - compiler must be called many times to compile each file. Most of this work can be done in parallel.

Check "Maintain active connection to hardware tool" in "Tools" -> "Options" -> "Project options" tab.

This will save you a lot of time when debugging.

Take a look at MPLAB memory limit in your configuration.

I'm not sure, but I think that MPLAB installer checks how much RAM you have and sets memory limits according to hardware. If you upgraded RAM - you may need to reconfigure IDE memory limit.

Locate your mplab_ide.conf file, in my case (default installation directory):

C:\Program Files (x86)\Microchip\MPLABX\v5.15\mplab_platform\etc\mplab_ide.conf

and find line with "default_options":

default_options="-J-Dcore.properties.disableHttpProxy=true --branding
  mplab -J-Dcrownking.stream.verbosity=very-quiet -J-Xss8m -J-Xms512m
  -J-Xmx2G -J-XX:+UseConcMarkSweepGC  -J-Dapt.limit.expanded.params=1000 -J-Dplugin.manager.check.interval=EVERY_WEEK -J-Dsun.java2d.noddraw=false -J-Dorg.netbeans.modules.extbrowser.UseDesktopBrowse=true -J-Dnetbeans.importclass=org.netbeans.upgrade.AutoUpgrade"

NOTE: Please edit your own config file, this may be not suitable for your MPLAB version.

Most important parameter here is -J-Xmx. This is memory limit. I have set it to 4GB (-J-Xmx4G) because I have 24GB RAM, but I have never seen MPLAB using more than 2GB (when I work with 8-bit microcontrollers).

Current MPLAB is based on NetBeans, so you can take a look here if you need more details:

How to assign more memory to Netbeans?

You may turn off few plugins in IDE to speed up MPLAB loading process. I have turned off these (in Tools -> Plugins):

Mercurial

Database

Knockout HTML Editor

AngularJS Editor

CSS Preprocessors

and it looks like nothing bad happened.

I have tried to turn off some other plugins, but MPLAB Code Configurator depends on them so I gave up.

(NOT TESTED) If you are not using MPLAB Code Configurator you can try to turn it off (in Tools -> Plugins).

If your project is pretty old - you may want to take a look at your version control (maybe manual Local history feature cleanup is necessary). Or just re-create new project from scratch and add your files.

HARDWARE TIPS

Install MPLAB compilers on SSD disk.

Put your project on SSD disk.

More CPU cores can help a lot ("parallel make" must be turned on)

Configuring MPLAB to use more than 2GB RAM makes no difference (if there is nothing wrong with project, sources, local history, Git etc.).

Title: How to speed up MPLAB X


问:
Optimistic Locking in Rails not allowing record to be modified in the console
I'm working on the database locking to ensure the safe data transactions in a multi-user participation.

The machine is installed with Passenger.

After I added the 'lock_version'(integer), the record no long is able to be modified through console.

Let's say,

```<code>lesson = Lesson.find(1)
lesson.start_time = Time.now
lesson.save

=> then, ActiveRecord::StaleObjectError: Attempted to update a stale object: Lesson
</code>```

But, with a very rare chance, a column is saved, which makes me confused a lot.

The rails version is 4.2.8

Many thanks over many thoughts..!

Best

答:
SO it turns out that in order to use Optimistic Locking, I should've added lock_version with the initial value 0 (integer), not null. Although in Rails console record shows 0, but in the database it actually was null.
!</p>

Body:
I'm working on the database locking to ensure the safe data transactions in a multi-user participation.

The machine is installed with Passenger.

After I added the 'lock_version'(integer), the record no long is able to be modified through console.

Let's say,

lesson = Lesson.find(1)
lesson.start_time = Time.now
lesson.save

=> then, ActiveRecord::StaleObjectError: Attempted to update a stale object: Lesson

But, with a very rare chance, a column is saved, which makes me confused a lot.

The rails version is 4.2.8

Many thanks over many thoughts..!

Best


问:
Laravel-Snappy PDF Suddenly stopped working - Windows
I am using Snappy PDF(Windows 10 Local Development)

```<code>wkhtmltopdf --version
wkhtmltopdf 0.12.5 (with patched qt)
</code>```

config\snappy.php file looks like this

```<code><?php

return array(

    'pdf' => array(
        'enabled' => true,
        'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe"',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    ),

 );

</code>```

It suddenly stopped working

```<code>The exit status code '-1073740771' says something went wrong: stderr: "Loading pages (1/6) [> ] 0% [======> ] 10% [========> ] 14% [=================> ] 29% [=====================> ] 36% [========================> ] 41% QNetworkAccessFileBackendFactory: URL has no schema set, use file:// for files [==========================> ] 44% [===========================> ] 46% [=============================> ] 49% [============================================================] 100% " stdout: "" command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality --orientation "landscape" --page-size "a5" --footer-right "Page [page] of [topage]"
</code>```

This issue is only in the windows environment. I checked my production which is on Ubuntu 16.0.4 and it works perfectly fine.

答:
I have assigned the port 8080 to a Physical printer.
Corrected it and everything works fine now.</p>

Body:
I am using Snappy PDF(Windows 10 Local Development)

wkhtmltopdf --version
wkhtmltopdf 0.12.5 (with patched qt)

config\snappy.php file looks like this

<?php

return array(

    'pdf' => array(
        'enabled' => true,
        'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe"',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    ),

 );

It suddenly stopped working

The exit status code '-1073740771' says something went wrong: stderr: "Loading pages (1/6) [> ] 0% [======> ] 10% [========> ] 14% [=================> ] 29% [=====================> ] 36% [========================> ] 41% QNetworkAccessFileBackendFactory: URL has no schema set, use file:// for files [==========================> ] 44% [===========================> ] 46% [=============================> ] 49% [============================================================] 100% " stdout: "" command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality --orientation "landscape" --page-size "a5" --footer-right "Page [page] of [topage]"

This issue is only in the windows environment. I checked my production which is on Ubuntu 16.0.4 and it works perfectly fine.


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
On AS3, I had to convert a 2D array into a 1D array. The fastest (run speed) and easiest (coding time) solution was:

```<code>var new1DArray:Array = the2DArray.toString().split(",");
</code>```

Be surprised but it's actually working as intended and quite fast, too!

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

Body:
On AS3, I had to convert a 2D array into a 1D array. The fastest (run speed) and easiest (coding time) solution was:

var new1DArray:Array = the2DArray.toString().split(",");

Be surprised but it's actually working as intended and quite fast, too!

OwnerDisplayName: LiraNuna

LastEditorDisplayName: LiraNuna


问:
Request types on iPhone || Android?
Is it possible to send GET, POST, PUT and DELETE requests from iPhone || Android applications to a third party server?

I want to build a web service to reuse on all 3 platforms (3rd being the web app itself).

答: Yes, making HTTP requests on mobile devices running iOS or Android is no different from desktop Java or Cocoa. Both platforms offer API's that enable you to change the request method. Checkout NSURLConnection on iOS and the org.apache.http package on Android.

Title: Request types on iPhone || Android?


问:
qt error: undefined reference to `vtable for Thread'
I have the code:

```<code>#include <iostream>
#include <QThread>
#include <unistd.h>
#include <stdlib.h>
#include <QApplication>

using std::cerr;
using std::endl;

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread();
    ~Thread();
    void setMessage(const QString &_message);
    void stop();
protected:
    void run();
private:
    QString message;
    volatile bool stopped;
};

Thread::Thread()
{
    stopped = false;
    run();
}

Thread::~Thread()
{

}

void Thread::run()
{
    while(!stopped){
        cerr << qPrintable(message);
        sleep(1);
    }
        stopped = false;
        cerr << endl;
}

void Thread::stop()
{
    stopped = true;
}

void Thread::setMessage(const QString &_message)
{
    message = _message;
}

int main(int argc,char *argv[])
{
    QApplication app(argc, argv);
    Thread *A,*B;
    A = new Thread();
    B = new Thread();
    A->setMessage("Thread A\n");
    B->setMessage("Thread B\n");
//.run();
//.run();
    sleep(10);
    A->stop();
    B->stop();
    return 0;
}
</code>```

and i have error

```<code>g++ -Wl,--hash-style=gnu -Wl,--as-needed -Wl,-O1 -o tmp main.o    -L/usr/lib -lQtGui -lQtCore -lpthread
main.o: In function `Thread::~Thread()':
main.cpp:(.text+0xa): undefined reference to `vtable for Thread'
main.o: In function `Thread::Thread()':
main.cpp:(.text+0x1da): undefined reference to `vtable for Thread'
collect2: ld returned 1 exit status
make: *** [tmp] Error 1
</code>```

答: I think that the qmake system requires that your header file include  directly.  Mine was failing to generate a moc until I added that include.

Body:
I have the code:

#include <iostream>
#include <QThread>
#include <unistd.h>
#include <stdlib.h>
#include <QApplication>

using std::cerr;
using std::endl;

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread();
    ~Thread();
    void setMessage(const QString &_message);
    void stop();
protected:
    void run();
private:
    QString message;
    volatile bool stopped;
};

Thread::Thread()
{
    stopped = false;
    run();
}

Thread::~Thread()
{

}

void Thread::run()
{
    while(!stopped){
        cerr << qPrintable(message);
        sleep(1);
    }
        stopped = false;
        cerr << endl;
}

void Thread::stop()
{
    stopped = true;
}

void Thread::setMessage(const QString &_message)
{
    message = _message;
}

int main(int argc,char *argv[])
{
    QApplication app(argc, argv);
    Thread *A,*B;
    A = new Thread();
    B = new Thread();
    A->setMessage("Thread A\n");
    B->setMessage("Thread B\n");
//.run();
//.run();
    sleep(10);
    A->stop();
    B->stop();
    return 0;
}

and i have error

g++ -Wl,--hash-style=gnu -Wl,--as-needed -Wl,-O1 -o tmp main.o    -L/usr/lib -lQtGui -lQtCore -lpthread
main.o: In function `Thread::~Thread()':
main.cpp:(.text+0xa): undefined reference to `vtable for Thread'
main.o: In function `Thread::Thread()':
main.cpp:(.text+0x1da): undefined reference to `vtable for Thread'
collect2: ld returned 1 exit status
make: *** [tmp] Error 1


问:
How to make python functions bind enclosing variable to value rather than to name
In python functions its perfectly legal to reference variables from enclosing scopes. These variables refer to whatever value they posses at the time the function is called. So, for instance

x = 1 # unused
def foo(y):
    return x+y

x=10
print(foo(1)) # prints 11
x=11
print(foo(1)) # prints 12
```

<p>is it possible to make the variable <code>x</code> be frozen to whatever the value of <code>x</code> was at creation time? That is, I want the <code>x</code> in <code>foo</code> to bind to the value of the outer <code>x</code> rather than its name. Basically the behavior I want is</p>

<pre class="lang-py prettyprint-override"><code>x = 1
def foo(y):
    return 1+y # I'd rather not hard code the value of x here

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
</code>```

I currently have a working solution, but It's not very readable, I think there might be a better solution (a decorator perhaps?)

my solution

x = 1
def wrapper():
    local_x = x
    def foo(y):
        return local_x+y
    return foo
foo = wrapper()

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
```

答:
You can also take advantage of a default argument:</p>

```<code>x = 1
def foo(y, x=x):
    return x + y

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
</code>```

Body:
In python functions its perfectly legal to reference variables from enclosing scopes. These variables refer to whatever value they posses at the time the function is called. So, for instance

x = 1 # unused
def foo(y):
    return x+y

x=10
print(foo(1)) # prints 11
x=11
print(foo(1)) # prints 12

is it possible to make the variable x be frozen to whatever the value of x was at creation time? That is, I want the x in foo to bind to the value of the outer x rather than its name. Basically the behavior I want is

x = 1
def foo(y):
    return 1+y # I'd rather not hard code the value of x here

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2

I currently have a working solution, but It's not very readable, I think there might be a better solution (a decorator perhaps?)

my solution

x = 1
def wrapper():
    local_x = x
    def foo(y):
        return local_x+y
    return foo
foo = wrapper()

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2

Body:
You can also take advantage of a default argument:

x = 1
def foo(y, x=x):
    return x + y

x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2


问:
Pandas - Identify if a date in a pandas column is falls on Saturday or Sunday
I want to identify if a date value is on a Saturday or Sunday. If it is, then I want to change said date to the friday prior. (example df and result df below - these are real dates from May 2019, as you can see there is a Saturday(5/4/19) and Sunday(5/26/19) date pulled into the week prior in the results df. The (5/2/19) date stays the same as it is a weekday not a weekend.

```<code>import pandas as pd
data = [['5/3/19','5/4/19'],['5/3/19','5/2/19'],['5/24/19','5/26/19']]
df = pd.DataFrame(data,columns=['Date1','Date2'])
print(df)

data2 = [['5/3/19','5/3/19'],['5/3/19','5/2/19'],['5/24/19','5/24/19']]
resultsdf = pd.DataFrame(data2,columns=['Date1','Date2'])
print(resultsdf)
</code>```

I am running this code for a Month to Date range. I have to have the code to group a large data set into a MTD view - but I am having trouble creating variables for a list of sat/sunday ( as there will be 8-10 weekend dates per month) Here is my code:

```<code>import pandas as pd
import xlrd # added when using visual studio
import datetime
from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d')
month_day = today.day
start_month_scope = today - pd.to_timedelta(month_day, unit = 'd')
first_day_of_month = start_month_scope + pd.to_timedelta(1, unit = 'd')
</code>```

The problem with the code below is that is only works if I need to find the saturday & sunday on 7 day (M-f) period.

```<code>last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_fri = last_sunday - pd.to_timedelta(2, unit='d')
</code>```

I need some variable to input to the code below:

```<code>finaldf.loc[(finaldf['Due_Date'] == last_sat), 'Due_Date'] = last_fri
</code>```

So 'last_fri' would be just the most recent friday from the given saturday or sunday, so referencing my example df there is the 5/4/19 example which gets pulled back into a 5/3/19 (the last friday for that instance) or the 5/26/19 gets pulled back to 5/24/19. As you can see the code would have to understand first if the date is saturday and sunday then next what is the closest friday prior.

* if all the above got confusing please just reference my df -> resulftdf *

答:
In your case using BDay with np.where

```<code>df=df.apply(pd.to_datetime)
from pandas.tseries.offsets import BDay
for x in df.columns:
    df[x]=np.where(df[x].dt.weekday.isin([5,6]),df[x]-BDay(1),df[x])

df
Out[623]:
       Date1      Date2
0 2019-05-03 2019-05-03
1 2019-05-03 2019-05-02
2 2019-05-24 2019-05-24
</code>```

Body:
I want to identify if a date value is on a Saturday or Sunday. If it is, then I want to change said date to the friday prior. (example df and result df below - these are real dates from May 2019, as you can see there is a Saturday(5/4/19) and Sunday(5/26/19) date pulled into the week prior in the results df. The (5/2/19) date stays the same as it is a weekday not a weekend.

import pandas as pd
data = [['5/3/19','5/4/19'],['5/3/19','5/2/19'],['5/24/19','5/26/19']]
df = pd.DataFrame(data,columns=['Date1','Date2'])
print(df)

data2 = [['5/3/19','5/3/19'],['5/3/19','5/2/19'],['5/24/19','5/24/19']]
resultsdf = pd.DataFrame(data2,columns=['Date1','Date2'])
print(resultsdf)

I am running this code for a Month to Date range. I have to have the code to group a large data set into a MTD view - but I am having trouble creating variables for a list of sat/sunday ( as there will be 8-10 weekend dates per month) Here is my code:

import pandas as pd
import xlrd # added when using visual studio
import datetime
from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d')
month_day = today.day
start_month_scope = today - pd.to_timedelta(month_day, unit = 'd')
first_day_of_month = start_month_scope + pd.to_timedelta(1, unit = 'd')

The problem with the code below is that is only works if I need to find the saturday & sunday on 7 day (M-f) period.

last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_fri = last_sunday - pd.to_timedelta(2, unit='d')

I need some variable to input to the code below:

finaldf.loc[(finaldf['Due_Date'] == last_sat), 'Due_Date'] = last_fri

So 'last_fri' would be just the most recent friday from the given saturday or sunday, so referencing my example df there is the 5/4/19 example which gets pulled back into a 5/3/19 (the last friday for that instance) or the 5/26/19 gets pulled back to 5/24/19. As you can see the code would have to understand first if the date is saturday and sunday then next what is the closest friday prior.

* if all the above got confusing please just reference my df -> resulftdf *

Body:
In your case using BDay with np.where

df=df.apply(pd.to_datetime)
from pandas.tseries.offsets import BDay
for x in df.columns:
    df[x]=np.where(df[x].dt.weekday.isin([5,6]),df[x]-BDay(1),df[x])

df
Out[623]:
       Date1      Date2
0 2019-05-03 2019-05-03
1 2019-05-03 2019-05-02
2 2019-05-24 2019-05-24


问:
Warning: filter_var() expects parameter 2 to be long, string given in
In this code I get a warning

Warning: filter_var() expects parameter 2 to be long, string given in the last line

```<code>$check = filter_var($email, FILTER_SANITIZE_EMAIL);
$str = filter_var($name, FILTER_SANITIZE_STRING);
if (!filter_var($check, FILTER_VALIDATE_EMAIL) && !filter_var($str, FILTER_VALIDATE_STRING)) { //here
</code>```

The problem is this, because without it no exists any warning message

```<code> !filter_var($str, FILTER_VALIDATE_STRING)
</code>```

What is the reason of this error?

答: There is no such filter as FILTER_VALIDATE_STRING... could you just use is_string?</p>

Body:
In this code I get a warning

Warning: filter_var() expects parameter 2 to be long, string given in the last line

$check = filter_var($email, FILTER_SANITIZE_EMAIL);
$str = filter_var($name, FILTER_SANITIZE_STRING);
if (!filter_var($check, FILTER_VALIDATE_EMAIL) && !filter_var($str, FILTER_VALIDATE_STRING)) { //here

The problem is this, because without it no exists any warning message

 !filter_var($str, FILTER_VALIDATE_STRING)

What is the reason of this error?


问:
mkdir no such file or directory syntax error?
I'm trying to auto-create an auto folder that is unique. Therefore i'm trying to name the folder after a date time stamp.

the code below is what i have already tried.

```<code>#! /bin/bash
d_space=$(date)
d_nospace= echo ${d_space//[[:blanl:]]/}
echo $d_nospace
mkdir -p "$d_nospace"

WedMay2920:52:47EDT2019
mkdir: cannot create directory '': No such file or directory
</code>```

答:
```<code>d_nospace= echo ${d_space//[[:blanl:]]/}
</code>```

You're missing a $(...) capture operator. There shouldn't be a space after the equal sign. And blanl should be blank.

```<code>d_nospace=$(echo ${d_space//[[:blank:]]/})
</code>```

Let's get rid of the useless use of echo. There's no need to echo a variable out and then capture the output. Just assign the variable directly.

```<code>d_nospace=${d_space//[[:blank:]]/}
</code>```

(You don't have to get rid of the spaces, by the way. Directory names can contain whitespace, it's fine.)

Body:
I'm trying to auto-create an auto folder that is unique. Therefore i'm trying to name the folder after a date time stamp.

the code below is what i have already tried.

#! /bin/bash
d_space=$(date)
d_nospace= echo ${d_space//[[:blanl:]]/}
echo $d_nospace
mkdir -p "$d_nospace"

WedMay2920:52:47EDT2019
mkdir: cannot create directory '': No such file or directory

Body:
d_nospace= echo ${d_space//[[:blanl:]]/}

You're missing a $(...) capture operator. There shouldn't be a space after the equal sign. And blanl should be blank.

d_nospace=$(echo ${d_space//[[:blank:]]/})

Let's get rid of the useless use of echo. There's no need to echo a variable out and then capture the output. Just assign the variable directly.

d_nospace=${d_space//[[:blank:]]/}

(You don't have to get rid of the spaces, by the way. Directory names can contain whitespace, it's fine.)


问:
Getting data from file stream in c
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

```<code>char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);
</code>```

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

答:
Easy and straightforward way is to use fseek() and ftell(). After retrieving the size of the file, allocate buffer for the data and read the file in with fread().

This example is a very common way to retrieve the exact size of the file.

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

/* excepts file stream which is already opened */
long get_filesize(FILE *fp)
{
    long filesize;

    if( fseek(fp, 0, SEEK_END) ) != 0)
        exit(EXIT_FAILURE); /* exit with errorcode if fseek() fails */

    filesize = ftell(fp);

    rewind(fp);

    return filesize;
}

int main(void)
{
    FILE *fp;
    long filesize;
    unsigned char *buffer;

    fp = fopen("info.dat", "rb");

    filesize = get_filesize(fp);
    if(filesize < 1) exit(EXIT_FAILURE);

    buffer = malloc( filesize * sizeof(unsigned char) );
    if(buffer == NULL) exit(EXIT_FAILURE);

    /* checking the fread return value is not necessary but recommended */
    if((fread(buffer, sizeof(unsigned char), filesize, fp)) != filesize)
        exit(EXIT_FAILURE);

    fclose(fp);

    /* ===== use the file here ===== */

    free(buffer); /* remember to free the memory */

    return EXIT_SUCCESS;
}
</code>```

Title: Getting data from file stream in c

Body:
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

Body:
Easy and straightforward way is to use fseek() and ftell(). After retrieving the size of the file, allocate buffer for the data and read the file in with fread().

This example is a very common way to retrieve the exact size of the file.

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

/* excepts file stream which is already opened */
long get_filesize(FILE *fp)
{
    long filesize;

    if( fseek(fp, 0, SEEK_END) ) != 0)
        exit(EXIT_FAILURE); /* exit with errorcode if fseek() fails */

    filesize = ftell(fp);

    rewind(fp);

    return filesize;
}

int main(void)
{
    FILE *fp;
    long filesize;
    unsigned char *buffer;

    fp = fopen("info.dat", "rb");

    filesize = get_filesize(fp);
    if(filesize < 1) exit(EXIT_FAILURE);

    buffer = malloc( filesize * sizeof(unsigned char) );
    if(buffer == NULL) exit(EXIT_FAILURE);

    /* checking the fread return value is not necessary but recommended */
    if((fread(buffer, sizeof(unsigned char), filesize, fp)) != filesize)
        exit(EXIT_FAILURE);

    fclose(fp);

    /* ===== use the file here ===== */

    free(buffer); /* remember to free the memory */

    return EXIT_SUCCESS;
}


问:
Need many to many relationship for multiple properties on one entity EF Core 2.2
I have an entity for Users and an entity for Projects.

I need to be able to assign multiple users to 3 different list properties on my project entity.  I have been able to do this successfully for one property (the many to many relationship) by a join entity.  I could specify the UserType on the Users table and just use the one property, but I may run into scenarios where Users may perform more than one role (type) and then that wouldn't work.

I thought I could just put the UserType on the join table (entity) but I'm at a loss as to how to build that entity in my DBContext.

Here is what I have that's working with one property defined:

ProjectEntity:

```<code>public class Project : IInt32Identity
{
    public int Id { get; set; }
    public string ProjectName { get; set; }
    ...
    public bool ProjectActive { get; set; }
    public List<ProjectFile> ProjectFiles { get; set; }
    public List<ProjectUsers> ProjectUsers { get; set; }
    public DateTime ProjectCreatedDate { get; set; }
    public DateTime ProjectModifiedDate { get; set; }
}
</code>```

UserEntity:

```<code>public class User : IInt32Identity
{
    public int Id { get; set; }
    public string UserEmail { get; set; }
    ...
    public List<ProjectUsers> ProjectUsers { get; set; }
    public DateTime UserCreatedDate { get; set; }
    public DateTime UserLastLoggedInDate { get; set; }
    public DateTime UserModifiedDate { get; set; }
}
</code>```

JoinEntity:

```<code>public class ProjectUsers
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int ProjectId { get; set; }
    public Project Project { get; set; }
}
</code>```

And my OnModelCreating() in my DBContext

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProjectUsers>()
            .HasKey(bc => new { bc.UserId, bc.ProjectId });
        modelBuilder.Entity<ProjectUsers>()
            .HasOne(bc => bc.User)
            .WithMany(b => b.ProjectUsers)
            .HasForeignKey(bc => bc.UserId);
        modelBuilder.Entity<ProjectUsers>()
            .HasOne(bc => bc.Project)
            .WithMany(c => c.ProjectUsers)
            .HasForeignKey(bc => bc.ProjectId);
    }
</code>```

That all works fine as I said above, but here's what I would like:

ProjectEntity:

```<code>public class Project : IInt32Identity
{
    public int Id { get; set; }
    public string ProjectName { get; set; }
    ...
    public bool ProjectActive { get; set; }
    public List<ProjectFile> ProjectFiles { get; set; }
    public List<ProjectUsers> ProjectClients { get; set; }
    public List<ProjectUsers> ProjectBuilders { get; set; }
    public List<ProjectUsers> ProjectDesigners { get; set; }
    public DateTime ProjectCreatedDate { get; set; }
    public DateTime ProjectModifiedDate { get; set; }
}
</code>```

UserEntity is the same.

JoinEntity:

```<code>public class ProjectUsers
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int ProjectId { get; set; }
    public Project Project { get; set; }
    public string UserType { get; set; }
}
</code>```

Where I'm lost is on the OnModelBinding() code and I'm also not sure if EF would be smart enough to populate the lists correctly based on that UserType meta property.

Any help or guidance would be greatly appreciated.

TIA

答:
It might seem possible to treat ProjectUser as the base class/entity, and create different class/entity/type for ProjectClient, ProjectBuilder and ProjectDesigner that are inherited from ProjectUser. And then you create tables for each type and one-to-many relationship to the project. This is typically called Table Per Type (TPT) approach.

However, TPT is not yet implemented in EF Core.

You can still achieve it using Table Per Hierarchy (TPH), but you will have just one list in the project for all project users, where UserId, ProjectId and UserType become the complex key. Project clients, builders and designers will be calculated properties off that one project user list.

Entities

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ProjectUser> ProjectUsers { get; set; }

    public IEnumerable<ProjectUser> ProjectClients => this.ProjectUsers
        .Where(x => x.UserType == "Client");
    public IEnumerable<ProjectUser> ProjectBuilders => this.ProjectUsers
        .Where(x => x.UserType == "Builder");
    public IEnumerable<ProjectUser> ProjectDesigners => this.ProjectUsers
        .Where(x => x.UserType == "Designer");
}

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }

    public virtual ICollection<ProjectUser> UserProjects { get; set; }
}

public class ProjectUser
{
    public int UserId { get; set; }
    public virtual User User { get; set; }

    public int ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public string UserType { get; set; }
}
```

<h3>Configurations</h3>

<pre class="lang-cs prettyprint-override"><code>public class ProjectConfiguration : IEntityTypeConfiguration<Project>
{
    public void Configure(EntityTypeBuilder<Project> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Name).IsRequired();
        builder.HasIndex(x => x.Name).IsUnique();

        builder.Ignore(x => x.ProjectBuilders);
        builder.Ignore(x => x.ProjectClients);
        builder.Ignore(x => x.ProjectDesigners);

        builder.ToTable("Project");
    }
}

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Email).IsRequired();
        builder.HasIndex(x => x.Email).IsUnique();

        builder.ToTable("User");
    }
}

public class ProjectUserConfiguration : IEntityTypeConfiguration<ProjectUser>
{
    public void Configure(EntityTypeBuilder<ProjectUser> builder)
    {
        builder.HasKey(x => new { x.ProjectId, x.UserId, x.UserType });
        builder.Property(x => x.UserType).IsRequired();

        builder.HasOne(x => x.Project)
            .WithMany(x => x.ProjectUsers)
            .HasForeignKey(x => x.ProjectId);

        builder.HasOne(x => x.User)
            .WithMany(x => x.UserProjects)
            .HasForeignKey(x => x.UserId);
    }
}
</code>```

The virtual keyword is there for lazy loading support. If you're not doing lazy loading, you don't have to have virtual there. Also you have to [NotMapped] those 3 calculated properties, which is the same as using .Ignore in fluent API's speaking.

DbContext

public class AppDbContext : DbContext
{
    public DbSet<Project> Projects { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfiguration(new ProjectConfiguration());
        modelBuilder.ApplyConfiguration(new UserConfiguration());
        modelBuilder.ApplyConfiguration(new ProjectUserConfiguration());
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=DL.SO.ProjectUsersDemo;Integrated Security=True;MultipleActiveResultSets=False;");
    }
}
```

Nothing special here. After you add the migration and update the database, yours should look like

After seeding the database with sample data, although it's hard to show here, you can see those 3 lists are filled with correct data:

Body:
I have an entity for Users and an entity for Projects.

I need to be able to assign multiple users to 3 different list properties on my project entity.  I have been able to do this successfully for one property (the many to many relationship) by a join entity.  I could specify the UserType on the Users table and just use the one property, but I may run into scenarios where Users may perform more than one role (type) and then that wouldn't work.

I thought I could just put the UserType on the join table (entity) but I'm at a loss as to how to build that entity in my DBContext.

Here is what I have that's working with one property defined:

ProjectEntity:

public class Project : IInt32Identity
{
    public int Id { get; set; }
    public string ProjectName { get; set; }
    ...
    public bool ProjectActive { get; set; }
    public List<ProjectFile> ProjectFiles { get; set; }
    public List<ProjectUsers> ProjectUsers { get; set; }
    public DateTime ProjectCreatedDate { get; set; }
    public DateTime ProjectModifiedDate { get; set; }
}

UserEntity:

public class User : IInt32Identity
{
    public int Id { get; set; }
    public string UserEmail { get; set; }
    ...
    public List<ProjectUsers> ProjectUsers { get; set; }
    public DateTime UserCreatedDate { get; set; }
    public DateTime UserLastLoggedInDate { get; set; }
    public DateTime UserModifiedDate { get; set; }
}

JoinEntity:

public class ProjectUsers
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int ProjectId { get; set; }
    public Project Project { get; set; }
}

And my OnModelCreating() in my DBContext

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProjectUsers>()
            .HasKey(bc => new { bc.UserId, bc.ProjectId });
        modelBuilder.Entity<ProjectUsers>()
            .HasOne(bc => bc.User)
            .WithMany(b => b.ProjectUsers)
            .HasForeignKey(bc => bc.UserId);
        modelBuilder.Entity<ProjectUsers>()
            .HasOne(bc => bc.Project)
            .WithMany(c => c.ProjectUsers)
            .HasForeignKey(bc => bc.ProjectId);
    }

That all works fine as I said above, but here's what I would like:

ProjectEntity:

public class Project : IInt32Identity
{
    public int Id { get; set; }
    public string ProjectName { get; set; }
    ...
    public bool ProjectActive { get; set; }
    public List<ProjectFile> ProjectFiles { get; set; }
    public List<ProjectUsers> ProjectClients { get; set; }
    public List<ProjectUsers> ProjectBuilders { get; set; }
    public List<ProjectUsers> ProjectDesigners { get; set; }
    public DateTime ProjectCreatedDate { get; set; }
    public DateTime ProjectModifiedDate { get; set; }
}

UserEntity is the same.

JoinEntity:

public class ProjectUsers
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int ProjectId { get; set; }
    public Project Project { get; set; }
    public string UserType { get; set; }
}

Where I'm lost is on the OnModelBinding() code and I'm also not sure if EF would be smart enough to populate the lists correctly based on that UserType meta property.

Any help or guidance would be greatly appreciated.

TIA

Body:
It might seem possible to treat ProjectUser as the base class/entity, and create different class/entity/type for ProjectClient, ProjectBuilder and ProjectDesigner that are inherited from ProjectUser. And then you create tables for each type and one-to-many relationship to the project. This is typically called Table Per Type (TPT) approach.

However, TPT is not yet implemented in EF Core.

You can still achieve it using Table Per Hierarchy (TPH), but you will have just one list in the project for all project users, where UserId, ProjectId and UserType become the complex key. Project clients, builders and designers will be calculated properties off that one project user list.

Entities

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ProjectUser> ProjectUsers { get; set; }

    public IEnumerable<ProjectUser> ProjectClients => this.ProjectUsers
        .Where(x => x.UserType == "Client");
    public IEnumerable<ProjectUser> ProjectBuilders => this.ProjectUsers
        .Where(x => x.UserType == "Builder");
    public IEnumerable<ProjectUser> ProjectDesigners => this.ProjectUsers
        .Where(x => x.UserType == "Designer");
}

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }

    public virtual ICollection<ProjectUser> UserProjects { get; set; }
}

public class ProjectUser
{
    public int UserId { get; set; }
    public virtual User User { get; set; }

    public int ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public string UserType { get; set; }
}

Configurations

public class ProjectConfiguration : IEntityTypeConfiguration<Project>
{
    public void Configure(EntityTypeBuilder<Project> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Name).IsRequired();
        builder.HasIndex(x => x.Name).IsUnique();

        builder.Ignore(x => x.ProjectBuilders);
        builder.Ignore(x => x.ProjectClients);
        builder.Ignore(x => x.ProjectDesigners);

        builder.ToTable("Project");
    }
}

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Email).IsRequired();
        builder.HasIndex(x => x.Email).IsUnique();

        builder.ToTable("User");
    }
}

public class ProjectUserConfiguration : IEntityTypeConfiguration<ProjectUser>
{
    public void Configure(EntityTypeBuilder<ProjectUser> builder)
    {
        builder.HasKey(x => new { x.ProjectId, x.UserId, x.UserType });
        builder.Property(x => x.UserType).IsRequired();

        builder.HasOne(x => x.Project)
            .WithMany(x => x.ProjectUsers)
            .HasForeignKey(x => x.ProjectId);

        builder.HasOne(x => x.User)
            .WithMany(x => x.UserProjects)
            .HasForeignKey(x => x.UserId);
    }
}

The virtual keyword is there for lazy loading support. If you're not doing lazy loading, you don't have to have virtual there. Also you have to [NotMapped] those 3 calculated properties, which is the same as using .Ignore in fluent API's speaking.

DbContext

public class AppDbContext : DbContext
{
    public DbSet<Project> Projects { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfiguration(new ProjectConfiguration());
        modelBuilder.ApplyConfiguration(new UserConfiguration());
        modelBuilder.ApplyConfiguration(new ProjectUserConfiguration());
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=DL.SO.ProjectUsersDemo;Integrated Security=True;MultipleActiveResultSets=False;");
    }
}

Nothing special here. After you add the migration and update the database, yours should look like

After seeding the database with sample data, although it's hard to show here, you can see those 3 lists are filled with correct data:


问:
Code signing is failing after running unit tests
I recently updated to Xcode 8 and converted my code to Swift 3. Now my unit testing are failing, probably as they should, but then code signing are failing when trying to run again.

I use several CocoaPods, but they have worked previously. Everything work outside of UnitTesting.

The only fix I found so far is to clear CMD+ALT+K and rebuild solution.

Does anyone have a permanent fix for this?

Error

```<code>/Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app: replacing existing signature
/Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app: code object is not signed at all
In subcomponent: /Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app/Contents/PlugIns/***Tests.xctest
Command /usr/bin/codesign failed with exit code 1
</code>```

Edit: When running UnitTests which are all successful the code signing still fails on second run. Basically I have to clean the build before each test run.

答: What worked for me was to go to the test target and turn on "Automatically manage signing." My app already had automatic signing turned on, so I'm thinking something is amiss in Xcode when automatic signing is not turned on for the test target as well.

Body:
I recently updated to Xcode 8 and converted my code to Swift 3. Now my unit testing are failing, probably as they should, but then code signing are failing when trying to run again.

I use several CocoaPods, but they have worked previously. Everything work outside of UnitTesting.

The only fix I found so far is to clear CMD+ALT+K and rebuild solution.

Does anyone have a permanent fix for this?

Error

/Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app: replacing existing signature
/Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app: code object is not signed at all
In subcomponent: /Users/***/Library/Developer/Xcode/DerivedData/***-bbpdbvqjecpwzvfliyyqcnarjvua/Build/Products/Pro Debug/***.app/Contents/PlugIns/***Tests.xctest
Command /usr/bin/codesign failed with exit code 1

Edit: When running UnitTests which are all successful the code signing still fails on second run. Basically I have to clean the build before each test run.


问:
Build and Deploy a Maven Project to Nexus via Jenkins
I have configured a simple maven freestyle project. I was able to successfully build the project but not deploy to Nexus. I get this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.1:deploy (default-deploy) on project eqs_utility: Failed to deploy artifacts: Could not find artifact com.companyName.eqs:eqs_utility:jar:1.0.1-20190529.191240-1 in nexus (https://nexus.companyRepo.com/repository/maven-snapshot/) -> [Help 1]

I have tried to change configurations to simplify the project but still nothing. Setting.xml changes.

EDITED
I added the following to my POM.xml

```<code>    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>nexus</id>
            <name>Company Nexus Repository</name>
            <url>https://nexus.mycompany.com/repository/maven-release/</url>
            </repository>
        <snapshotRepository>
            <uniqueVersion>true</uniqueVersion>
            <id>nexus</id>
            <name>Company Nexus Snapshots</name>
            <url>https://nexus.companyName.com/repository/maven-snapshot/</url>
        </snapshotRepository>
    </distributionManagement>
</code>```

Then, updated my settings.xml with  this

```<code><server>
      <id>nexus</id>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
    </server>

    <!-- Another sample, using keys to authenticate. -->
    <server>
      <id>nexus</id>
      <username>NexusUser</username>
      <password>MyLongTokenValueHere</password>
    </server>
</code>```

答:
According to  Apache Maven Deploy Plugin setup

You need a section:

```<code>  <distributionManagement>
    <repository>
      <id>internal.repo</id>
      <name>MyCo Internal Repository</name>
      <url>Host to Company Repository</url>
    </repository>
  </distributionManagement>
</code>```

As you're using Nexus, you probably need a section in the pom that aligns with your nexus repositories (one for snapshots and one for release artifacts since you can't combine them in nexus):

```<code><distributionManagement>
   <repository>
      <id>mavenrepository</id>
      <url>http://mavenrepository.companyName.com/nexus/content/repositories/m3</url>
   </repository>
   <snapshotRepository>
      <id>tmavenrepository</id>
      <url>http://mavenrepository.companyName.com/nexus/content/repositories/m3-snapshots</url>
   </snapshotRepository>
</distributionManagement>
</code>```

Plus of course, in your local settings or other private location

```<code>    <server>
      <id>mavenrepository</id>
      <username>maven</username>
      <password>foobar</password>
    </server>
</code>```

This is described by Sonatype and cleaner by others.

Body:
I have configured a simple maven freestyle project. I was able to successfully build the project but not deploy to Nexus. I get this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.1:deploy (default-deploy) on project eqs_utility: Failed to deploy artifacts: Could not find artifact com.companyName.eqs:eqs_utility:jar:1.0.1-20190529.191240-1 in nexus (https://nexus.companyRepo.com/repository/maven-snapshot/) -> [Help 1]

I have tried to change configurations to simplify the project but still nothing. Setting.xml changes.

EDITED
I added the following to my POM.xml

    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>nexus</id>
            <name>Company Nexus Repository</name>
            <url>https://nexus.mycompany.com/repository/maven-release/</url>
            </repository>
        <snapshotRepository>
            <uniqueVersion>true</uniqueVersion>
            <id>nexus</id>
            <name>Company Nexus Snapshots</name>
            <url>https://nexus.companyName.com/repository/maven-snapshot/</url>
        </snapshotRepository>
    </distributionManagement>

Then, updated my settings.xml with  this

<server>
      <id>nexus</id>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
    </server>

    <server>
      <id>nexus</id>
      <username>NexusUser</username>
      <password>MyLongTokenValueHere</password>
    </server>

Body:
According to  Apache Maven Deploy Plugin setup

You need a section:

  <distributionManagement>
    <repository>
      <id>internal.repo</id>
      <name>MyCo Internal Repository</name>
      <url>Host to Company Repository</url>
    </repository>
  </distributionManagement>

As you're using Nexus, you probably need a section in the pom that aligns with your nexus repositories (one for snapshots and one for release artifacts since you can't combine them in nexus):

<distributionManagement>
   <repository>
      <id>mavenrepository</id>
      <url>http://mavenrepository.companyName.com/nexus/content/repositories/m3</url>
   </repository>
   <snapshotRepository>
      <id>tmavenrepository</id>
      <url>http://mavenrepository.companyName.com/nexus/content/repositories/m3-snapshots</url>
   </snapshotRepository>
</distributionManagement>

Plus of course, in your local settings or other private location

    <server>
      <id>mavenrepository</id>
      <username>maven</username>
      <password>foobar</password>
    </server>

This is described by Sonatype and cleaner by others.