问:
substracting date times in pandas
i've data frame is this

```<code>In[1]: df1
Out[1]
   Loan Date Negotiation
   2019-03-31
   2019-03-31
   2019-03-31

as Loan Date Negotiation           datetime64[ns]
</code>```

so i wanna make function to subtract 2 days from it. if last the day of the month is sunday, i will subtract 2 days from it.

From dataframe above, 2019-03-31 Is sunday,

i've tried but it's fail, this is

```<code> def subtractingDate(dateTime):
     dateTimestamp = pd.Timestamp(dateTime)
     newDate = dateTimestamp - pd.Timedelta("2 days")
     return newDate

 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])

*note: 6 is for sunday

So the error is

TypeError                                 Traceback (most recent call last)
<ipython-input-9-cc2a3348e6ce> in <module>
     16 # a = subtractingDate(dfMARET["Loan Date Negotiation"])
     17 # a
---> 18 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])
     19 dfMARET
     20

<ipython-input-9-cc2a3348e6ce> in subtractingDate(dateTime)
     10
     11 def subtractingDate(dateTime):
---> 12     dateTimestamp = pd.Timestamp(dateTime)
     13     newDate = dateTimestamp - pd.Timedelta(days = 2)
     14     return newDate

pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps.Timestamp.__new__()

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.convert_to_tsobject()```

```

<p><strong>so my expectation would be</strong></p>

``` Loan Date Negotiation
 2019-03-29
 2019-03-29
 2019-03-29
```

Ther's solution in pandas?

thank's

答:
If you need to convert datetime64 to Timestamp first, you can use:

```<code>df['Date'] = [pd.Timestamp(x) for x in df['Date']]
</code>```

and use timedelta():

```<code>from datetime import datetime, timedelta
dt = pd.Timestamp(2019,3,31)
new_dt = dt-timedelta(days=2)

new_dt
> datetime.datetime(2019, 3, 29, 0, 0)

new_dt.strftime('%Y-%m-%d')
> '2019-03-29'
</code>```

Or on whole column Date with:

```<code>df['New_Date'] = df['Date']-timedelta(days=2)
</code>```

EDIT: Full example:

```<code>import numpy as np
from datetime import datetime, timedelta

df1 = pd.DataFrame([[np.datetime64(datetime(2019, 3, 31))],
                    [np.datetime64(datetime(2019, 3, 27))],
                    [np.datetime64(datetime(2019, 3, 24))]],
                   columns=['Loan Date Negotiation'])
df1
</code>```

```<code>df1['Loan Date Negotiation'].dtype
> dtype('<M8[ns]')
</code>```

M8[ns] is a specific type of datetime64[ns], so there should be no difference in further processing.

If you want to subtract two days only if the day is a sunday, you can use np.where():

```<code>df1['New_Date'] = np.where(df1['Loan Date Negotiation'].dt.dayofweek==6,
         df1['Loan Date Negotiation']-timedelta(days=2),
         df1['Loan Date Negotiation'])
</code>```

Dates at index 0 and 2 were sundays and got 2 days subtracted. Date at index 1 was not touched.

Alternative via list comprehension over every single Timestamp

```<code>df1['New_Date'] = [x-timedelta(days=2) if x.weekday()==6 else x for x in df1['Loan Date Negotiation']]
</code>```

Title: substracting date times in pandas

Body:
i've data frame is this

In[1]: df1
Out[1]
   Loan Date Negotiation
   2019-03-31
   2019-03-31
   2019-03-31

as Loan Date Negotiation           datetime64[ns]

so i wanna make function to subtract 2 days from it. if last the day of the month is sunday, i will subtract 2 days from it.

From dataframe above, 2019-03-31 Is sunday,

i've tried but it's fail, this is

 def subtractingDate(dateTime):
     dateTimestamp = pd.Timestamp(dateTime)
     newDate = dateTimestamp - pd.Timedelta("2 days")
     return newDate

 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])

*note: 6 is for sunday

So the error is

TypeError                                 Traceback (most recent call last)
<ipython-input-9-cc2a3348e6ce> in <module>
     16 # a = subtractingDate(dfMARET["Loan Date Negotiation"])
     17 # a
---> 18 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])
     19 dfMARET
     20

<ipython-input-9-cc2a3348e6ce> in subtractingDate(dateTime)
     10
     11 def subtractingDate(dateTime):
---> 12     dateTimestamp = pd.Timestamp(dateTime)
     13     newDate = dateTimestamp - pd.Timedelta(days = 2)
     14     return newDate

pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps.Timestamp.__new__()

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.convert_to_tsobject()```

so my expectation would be

 Loan Date Negotiation
 2019-03-29
 2019-03-29
 2019-03-29

Ther's solution in pandas?

thank's

Body:
If you need to convert datetime64 to Timestamp first, you can use:

df['Date'] = [pd.Timestamp(x) for x in df['Date']]

and use timedelta():

from datetime import datetime, timedelta
dt = pd.Timestamp(2019,3,31)
new_dt = dt-timedelta(days=2)

new_dt
> datetime.datetime(2019, 3, 29, 0, 0)

new_dt.strftime('%Y-%m-%d')
> '2019-03-29'

Or on whole column Date with:

df['New_Date'] = df['Date']-timedelta(days=2)

EDIT: Full example:

import numpy as np
from datetime import datetime, timedelta

df1 = pd.DataFrame([[np.datetime64(datetime(2019, 3, 31))],
                    [np.datetime64(datetime(2019, 3, 27))],
                    [np.datetime64(datetime(2019, 3, 24))]],
                   columns=['Loan Date Negotiation'])
df1

df1['Loan Date Negotiation'].dtype
> dtype('<M8[ns]')

M8[ns] is a specific type of datetime64[ns], so there should be no difference in further processing.

If you want to subtract two days only if the day is a sunday, you can use np.where():

df1['New_Date'] = np.where(df1['Loan Date Negotiation'].dt.dayofweek==6,
         df1['Loan Date Negotiation']-timedelta(days=2),
         df1['Loan Date Negotiation'])

Dates at index 0 and 2 were sundays and got 2 days subtracted. Date at index 1 was not touched.

Alternative via list comprehension over every single Timestamp

df1['New_Date'] = [x-timedelta(days=2) if x.weekday()==6 else x for x in df1['Loan Date Negotiation']]


来源: stackexchange

问:
wsdl2java with Basic Authentication (Axis 1.6.1)
I am using wsdl2java to generate my java stub code for a web service.

I know it has been a bug  since 1.4 that a wsdl source that requires HTTP basic auth could not be accessed. You will receive a 401 error because authorization was denied and there is no way to specify credentials.

Does anyone know if this issue was resolved or has someone a workaround for this? I could setup a proxyy server probably, but this is too much hassle for me, I am seeking something simple :)

答:
You can pass username and password in URL like this: http://username:password@example.com/wsdl
It works for me in axis: 1.7.9</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Drawing full screen chessboard pattern?
I'm working in OpenCV (camera calibration and then creating 3d model) and till now I always printed a checkerboard pattern on paper and then took pictures needed for calibration. I tried to find a way to draw the pattern on the full screen with pre-defined square sizes (so I could set that square size in the calibration process), but I only found the Python turtle module which seems to only be for drawing on part of screen, and it always draws an arrow on last square. I need to draw the pattern with some small offset from the screen borders and, inside those offsets, draw a checkerboard with uniform squares. Also, I saw some people are drawing patterns in GIMP, but not on the full screen.

OpenCV has the function drawChessboardCorners but it requires founded corners from previous imported images, which need to be calibrated, so I think it doesn't make sense.

If anybody has an idea how to solve this problem, either with some program or module in some programming language (Python if possible), I would be grateful.

答:
Here is a simple code for generating the chessboard pattern. However, the diameter of the chessboard is in pixel unit.</p>

```<code>import numpy as np

h = 6
w = 8
size = 100
checkerboard = 255.0 * np.kron([[1, 0] * (w//2), [0, 1] * (w//2)] * (h//2), np.ones((size, size)))
</code>```

Title: Drawing full screen chessboard pattern?

Body:
Here is a simple code for generating the chessboard pattern. However, the diameter of the chessboard is in pixel unit.

import numpy as np

h = 6
w = 8
size = 100
checkerboard = 255.0 * np.kron([[1, 0] * (w//2), [0, 1] * (w//2)] * (h//2), np.ones((size, size)))


问:
Multi touch with appcelerator titanium
I'm currently building a iPhone App which require the multitouch (here to resize an ImageView) but I didn't find any documentation / tutorials about such a feature.

Is it possible to do so?

then how?

EDIT
Here is a link I found, but i don't know how to use it (I mean, when I try to build this like it's said in the readme, I have errors about Timodule/h, TiUIView.h etc).
https://github.com/masuidrive/TiMultitouch

Thanks,

KiTe.

答: well, no way to do a well handled multitouch on iPhone with Titanium simply for now. Let's wait the 1.7 version. Or switch technology ^^</p>

Title: Multi touch with appcelerator titanium


问:
How to position image in the center/middle both vertically and horizontally
```<code><div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<img src="bla.jpg">
</div>
</code>```

How can i make the image start from the middle of this box? (middle both vertical and horizontal)

答:
A suitable solution for modern browsers is flexbox. A flex container can be configured to align its items both horizontally and vertically.</p>

```<code><div style="display: flex; align-items: center; justify-content: center; width: 600px; height: 600px;">
    <img src="bla.jpg">
</div>
</code>```

Body:
A suitable solution for modern browsers is flexbox. A flex container can be configured to align its items both horizontally and vertically.

<div style="display: flex; align-items: center; justify-content: center; width: 600px; height: 600px;">
    <img src="bla.jpg">
</div>


问:
python mails being sent out have a blank TO field
I have a python script that sends out emails.  The emails are being sent out with no issues.

However, when I get the mails and open them up, their "to:" field do not show the recipients.  It's just blank.  I want to show all the recipients.  And since I'm not using any "bcc" configuration in my script, I'm befuddled as to how this could be.

Here's the code I'm using:

```<code>#!/usr/bin/env python

you = [ "MyEmail1@MyEmail.com", "MyEmail2@MyEmail.com" ]
for eachrecord in fformatErrMessage:
    # Preparing all variables #
    msg = MIMEMultipart()
    msg['Subject'] = subjectMsg
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()
</code>```

I have tried replacing the you with:

```<code>you = "MyEmail1@MyEmail.com"
</code>```

thinking maybe the list is the problem - but that did not work.

答:
When sending emails, servers do not look at the To:-Field. Instead, email servers have a separate way of transmitting recipient addresses, sometimes called the "envelope", which they use to route and deliver mail. The client never receives that envelope, it instead uses the To:-field in the message headers.

The sendmail() call simply sets the addresses of the SMTP envelope. If you want the To:-field to show up in the mail itself, you must set the appropriate header:

msg['To'] = "foo@bar.com"

This is, btw, how BCC works: The addresses on the envelope is simply not repeated in the message headers.

Body:
I have a python script that sends out emails.  The emails are being sent out with no issues.

However, when I get the mails and open them up, their "to:" field do not show the recipients.  It's just blank.  I want to show all the recipients.  And since I'm not using any "bcc" configuration in my script, I'm befuddled as to how this could be.

Here's the code I'm using:

#!/usr/bin/env python

you = [ "MyEmail1@MyEmail.com", "MyEmail2@MyEmail.com" ]
for eachrecord in fformatErrMessage:
    # Preparing all variables #
    msg = MIMEMultipart()
    msg['Subject'] = subjectMsg
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()

I have tried replacing the you with:

you = "MyEmail1@MyEmail.com"

thinking maybe the list is the problem - but that did not work.


问:
Using zoomCallback, how can I "snap" the zoom to existing x values?
I'm trying to use the zoomCallback function to set up interaction between my dygrpahs chart and a map chart. My x values are timestamps in seconds but since the sample rate is about 100Hz the timestamps are stored as float numbers.

The goal is that when dygraphs chart is zoomed in, the new x1 and x2 will be used to extract a piece of GPS track (lat, lng points). The extracted track will be used to re-fit the map boundaries - this will look like a "zoom in" on the map chart.

In my dygraphs options I specified the callback:

```<code>zoomCallback: function(x1,x2) {
  let x1Index = graphHolder.getRowForX(x1);
  let x2Index = graphHolder.getRowForX(x2);
  // further code
}
</code>```

But it looks like the zoom is not "snapped" to existing timestamp points so both x1Index and x2Index are null. Only when I zoom out, they'll correctly point to row 0 and the last row of data.

So the question is - is there a way to make the zoom snap only to the nearest existing x value so the row number can be returned? Or, is there an alternative to do what I want?

Thanks for any insights!

答:
You can access the x-axis values via g.getValue(row, 0). From this you can either do a linear scan to find the first row in the range or (fancier but faster) use a binary search.

Here's a way to do the linear scan:

const [x1, x2] = g.xAxisRange();
let letRow = null, highRow = null;
for (let i = 0; i < g.numRows(); i++) {
    if (g.getValue(i, 0) >= x1) {
        lowRow = i;
        break;
    }
}
for (let i = g.numRows() - 1; i >= 0; i--) {
    if (g.getValue(i, 0) <= x2) {
        highRow = i;
        break;
    }
}
const dataX1 = g.getValue(lowRow, 0);
const dataX2 = g.getValue(highRow, 0);
```

<p>For larger data sets you might want to do a binary search using something like lodash's <code>_.sortedIndex</code>.</p>

<p><strong>Update</strong> Here's a binary search implementation. No promises about the exact behavior on the boundaries (i.e. whether it always returns indices that are inside the visible range or indices which contain the visible range).</p>

<pre class="lang-js prettyprint-override"><code>function dygraphBinarySearch(g, x) {
    let low = 0;
    let high = g.numRows() - 1;
    while (high > low) {
        let i = Math.floor(low + (high - low) / 2);
        const xi = g.getValue(i, 0);
        if (xi < x) {
            low = i + 1;
        } else if (xi > x) {
            high = i - 1;
        } else {
            return i;
        }
    }
    return low;
}
function getVisibleDataRange(g) {
    const [x1, x2] = g.xAxisRange();
    let lowI = dygraphBinarySearch(g, x1);
    let highI = dygraphBinarySearch(g, x2);
    return [lowI, highI];
}
</code>```

Body:
I'm trying to use the zoomCallback function to set up interaction between my dygrpahs chart and a map chart. My x values are timestamps in seconds but since the sample rate is about 100Hz the timestamps are stored as float numbers.

The goal is that when dygraphs chart is zoomed in, the new x1 and x2 will be used to extract a piece of GPS track (lat, lng points). The extracted track will be used to re-fit the map boundaries - this will look like a "zoom in" on the map chart.

In my dygraphs options I specified the callback:

zoomCallback: function(x1,x2) {
  let x1Index = graphHolder.getRowForX(x1);
  let x2Index = graphHolder.getRowForX(x2);
  // further code
}

But it looks like the zoom is not "snapped" to existing timestamp points so both x1Index and x2Index are null. Only when I zoom out, they'll correctly point to row 0 and the last row of data.

So the question is - is there a way to make the zoom snap only to the nearest existing x value so the row number can be returned? Or, is there an alternative to do what I want?

Thanks for any insights!

Body:
You can access the x-axis values via g.getValue(row, 0). From this you can either do a linear scan to find the first row in the range or (fancier but faster) use a binary search.

Here's a way to do the linear scan:

const [x1, x2] = g.xAxisRange();
let letRow = null, highRow = null;
for (let i = 0; i < g.numRows(); i++) {
    if (g.getValue(i, 0) >= x1) {
        lowRow = i;
        break;
    }
}
for (let i = g.numRows() - 1; i >= 0; i--) {
    if (g.getValue(i, 0) <= x2) {
        highRow = i;
        break;
    }
}
const dataX1 = g.getValue(lowRow, 0);
const dataX2 = g.getValue(highRow, 0);

For larger data sets you might want to do a binary search using something like lodash's _.sortedIndex.

Update Here's a binary search implementation. No promises about the exact behavior on the boundaries (i.e. whether it always returns indices that are inside the visible range or indices which contain the visible range).

function dygraphBinarySearch(g, x) {
    let low = 0;
    let high = g.numRows() - 1;
    while (high > low) {
        let i = Math.floor(low + (high - low) / 2);
        const xi = g.getValue(i, 0);
        if (xi < x) {
            low = i + 1;
        } else if (xi > x) {
            high = i - 1;
        } else {
            return i;
        }
    }
    return low;
}
function getVisibleDataRange(g) {
    const [x1, x2] = g.xAxisRange();
    let lowI = dygraphBinarySearch(g, x1);
    let highI = dygraphBinarySearch(g, x2);
    return [lowI, highI];
}


问:
Create a date column from existing date column as one day minus the existing date column
I have a date column, called Eff_Date and a column name cmg as below,

```<code>Eff_Date       cmg
-------------------
15-12-2017     F1
18-12-2018     F1
1-2-2019       F2
</code>```

and I want to create a new Date Column which is one day previous to the date in the next row in  eff_date Column as below for a particular cmg.

```<code>Eff_Date        NewDateColumn
-------------------------------
15-12-2017      17-12-2018
18-12-2018      18-12-2018
1-2-2019        1-2-2019
</code>```

the NewDateColumn will have (17-12-2018 , as next row in Eff_date has 18-12-2018) for cmg = F1

The last row will be same as eff_date for a particular cmg
Please help

答:
I added a few rows in your table to test for handling of ties:

```<code>Eff_Date    cmg
12/15/2017  F1
12/18/2018  F1
1/15/2019   F1
1/20/2019   F1
1/22/2019   F1
6/7/2017    F2
8/9/2018    F2
10/10/2018  F2
1/2/2019    F2
1/2/2019    F2
</code>```

While there are many ways to calculate this, I think the most important is that you need to rank the dates in order to identify the next one.

I did this by defining a few variables:

```<code>=
VAR thisDateRank =
    RANKX (
        FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
        Table1[Eff_Date],
        ,
        ASC
    )
VAR maxDateRank =
    MAXX (
        FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
        Table1[Eff_Date]
    )
VAR nextDate =
    CALCULATE (
        MAX ( Table1[Eff_Date] ),
        FILTER (
            ALL ( Table1 ),
            Table1[cmg] = EARLIER ( Table1[cmg] )
                && RANKX (
                    FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
                    Table1[Eff_Date],
                    ,
                    ASC
                ) = thisDateRank + 1
        )
    )
RETURN
    IF ( Table1[Eff_Date] = maxDateRank, maxDateRank, nextDate - 1 )
</code>```

The result looks like this

```<code>Eff_Date    cmg NewDateColumn
12/15/2017  F1  12/17/2018
12/18/2018  F1  1/14/2019
1/15/2019   F1  1/19/2019
1/20/2019   F1  1/21/2019
1/22/2019   F1  1/22/2019
6/7/2017    F2  8/8/2018
8/9/2018    F2  10/9/2018
10/10/2018  F2  1/1/2019
1/2/2019    F2  1/2/2019
1/2/2019    F2  1/2/2019
</code>```

Body:
I have a date column, called Eff_Date and a column name cmg as below,

Eff_Date       cmg
-------------------
15-12-2017     F1
18-12-2018     F1
1-2-2019       F2

and I want to create a new Date Column which is one day previous to the date in the next row in  eff_date Column as below for a particular cmg.

Eff_Date        NewDateColumn
-------------------------------
15-12-2017      17-12-2018
18-12-2018      18-12-2018
1-2-2019        1-2-2019

the NewDateColumn will have (17-12-2018 , as next row in Eff_date has 18-12-2018) for cmg = F1

The last row will be same as eff_date for a particular cmg
Please help

Body:
I added a few rows in your table to test for handling of ties:

Eff_Date    cmg
12/15/2017  F1
12/18/2018  F1
1/15/2019   F1
1/20/2019   F1
1/22/2019   F1
6/7/2017    F2
8/9/2018    F2
10/10/2018  F2
1/2/2019    F2
1/2/2019    F2

While there are many ways to calculate this, I think the most important is that you need to rank the dates in order to identify the next one.

I did this by defining a few variables:

=
VAR thisDateRank =
    RANKX (
        FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
        Table1[Eff_Date],
        ,
        ASC
    )
VAR maxDateRank =
    MAXX (
        FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
        Table1[Eff_Date]
    )
VAR nextDate =
    CALCULATE (
        MAX ( Table1[Eff_Date] ),
        FILTER (
            ALL ( Table1 ),
            Table1[cmg] = EARLIER ( Table1[cmg] )
                && RANKX (
                    FILTER ( Table1, Table1[cmg] = EARLIER ( Table1[cmg] ) ),
                    Table1[Eff_Date],
                    ,
                    ASC
                ) = thisDateRank + 1
        )
    )
RETURN
    IF ( Table1[Eff_Date] = maxDateRank, maxDateRank, nextDate - 1 )

The result looks like this

Eff_Date    cmg NewDateColumn
12/15/2017  F1  12/17/2018
12/18/2018  F1  1/14/2019
1/15/2019   F1  1/19/2019
1/20/2019   F1  1/21/2019
1/22/2019   F1  1/22/2019
6/7/2017    F2  8/8/2018
8/9/2018    F2  10/9/2018
10/10/2018  F2  1/1/2019
1/2/2019    F2  1/2/2019
1/2/2019    F2  1/2/2019


问:
How do I mark (or) shade the area below the graph of Surface plot in Matlab?
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

```<code>[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');
</code>```

答:
You can add the extra surfaces by building up a new set of matrices to pass to surf, with a few different options based on how you want the results to look...

Option #1: Fill the sides, one surface object:

If you want to just fill in the sides, you can add a new row and column on each side of your matrices like so:

```<code>[R, C] = size(Z);
Xfill = [nan X(1, :) nan; X(:, [1 1:C C]); nan X(R, :) nan];
Yfill = [nan Y(1, :) nan; Y(:, [1 1:C C]); nan Y(R, :) nan];
Zfill = [nan zeros(1, C) nan; zeros(R, 1) Z zeros(R, 1); nan zeros(1, C) nan];

surf(Xfill, Yfill, Zfill);
view(-120, 30);
</code>```

This allows you to plot the surface and sides with a single call to surf, with this result:

Option #2: Fill the sides and bottom, one surface object:

If you would also like to fill in the bottom of the shape, you can wrap the surface around and under itself by adding new columns and then add a new row at the top and bottom to close the ends:

```<code>[R, C] = size(Z);
Xfill = [X(1, 1:C) nan(1, C+1); ...  % Close top
         X flip(X, 2) X(:, 1); ...   % Flip data and connect to other side
         X(R, 1:C) nan(1, C+1)];     % Close bottom
Yfill = [Y(1, 1:C) nan(1, C+1); ...
         Y flip(Y, 2) Y(:, 1); ...
         Y(R, 1:C) nan(1, C+1)];
Zfill = [zeros(1, C) nan(1, C+1); ...
         Z zeros(R, C) Z(:, 1); ...
         zeros(1, C) nan(1, C+1)];

surf(Xfill, Yfill, Zfill);
view(-120, -20);
</code>```

Again, you can plot the entire closed surface with a single call to surf. Here's the view from the underside, showing the closed bottom:

Option #3: Add a separate surface object for the sides:

When plotting everything as one object, you're limited if you want to render the sides differently than the top. Making the sides separate objects like Ander does (using patch or a separate call to surf) will give you more control over how they are colored relative to the top surface. To make a single surface object for all four of your sides, you can extract the entries around the edges of your matrices and replicate them as needed:

```<code>[R, C] = size(Z);
Xside = [1; 1]*[X(1, :) ...           % Get first row
                X(2:R, C).' ...       % Get last column, without first row
                X(R, (C-1):-1:1) ...  % Get last row, without last column, flipped
                X((R-1):-1:1, 1).'];  % Get first column, without last row, flipped
Yside = [1; 1]*[Y(1, :) ...
                Y(2:R, C).' ....
                Y(R, (C-1):-1:1) ...
                Y((R-1):-1:1, 1).'];
Zside = [Z(1, :) ...
         Z(2:R, C).' ...
         Z(R, (C-1):-1:1) ...
         Z((R-1):-1:1, 1).'; ...
         zeros(1, 2*(R+C)-3)];

surf(X, Y, Z);  % Plot top surface
hold on;
surf(Xside, Yside, Zside, ...  % Plot all four sides...
     'EdgeColor', 'none', ...  %   with no edge coloring (i.e. grid)...
     'FaceAlpha', 0.5);        %   and transparency
view(-120, 30);
</code>```

And the resulting plot:

Body:
I am trying to plot a 3D surface graph for the following equation
 t_t <= (xi_i - xi_j) . sqrt(rho). I have included my code. But I would like to mark or shade the area under the graph of this surface plot. How do I solve it?

[X,Y] = meshgrid(1:0.5:10,1:20);

Z = X.* sqrt(Y);

figure;

colormap(jet)

surf(X,Y,Z)

colorbar

xlabel('Distance between two spatial points \xi_i & \xi_j (\xi_i - \xi_j)');

ylabel('Density(\rho)');

zlabel('Transmission Delay (t_t)');

Body:
You can add the extra surfaces by building up a new set of matrices to pass to surf, with a few different options based on how you want the results to look...

Option #1: Fill the sides, one surface object:

If you want to just fill in the sides, you can add a new row and column on each side of your matrices like so:

[R, C] = size(Z);
Xfill = [nan X(1, :) nan; X(:, [1 1:C C]); nan X(R, :) nan];
Yfill = [nan Y(1, :) nan; Y(:, [1 1:C C]); nan Y(R, :) nan];
Zfill = [nan zeros(1, C) nan; zeros(R, 1) Z zeros(R, 1); nan zeros(1, C) nan];

surf(Xfill, Yfill, Zfill);
view(-120, 30);

This allows you to plot the surface and sides with a single call to surf, with this result:

Option #2: Fill the sides and bottom, one surface object:

If you would also like to fill in the bottom of the shape, you can wrap the surface around and under itself by adding new columns and then add a new row at the top and bottom to close the ends:

[R, C] = size(Z);
Xfill = [X(1, 1:C) nan(1, C+1); ...  % Close top
         X flip(X, 2) X(:, 1); ...   % Flip data and connect to other side
         X(R, 1:C) nan(1, C+1)];     % Close bottom
Yfill = [Y(1, 1:C) nan(1, C+1); ...
         Y flip(Y, 2) Y(:, 1); ...
         Y(R, 1:C) nan(1, C+1)];
Zfill = [zeros(1, C) nan(1, C+1); ...
         Z zeros(R, C) Z(:, 1); ...
         zeros(1, C) nan(1, C+1)];

surf(Xfill, Yfill, Zfill);
view(-120, -20);

Again, you can plot the entire closed surface with a single call to surf. Here's the view from the underside, showing the closed bottom:

Option #3: Add a separate surface object for the sides:

When plotting everything as one object, you're limited if you want to render the sides differently than the top. Making the sides separate objects like Ander does (using patch or a separate call to surf) will give you more control over how they are colored relative to the top surface. To make a single surface object for all four of your sides, you can extract the entries around the edges of your matrices and replicate them as needed:

[R, C] = size(Z);
Xside = [1; 1]*[X(1, :) ...           % Get first row
                X(2:R, C).' ...       % Get last column, without first row
                X(R, (C-1):-1:1) ...  % Get last row, without last column, flipped
                X((R-1):-1:1, 1).'];  % Get first column, without last row, flipped
Yside = [1; 1]*[Y(1, :) ...
                Y(2:R, C).' ....
                Y(R, (C-1):-1:1) ...
                Y((R-1):-1:1, 1).'];
Zside = [Z(1, :) ...
         Z(2:R, C).' ...
         Z(R, (C-1):-1:1) ...
         Z((R-1):-1:1, 1).'; ...
         zeros(1, 2*(R+C)-3)];

surf(X, Y, Z);  % Plot top surface
hold on;
surf(Xside, Yside, Zside, ...  % Plot all four sides...
     'EdgeColor', 'none', ...  %   with no edge coloring (i.e. grid)...
     'FaceAlpha', 0.5);        %   and transparency
view(-120, 30);

And the resulting plot:


问:
Loop through each sheets to look for name containing value, do something, loop again looking for new value
I am trying to loop through sheets in a workbook, select those with names alike, save them to a PDF, then loop again but change the name it looks for in the sheets.  The sheets will have in common a number that is 4 digits like 0001 or 0243 and the four digits are important so sheets 0030 and 0003 do not get combined.

I have gotten the code to work on just one name to find (below) but cannot figure out how to make it loop through more names.  Tried making the name an integer and add 1 to it after each loop, tried very briefly to make it loop through array values but that did not work how I tried.

```<code>For Each sh In ActiveWorkbook.Worksheets

    If sh.Name Like "*0001*" Then

        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''

    End If

Next sh
</code>```

If it could loop through each digit from 0001 to 0300 that would be ideal so I do not need to edit code each time I run it to add the new sheet names.  However if an array will work best I can make a long array for the numbers I know will be present in the file and add new ones each month as needed.

答:
I would use a code similar to the below:</p>

```<code>Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count

For i = 1 to i = K
    t = Sheets(i).Name

    Sheets(i).activate

    ' Do your activities within this loop
Next i

</code>```

Body:
I am trying to loop through sheets in a workbook, select those with names alike, save them to a PDF, then loop again but change the name it looks for in the sheets.  The sheets will have in common a number that is 4 digits like 0001 or 0243 and the four digits are important so sheets 0030 and 0003 do not get combined.

I have gotten the code to work on just one name to find (below) but cannot figure out how to make it loop through more names.  Tried making the name an integer and add 1 to it after each loop, tried very briefly to make it loop through array values but that did not work how I tried.

For Each sh In ActiveWorkbook.Worksheets

    If sh.Name Like "*0001*" Then

        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''

    End If

Next sh

If it could loop through each digit from 0001 to 0300 that would be ideal so I do not need to edit code each time I run it to add the new sheet names.  However if an array will work best I can make a long array for the numbers I know will be present in the file and add new ones each month as needed.

Body:
I would use a code similar to the below:

Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count

For i = 1 to i = K
    t = Sheets(i).Name

    Sheets(i).activate

    ' Do your activities within this loop
Next i


问:
Ubuntu 9.04: Pecl extension downloads but does not install
I'm new to php, so apologies if I've overlooked something simple. I want to install the php extension pecl_http. I have followed the instructions here http://www.mkfoster.com/2009/01/04/how-to-install-a-php-pecl-extensionmodule-on-ubuntu/, specifically:

```<code>sudo apt-get install php-pear
sudo apt-get install php5-dev
sudo apt-get install libcurl3-openssl-dev
</code>```

which all works fine. However, the next step does not seem to complete:

```<code>sudo pecl install pecl_http
</code>```

All this does is download the .tgz, but doesn't actually install it. It puts the file here:

```<code>/build/buildd/php5-5.2.10.dfsg.1/pear-build-download/pecl_http-1.7.0.tgz
</code>```

I can unpack it myself, but have a feeling there may be more to installing it. Indeed, doing:

```<code>pecl list
</code>```

tells me no extensions installed. What am I not doing?

Thanks.

Edit: I've found these alternatives to installing a pecl extension: https://serverfault.com/questions/178986/pecl-install-uploadprogress-fails-silently However it breaks on build:

```<code>install: cannot stat `tmp/modules5/pecl-http.so': No such file or directory
</code>```

for the simple reason the lib is called http.so, not pecl-http.so...

答:
You should be able to debug the process by adding -v or -vvv to the pecl command.

Can you provide output?

ContentLicense: CC BY-SA 2.5

Body:
I'm new to php, so apologies if I've overlooked something simple. I want to install the php extension pecl_http. I have followed the instructions here http://www.mkfoster.com/2009/01/04/how-to-install-a-php-pecl-extensionmodule-on-ubuntu/, specifically:

sudo apt-get install php-pear
sudo apt-get install php5-dev
sudo apt-get install libcurl3-openssl-dev

which all works fine. However, the next step does not seem to complete:

sudo pecl install pecl_http

All this does is download the .tgz, but doesn't actually install it. It puts the file here:

/build/buildd/php5-5.2.10.dfsg.1/pear-build-download/pecl_http-1.7.0.tgz

I can unpack it myself, but have a feeling there may be more to installing it. Indeed, doing:

pecl list

tells me no extensions installed. What am I not doing?

Thanks.

Edit: I've found these alternatives to installing a pecl extension: https://serverfault.com/questions/178986/pecl-install-uploadprogress-fails-silently However it breaks on build:

install: cannot stat `tmp/modules5/pecl-http.so': No such file or directory

for the simple reason the lib is called http.so, not pecl-http.so...


问:
Calling functions on my SavingsAccount object and printing the result
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}
```

I would like to use my functions on the object I make and print the result.

Thanks for reading.

答:
You can call your functions in the constructor:

```<code>public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    deposit(deposit);
    withdraw(withdraw);
    checkBalance();
}
</code>```

Then you will see all the System.out messages without the need to change the main method.

Body:
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}

I would like to use my functions on the object I make and print the result.

Thanks for reading.

Body:
You can call your functions in the constructor:

public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    deposit(deposit);
    withdraw(withdraw);
    checkBalance();
}

Then you will see all the System.out messages without the need to change the main method.


问:
The ProjectLayout.directoryProperty() method has been deprecated
After update to gradle 5.2.1

Deprecated Gradle features were used in this build, making it
  incompatible with Gradle 6.0.

So I run ./gradlew :app:clean --warning-mode all

I have warnings in console:

The ProjectLayout.directoryProperty() method has been deprecated. This is scheduled to be removed in Gradle 6.0. Please use the ObjectFactory.directoryProperty() method instead.

The ProjectLayout.fileProperty() method has been deprecated. This is
  scheduled to be removed in Gradle 6.0. Please use the
  ObjectFactory.fileProperty() method instead.

Even if its a newly created empty Android project without libraries.
Also searching for ProjectLayout doesnt give any result.

P.S I already know that its warning, not error. But I just need to know whats wrong with gradle again.

答:
This is just an internal API that the Android Gradle Tool uses, and they will update when they support 6.0 (they support 5.1 now IIRC)

The issue is being tracked here (and is currently assigned to a Google Developer)
https://issuetracker.google.com/issues/127538936


问:
Is there a way to find text with spaces before and after string in excel?
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

```<code>=SEARCH(" "&"Nw"&" ",A2,1)
</code>```

and

```<code>=SEARCH(" Nw ",A2,1)
</code>```

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

答:
SEARCH will return the position of the substring within the string being searched and is case insensitive. This can be used with REPLACE to achieve what you want:

```<code>=REPLACE(A2,SEARCH(" NW ",A2 & " "),3," NW")
</code>```

Body:
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

=SEARCH(" "&"Nw"&" ",A2,1)

and

=SEARCH(" Nw ",A2,1)

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

Body:
SEARCH will return the position of the substring within the string being searched and is case insensitive. This can be used with REPLACE to achieve what you want:

=REPLACE(A2,SEARCH(" NW ",A2 & " "),3," NW")


问:
Starting position for replace function in db2
I'm converting some Access VBA functionality to DB2 and found a vital difference.  VBA lets you specify the starting point in the character string you're working on.  DB2 doesn't have that option.  It starts from position 1 and replaces whatever you want to be replaced in the whole string. How can I make DB2 start the replace at a specified place in the string? For example, my string is "Incongruent Plastics Incorporated" and I want to replace the second "Inc" at position 22 with "Inc". I'm doing this in a WHILE loop, going through long strings, replacing parts of them until they are less than a specified maximum (15 or 30 depending on the field).

I looked at the Locate function, but I'm not sure that's right.

Replace(a.PAYEE_STD_NAME, B.FullWord, B.abbreviation, B.mLastWord)
```

Where a.PAYEE_STD_NAME is the string I'm looking at, B.FullWord is what I want to replace, B.abbreviation is what I want to replace it with, and B.mLastWord is the position where I want to start replacing.  Something like Replace("Incongruent Plastics Incorporated","Incorporated","Inc",22)

I expect the characters to be replaced starting in the position I need, towards the back of the string, not in the beginning.

Thanks!

答:
Not that good at DB2, but that limitation can generally be worked around by using SUBSTR

The equivalent of Replace(a.PAYEE_STD_NAME, B.FullWord, B.abbreviation, B.mLastWord) would be:

```<code>CONCAT(SUBSTR(a.PAYEE_STD_NAME, 1, B.mLastWord - 1), Replace(SUBSTR(a.PAYEE_STD_NAME, b.mLastWord), B.FullWord, B.abbreviation))
</code>```

This assumes b.mLastWord is greater than 1, if it's 1 you can use a normal REPLACE.

Body:
I'm converting some Access VBA functionality to DB2 and found a vital difference.  VBA lets you specify the starting point in the character string you're working on.  DB2 doesn't have that option.  It starts from position 1 and replaces whatever you want to be replaced in the whole string. How can I make DB2 start the replace at a specified place in the string? For example, my string is "Incongruent Plastics Incorporated" and I want to replace the second "Inc" at position 22 with "Inc". I'm doing this in a WHILE loop, going through long strings, replacing parts of them until they are less than a specified maximum (15 or 30 depending on the field).

I looked at the Locate function, but I'm not sure that's right.

Replace(a.PAYEE_STD_NAME, B.FullWord, B.abbreviation, B.mLastWord)

Where a.PAYEE_STD_NAME is the string I'm looking at, B.FullWord is what I want to replace, B.abbreviation is what I want to replace it with, and B.mLastWord is the position where I want to start replacing.  Something like Replace("Incongruent Plastics Incorporated","Incorporated","Inc",22)

I expect the characters to be replaced starting in the position I need, towards the back of the string, not in the beginning.

Thanks!

Body:
Not that good at DB2, but that limitation can generally be worked around by using SUBSTR

The equivalent of Replace(a.PAYEE_STD_NAME, B.FullWord, B.abbreviation, B.mLastWord) would be:

CONCAT(SUBSTR(a.PAYEE_STD_NAME, 1, B.mLastWord - 1), Replace(SUBSTR(a.PAYEE_STD_NAME, b.mLastWord), B.FullWord, B.abbreviation))

This assumes b.mLastWord is greater than 1, if it's 1 you can use a normal REPLACE.


问:
How do I get the coordinates of a mouse click on a canvas element?
What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No legacy browser compatibility required, Safari, Opera and Firefox will do.

答:
I was creating an application having a canvas over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf,  I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.

I was using rxjs and angular 6, and didn't found any answer specific to the newest version.

Here is the entire code snippet that would be helpful, to anyone leveraging rxjs to draw on top of canvas.

```<code>  private captureEvents(canvasEl: HTMLCanvasElement) {

    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
      .pipe(
        switchMap((e: any) => {

          return fromEvent(canvasEl, 'mousemove')
            .pipe(
              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
                const prevPos = {
                  x: null,
                  y: null
                };
              })),

              takeUntil(fromEvent(canvasEl, 'mouseleave')),
              pairwise()
            )
        })
      )
      .subscribe((res: [MouseEvent, MouseEvent]) => {
        const rect = this.cx.canvas.getBoundingClientRect();
        const prevPos = {
          x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };
        const currentPos = {
          x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };

        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
        this.drawOnCanvas(prevPos, currentPos);
      });
  }
</code>```

And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.

```<code>const prevPos = {
  x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
const currentPos = {
  x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
</code>```

OwnerDisplayName: Tom

LastEditorDisplayName: Tom

Body:
I was creating an application having a canvas over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf,  I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.

I was using rxjs and angular 6, and didn't found any answer specific to the newest version.

Here is the entire code snippet that would be helpful, to anyone leveraging rxjs to draw on top of canvas.

  private captureEvents(canvasEl: HTMLCanvasElement) {

    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
      .pipe(
        switchMap((e: any) => {

          return fromEvent(canvasEl, 'mousemove')
            .pipe(
              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
                const prevPos = {
                  x: null,
                  y: null
                };
              })),

              takeUntil(fromEvent(canvasEl, 'mouseleave')),
              pairwise()
            )
        })
      )
      .subscribe((res: [MouseEvent, MouseEvent]) => {
        const rect = this.cx.canvas.getBoundingClientRect();
        const prevPos = {
          x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };
        const currentPos = {
          x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };

        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
        this.drawOnCanvas(prevPos, currentPos);
      });
  }

And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.

const prevPos = {
  x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
const currentPos = {
  x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};


问:
CSS for rows of logos
I'm trying to code a row of logos in the footer of website https://www.andromedi.com/

The desktop version works fine but the mobile needs to looks like this

I checked online and the way to go apparently is using flexbox (I still need to better understand the difference between css-grid and flexbox)

The css code:

.footer-asociaciones-wrapper {
  width: 100%;
  margin: auto;
  padding: 1.5rem 5rem;
}

.footer-asociaciones-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

.footer-asociaciones-column {
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex: 1;
}

.footer-asociaciones-column img {
    height:100px;
}

.footer-asociaciones-column a {
    margin: auto;
}

p.footer-asociaciones-title {
  padding: 1.5rem 1rem;
  color: white;
  font-family: 'DIN1451EngschriftRegular';
  font-size: large;
}
```

I tried using width: 33%; but then the logos overlap

Any help is appreciated. Thanks!

答:
You need to give your images max-width and max-height dimensions so they change according to the size of their containers. Auto values for height and width are there to maintain aspect ratio of the images.

```<code>.footer-asociaciones-column img {
  max-width: 100%;
  max-height: 100px;
  height: auto;
  width: auto;
}
</code>```

Title: CSS for rows of logos

Body:
I'm trying to code a row of logos in the footer of website https://www.andromedi.com/

The desktop version works fine but the mobile needs to looks like this

I checked online and the way to go apparently is using flexbox (I still need to better understand the difference between css-grid and flexbox)

The css code:

.footer-asociaciones-wrapper {
  width: 100%;
  margin: auto;
  padding: 1.5rem 5rem;
}

.footer-asociaciones-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

.footer-asociaciones-column {
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex: 1;
}

.footer-asociaciones-column img {
    height:100px;
}

.footer-asociaciones-column a {
    margin: auto;
}

p.footer-asociaciones-title {
  padding: 1.5rem 1rem;
  color: white;
  font-family: 'DIN1451EngschriftRegular';
  font-size: large;
}

I tried using width: 33%; but then the logos overlap

Any help is appreciated. Thanks!

Body:
You need to give your images max-width and max-height dimensions so they change according to the size of their containers. Auto values for height and width are there to maintain aspect ratio of the images.

.footer-asociaciones-column img {
  max-width: 100%;
  max-height: 100px;
  height: auto;
  width: auto;
}


问:
React Native get correct status bar height on android
I'm trying to get the status bar height on Android devices using React Native's StatusBar.currentHeight https://facebook.github.io/react-native/docs/statusbar. On a pixel 2, that variable is 24 when in fact the status bar height is 19. Does anyone know of a way to get the correct status bar height on all devices with React Native?</p>

答:
You can try download the expo-constants module.

import Constants from 'expo-constants';
...
const STATUSBAR_HEIGHT = Constants.statusBarHeight
```
<blockquote>
<p>EDIT</p>
</blockquote>
<p>OR</p>
<p>you can use <code>react-native-safe-area-context</code></p>
<ul>
<li>sample</li>
</ul>
```import { useSafeAreaInsets } from 'react-native-safe-area-context';

function HookComponent() {
  const insets = useSafeAreaInsets();

  useEffect(() => {
     const { top , bottom , left , right } = insets // typeof { top: number, right: number, bottom: number, left: number }
     console.log(top , bottom , left , right)
  },[insets])

  return <View style={{ paddingBottom: Math.max(insets.bottom, 16) }} />;
}
```

Body:
You can try download the expo-constants module.

import Constants from 'expo-constants';
...
const STATUSBAR_HEIGHT = Constants.statusBarHeight

EDIT

OR

you can use react-native-safe-area-context

sample

import { useSafeAreaInsets } from 'react-native-safe-area-context';

function HookComponent() {
  const insets = useSafeAreaInsets();

  useEffect(() => {
     const { top , bottom , left , right } = insets // typeof { top: number, right: number, bottom: number, left: number }
     console.log(top , bottom , left , right)
  },[insets])

  return <View style={{ paddingBottom: Math.max(insets.bottom, 16) }} />;
}


问:
Monotouch and XCode 4, where did the outlets go?
Today I updated my mac with the latest version of MonoDevelop, MonoTouch and the Mono-Framework. I also downloaded the latest version of XCode, version 4 (a nifty 4.5 gig download).

At first I did not notice it because I was busy copying code into my project for re-use. But when the time came to actually add some controls, actions and outlets to the MainWindow file - I realized that something was missing.

Hopefully I have over-looked something, because I cannot find functions for adding outlets and actions any more? After googling the problem I realized that the new XCode now does these things by code -- but not in C#, it's exclusively an Objective C thing.

How exactly do I solve this problem? I am currently downloading XCode 3.2.6 but surely there has to be a better option? (I dont even know if this will install over the 4.x version) How exactly do I define actions and outlets by code? Are there any tutorials on this to curve the extra time it will take?

Any help is welcome

Update: A tip for those who need to remove XCode and start from scratch. Open a terminal window and type:

```<code>"sudo /Developer/Library/uninstall-devtools --mode=all"
</code>```

This will remove your current XCode installation (all of it). Remember to re-boot your Mac afterwards. You can then install an older version of XCode.

答:
From Miguel's MT 4.0 Announcement

We are currently hard at work to add
  support to MonoDevelop to work with
  the new XCode 4.

With XCode 4, Apple removed Interface
  Builder as a standalone tool. We
  should have a beta in a couple of
  weeks of the solution we came up with.

Body:
Today I updated my mac with the latest version of MonoDevelop, MonoTouch and the Mono-Framework. I also downloaded the latest version of XCode, version 4 (a nifty 4.5 gig download).

At first I did not notice it because I was busy copying code into my project for re-use. But when the time came to actually add some controls, actions and outlets to the MainWindow file - I realized that something was missing.

Hopefully I have over-looked something, because I cannot find functions for adding outlets and actions any more? After googling the problem I realized that the new XCode now does these things by code -- but not in C#, it's exclusively an Objective C thing.

How exactly do I solve this problem? I am currently downloading XCode 3.2.6 but surely there has to be a better option? (I dont even know if this will install over the 4.x version) How exactly do I define actions and outlets by code? Are there any tutorials on this to curve the extra time it will take?

Any help is welcome

Update: A tip for those who need to remove XCode and start from scratch. Open a terminal window and type:

"sudo /Developer/Library/uninstall-devtools --mode=all"

This will remove your current XCode installation (all of it). Remember to re-boot your Mac afterwards. You can then install an older version of XCode.


问:
GroupBy with linq entity poco
I have this entities

```<code>public class Counter
    {
        public int DocEntry { get; set; }
        public int LineId { get; set; }
        public string Item { get; set; }
        public decimal Quantity { get; set; }
        public string FromWarehouse { get; set; }
        public string ToWarehouse { get; set; }
        public virtual List<Batch> batchs { get; set; }
    }

    public class Batch
    {
      public string BatchNumber { get; set; }

        public decimal Quantity { get; set; }
    }
</code>```

And I have List count,I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse, and the result should be grouped with summed quantity and the list of Batch merged, I tried cycling the Counter list using the foreach method and inserting in a new list the first element, in the subsequent iterations if the current row reflected the values of the one already in the list I summarized the quantities and added to the Batch list the elements of the Batch list of the i-th line, otherwise I added a new line, this approach I it seemed too complicated, not being very expert on linq or in any case is there an easier way to manage the group by?

This is my method:

```<code>public static List<Counter> GroupBy(List<Counter> list)
        {
            List<Counter> rows = new List<Counter>();
            int i = 0;
            foreach (Counter elem in list)
            {
                if (list.First() == elem)
                {
                    rows.Add(elem);
                    i++;
                }
                else
                {

                    if (elem.Item == rows.ElementAt(i).Item &&
                        elem.FromWarehouse == rows.ElementAt(i).FromWarehouse &&
                        elem.ToWarehouse == rows.ElementAt(i).ToWarehouse)
                    {
                        rows.First().Quantity += elem.Quantity;
                        rows.First().batchs.Add(elem.batchs.First());
                    }
                    else
                    {
                        rows.Add(elem);
                        i++;
                    }
                }
            }

            return rows;
        }
</code>```

This is the solution:

```<code>public static List<Counter> GroupBy(List<Counter> list)
        {
            List<Counter> rows = new List<Counter>();

            foreach (Counter elem in list)
            {
                if (rows.Any(x=>x.Item == elem.Item &&
                        x.FromWarehouse == elem.FromWarehouse &&
                        x.ToWarehouse == elem.ToWarehouse))
                {
                    rows.First().Quantity += elem.Quantity;
                    rows.First().batchs.Add(elem.batchs.First());
                }
                else
                {
                    rows.Add(elem);
                }
            }

            return rows;
        }
</code>```

答:
Let's try to write the Linq, step by step.

"I have List count":

```<code>   List<Counter> count = ...
</code>```

"I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse":

```<code>   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })
</code>```

"result should be grouped with summed quantity and the list of Batch merged", i.e. you should Aggregate items within each chunk

```<code>   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })
     .Select(chunk => new {
        key = chunk.Key,
        summary = chunk.Aggregate(
          Tuple.Create(0m, new List<Batch>()),                      // initial empty
          (s, a) => Tuple.Create(s.Item1 + a.Quantity,              // add
                                 s.Item2.Concat(a.batchs).ToList()) // merge
      })
</code>```

Finally, let's represent the result in more convenient (readable) format:

```<code>   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })
     .Select(chunk => new {
        key = chunk.Key,
        summary = chunk.Aggregate(
          Tuple.Create(0m, new List<Batch>()),
          (s, a) => Tuple.Create(s.Item1 + a.Quantity,
                                 s.Item2.Concat(a.batchs).ToList())
      })
     .Select(item => new {
        Item = item.key.Item,
        FromWarehouse = item.key.FromWarehouse,
        ToWarehouse = item.key.ToWarehouse,
        Quantity = item.summary.Item1,
        Batches = item.summary.Item2
      }); // Add ToArray() if you want to materialize
</code>```

Title: GroupBy with linq entity poco

Body:
I have this entities

public class Counter
    {
        public int DocEntry { get; set; }
        public int LineId { get; set; }
        public string Item { get; set; }
        public decimal Quantity { get; set; }
        public string FromWarehouse { get; set; }
        public string ToWarehouse { get; set; }
        public virtual List<Batch> batchs { get; set; }
    }

    public class Batch
    {
      public string BatchNumber { get; set; }

        public decimal Quantity { get; set; }
    }

And I have List count,I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse, and the result should be grouped with summed quantity and the list of Batch merged, I tried cycling the Counter list using the foreach method and inserting in a new list the first element, in the subsequent iterations if the current row reflected the values of the one already in the list I summarized the quantities and added to the Batch list the elements of the Batch list of the i-th line, otherwise I added a new line, this approach I it seemed too complicated, not being very expert on linq or in any case is there an easier way to manage the group by?

This is my method:

public static List<Counter> GroupBy(List<Counter> list)
        {
            List<Counter> rows = new List<Counter>();
            int i = 0;
            foreach (Counter elem in list)
            {
                if (list.First() == elem)
                {
                    rows.Add(elem);
                    i++;
                }
                else
                {

                    if (elem.Item == rows.ElementAt(i).Item &&
                        elem.FromWarehouse == rows.ElementAt(i).FromWarehouse &&
                        elem.ToWarehouse == rows.ElementAt(i).ToWarehouse)
                    {
                        rows.First().Quantity += elem.Quantity;
                        rows.First().batchs.Add(elem.batchs.First());
                    }
                    else
                    {
                        rows.Add(elem);
                        i++;
                    }
                }
            }

            return rows;
        }

This is the solution:

public static List<Counter> GroupBy(List<Counter> list)
        {
            List<Counter> rows = new List<Counter>();

            foreach (Counter elem in list)
            {
                if (rows.Any(x=>x.Item == elem.Item &&
                        x.FromWarehouse == elem.FromWarehouse &&
                        x.ToWarehouse == elem.ToWarehouse))
                {
                    rows.First().Quantity += elem.Quantity;
                    rows.First().batchs.Add(elem.batchs.First());
                }
                else
                {
                    rows.Add(elem);
                }
            }

            return rows;
        }

Body:
Let's try to write the Linq, step by step.

"I have List count":

   List<Counter> count = ...

"I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse":

   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })

"result should be grouped with summed quantity and the list of Batch merged", i.e. you should Aggregate items within each chunk

   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })
     .Select(chunk => new {
        key = chunk.Key,
        summary = chunk.Aggregate(
          Tuple.Create(0m, new List<Batch>()),                      // initial empty
          (s, a) => Tuple.Create(s.Item1 + a.Quantity,              // add
                                 s.Item2.Concat(a.batchs).ToList()) // merge
      })

Finally, let's represent the result in more convenient (readable) format:

   var result = count
     .GroupBy(item => new {
        item.Item,
        item.FromWarehouse
        item.ToWarehouse
      })
     .Select(chunk => new {
        key = chunk.Key,
        summary = chunk.Aggregate(
          Tuple.Create(0m, new List<Batch>()),
          (s, a) => Tuple.Create(s.Item1 + a.Quantity,
                                 s.Item2.Concat(a.batchs).ToList())
      })
     .Select(item => new {
        Item = item.key.Item,
        FromWarehouse = item.key.FromWarehouse,
        ToWarehouse = item.key.ToWarehouse,
        Quantity = item.summary.Item1,
        Batches = item.summary.Item2
      }); // Add ToArray() if you want to materialize


问:
Promise don't resolve in catchError typescript
I need resolve(false) in catchError, but this dosn't work.

In my loin.page.ts

async login() {
      if (this.signin.valid) {
        const controls = this.signin.controls;
        const valid = await this.authService.signin(controls.email.value, controls.password.value);
        if (valid) {
            this.navCtrl.navigateRoot('/user', { animated: true});
        } else {
            console.log('Bad credentials');
        }
    }
  }
```

<p><strong>authService.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

signin(email, password) {

        const headers = new HttpHeaders({
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        });
        const data = {
            email,
            password
        };
        const url = URL_SERVICIOS + 'xxx';
        return new Promise ((resolve) => {

            this.http.post(url, data).pipe(
                map( (result: any) => {
                    this.credentials = result;
                    resolve(true);
                }),
                catchError(() => {
                    return Promise.resolve(false);
                })
            ).subscribe();
        });
     }
</code>```

This code ends in 'return Promise.resolve(false);' and does not continue in loin.page.ts

答:
that's because you are returning a new Promise which will resolve instead of calling the resolve callback.

Try to do:

```<code>        catchError(() => {
             resolve(false);
         })
</code>```

Body:
I need resolve(false) in catchError, but this dosn't work.

In my loin.page.ts

async login() {
      if (this.signin.valid) {
        const controls = this.signin.controls;
        const valid = await this.authService.signin(controls.email.value, controls.password.value);
        if (valid) {
            this.navCtrl.navigateRoot('/user', { animated: true});
        } else {
            console.log('Bad credentials');
        }
    }
  }

authService.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

signin(email, password) {

        const headers = new HttpHeaders({
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        });
        const data = {
            email,
            password
        };
        const url = URL_SERVICIOS + 'xxx';
        return new Promise ((resolve) => {

            this.http.post(url, data).pipe(
                map( (result: any) => {
                    this.credentials = result;
                    resolve(true);
                }),
                catchError(() => {
                    return Promise.resolve(false);
                })
            ).subscribe();
        });
     }

This code ends in 'return Promise.resolve(false);' and does not continue in loin.page.ts

Body:
that's because you are returning a new Promise which will resolve instead of calling the resolve callback.

Try to do:

        catchError(() => {
             resolve(false);
         })


问:
PowerShell If Statement Failure
I need another set of eyes because I'm certain this is simple but it's kicking my butt right now. I'm writing a script to install Windows roles/features on both Server 2008 and Server 2012 machines.

I know that 2008 uses Add-WindowsFeature whereas 2012 uses Install-WindowsFeature.  So my goal is to look at the OS and if it's 2008 create a variable called $Install with a value of Add-WindowsFeature and if it's not 2008 give it the value of Install-WindowsFeature.

This is what I have now:

```<code>$OS = (Get-WmiObject Win32_OperatingSystem).Name

if ($OS -like '2008') {
    $Install = 'Add-WindowsFeature'
} else {
    $Install = 'Install-WindowsFeature'
}
</code>```

Currently, when I call up the $OS variable I get a returned value of:

```
Microsoft Windows Server 2008 R2 Standard |C:\Windows|\Device\Harddisk0\Partition2
```

But when I call up the $Install variable I get a returned value of:

```
Install-WindowsFeature
```

I've also tried -contains instead of -like but I get the same result.  I've also tried eliminating the spaces before the curly brackets, but still no change.  What am I doing wrong?

答: Alternatively the cmdlet Enable-WindowsOptionalFeature should be available on 2008 and beyond machines. You should be able to use that to install whatever feature you need regardless of the OS.

Title: PowerShell If Statement Failure

Body:
I need another set of eyes because I'm certain this is simple but it's kicking my butt right now. I'm writing a script to install Windows roles/features on both Server 2008 and Server 2012 machines.

I know that 2008 uses Add-WindowsFeature whereas 2012 uses Install-WindowsFeature.  So my goal is to look at the OS and if it's 2008 create a variable called $Install with a value of Add-WindowsFeature and if it's not 2008 give it the value of Install-WindowsFeature.

This is what I have now:

$OS = (Get-WmiObject Win32_OperatingSystem).Name

if ($OS -like '2008') {
    $Install = 'Add-WindowsFeature'
} else {
    $Install = 'Install-WindowsFeature'
}

Currently, when I call up the $OS variable I get a returned value of:

Microsoft Windows Server 2008 R2 Standard |C:\Windows|\Device\Harddisk0\Partition2

But when I call up the $Install variable I get a returned value of:

Install-WindowsFeature

I've also tried -contains instead of -like but I get the same result.  I've also tried eliminating the spaces before the curly brackets, but still no change.  What am I doing wrong?


问:
Infeasible Solution, Definitely Feasible - CPLEX
Basically, I have two employees, who could each be allocated to one of two roster patterns, which in turns allocates a set of shifts for each employee.

Allocate an employee a roster pattern -> that employee can only work shifts stated on that roster pattern, and must work all of them.

To that end, I have a constraint which basically states that the sum of all shifts each employee does should equal the input shiftsPerRP. So if a roster pattern, e.g. 0, is selected for say employee Allan, then Allan should work exactly 45 shifts.

However this constraint keeps failing and causing an infeasible solution. I can't work out what I'm missing here. Any help is appreciated.

Relevant DAT:

```<code>days={
    1, 2, 3, 4, 5, 6, 7
}

People = {
    Allan,
    Joe,
};

rosterPatterns = {
    0,1
};

shiftsPerRP = {
    <0,45>
    <1,5>
};

Skills= {
    A,
    B,
    C
};
</code>```

Relevant Code:

```<code>dvar boolean Assign[days][Hours][People][Skills];   // Indicates a shift assignment

range Hours = 0..23;

forall(h in Hours, d in days, p in People, rp in rosterPatterns, shiftsInRP in shiftsPerRP : shiftsInRP.ID == rp)
      sum(s in Skills)
            Assign[d][h][p][s] == shiftsInRP.shifts;
</code>```

答:
In order to analyze this, label your constraints (see the added 'c1'):

```<code>forall(h in Hours,
       d in days,
       p in People,
       rp in rosterPatterns,
       shiftsInRP in shiftsPerRP
       : shiftsInRP.ID == rp)
c1:
      sum(s in Skills)
            Assign[d][h][p][s] == shiftsInRP.shifts;
</code>```

With that OPL should compute a minimal conflict that shows which constraints are infeasible. Doing that (on the command line) I found that the very first constraint generated is infeasible. The constraint has only three variables on its left-hand side but the right-hand side is 5. This can never be satisfied.

Given that you have only three elements in your set Skills, the left-hand side of the constraint will always have 3 variables. Thus it can take values in {0, 1, 2, 3}. If for any tuple shifts has a value greater than 3 then this constraint can obviously not be satisfied.

EDIT: It looks like you may have mixed up what should go into the forall and what should go into the sum. In order to formulate that correctly I think you will need an auxiliary variable

```<code>dvar boolean RosterAssigned[People][rosterPatterns];
</code>```

that is 1 if a person is assigned to a roster pattern and 0 otherwise.
With that you can formulate the constraint as

```<code>forall(p in People)
  sum(h in Hours, s in Skills, d in days)
     Assign[d][h][p][s]
     == sum(rp in rosterPatterns, shiftsInRP in shiftsPerRP : shitsInRP.ID == rp) (RosterAssigned[p][rp] * shiftsInRP.shifts);
</code>```

The left-hand side gives the number of shifts a person p actually works. The right-hand side gives the number of shifts required by the roster pattern. Of course you also have to add constraints that guarantee that each employee is assigned to exactly one roster pattern.

Body:
Basically, I have two employees, who could each be allocated to one of two roster patterns, which in turns allocates a set of shifts for each employee.

Allocate an employee a roster pattern -> that employee can only work shifts stated on that roster pattern, and must work all of them.

To that end, I have a constraint which basically states that the sum of all shifts each employee does should equal the input shiftsPerRP. So if a roster pattern, e.g. 0, is selected for say employee Allan, then Allan should work exactly 45 shifts.

However this constraint keeps failing and causing an infeasible solution. I can't work out what I'm missing here. Any help is appreciated.

Relevant DAT:

days={
    1, 2, 3, 4, 5, 6, 7
}

People = {
    Allan,
    Joe,
};

rosterPatterns = {
    0,1
};

shiftsPerRP = {
    <0,45>
    <1,5>
};

Skills= {
    A,
    B,
    C
};

Relevant Code:

dvar boolean Assign[days][Hours][People][Skills];   // Indicates a shift assignment

range Hours = 0..23;

forall(h in Hours, d in days, p in People, rp in rosterPatterns, shiftsInRP in shiftsPerRP : shiftsInRP.ID == rp)
      sum(s in Skills)
            Assign[d][h][p][s] == shiftsInRP.shifts;

Body:
In order to analyze this, label your constraints (see the added 'c1'):

forall(h in Hours,
       d in days,
       p in People,
       rp in rosterPatterns,
       shiftsInRP in shiftsPerRP
       : shiftsInRP.ID == rp)
c1:
      sum(s in Skills)
            Assign[d][h][p][s] == shiftsInRP.shifts;

With that OPL should compute a minimal conflict that shows which constraints are infeasible. Doing that (on the command line) I found that the very first constraint generated is infeasible. The constraint has only three variables on its left-hand side but the right-hand side is 5. This can never be satisfied.

Given that you have only three elements in your set Skills, the left-hand side of the constraint will always have 3 variables. Thus it can take values in {0, 1, 2, 3}. If for any tuple shifts has a value greater than 3 then this constraint can obviously not be satisfied.

EDIT: It looks like you may have mixed up what should go into the forall and what should go into the sum. In order to formulate that correctly I think you will need an auxiliary variable

dvar boolean RosterAssigned[People][rosterPatterns];

that is 1 if a person is assigned to a roster pattern and 0 otherwise.
With that you can formulate the constraint as

forall(p in People)
  sum(h in Hours, s in Skills, d in days)
     Assign[d][h][p][s]
     == sum(rp in rosterPatterns, shiftsInRP in shiftsPerRP : shitsInRP.ID == rp) (RosterAssigned[p][rp] * shiftsInRP.shifts);

The left-hand side gives the number of shifts a person p actually works. The right-hand side gives the number of shifts required by the roster pattern. Of course you also have to add constraints that guarantee that each employee is assigned to exactly one roster pattern.


问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
A bit more cryptic than I'd like but with GNU awk for multi-char RS:

```<code>$ awk -v RS='\nvwxyz\n' -v ORS= '!sub(/(^|\n)abcd$/,""){$0=$0 RT} 1' file
abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

Unfortunately if we're going with an RS-based solution (as opposed to keeping a rolling 2-line buffer or similar) then that's how it has to be done to accommodate the multi-line string appearing at the start and/or end of the file and/or in repeated blocks and/or starting/stopping in the middle of other lines. It can be used as-is for arbitrary long blocks of lines though:

```<code>awk -v RS='\nvwxyz\n' -v ORS= '!sub(/(^|\n)foo\nbar\netc\nabcd$/,""){$0=$0 RT} 1' file
</code>```

or if you prefer:

```<code>awk -v RS='\nbar\netc\nabcd\nvwxyz\n' -v ORS= '!sub(/(^|\n)foo$/,""){$0=$0 RT} 1' file
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
A bit more cryptic than I'd like but with GNU awk for multi-char RS:

$ awk -v RS='\nvwxyz\n' -v ORS= '!sub(/(^|\n)abcd$/,""){$0=$0 RT} 1' file
abcd
line1
line2
line3
vwxyz
line4
line5

Unfortunately if we're going with an RS-based solution (as opposed to keeping a rolling 2-line buffer or similar) then that's how it has to be done to accommodate the multi-line string appearing at the start and/or end of the file and/or in repeated blocks and/or starting/stopping in the middle of other lines. It can be used as-is for arbitrary long blocks of lines though:

awk -v RS='\nvwxyz\n' -v ORS= '!sub(/(^|\n)foo\nbar\netc\nabcd$/,""){$0=$0 RT} 1' file

or if you prefer:

awk -v RS='\nbar\netc\nabcd\nvwxyz\n' -v ORS= '!sub(/(^|\n)foo$/,""){$0=$0 RT} 1' file


问:
getenv("APPDATA") returns incorrect values if current user having username containing unicode characters
Windows gives an api to get environment variable values using getenv(). If current user is having username containing localised characters (i.e. multibyte characters), then getenv returns incorrect value.

current user with username: テスト :
getenv("AppData") returns C:\Users\???\AppData\Roaming

It should return C:\Users\テスト\AppData\Roaming

Is there any alternative to getenv in Windows?

答:
Actually, getenv is not a Windows API function. That function is provided by the C runtime. If you wish to continue with a C runtime function, then rather than using getenv, you should use the Unicode version, _wgetenv.

The Windows API function, which getenv and _wgetenv wrap, is GetEnvironmentVariable. You could equally use that function, but you must make sure that you target Unicode when building, or call the Unicode version GetEnvironmentVariableW explicitly.

That answers the direct question that you asked. However, it is also worth pointing out that reading the APPDATA variable is not the correct way to obtain that information. You should instead call SHGetKnownFolderPath passing FOLDERID_RoamingAppData.


问:
driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption
I am trying to connect to my companies Microsoft sql via my groovy code. Using this code:

```<code>String conn= "jdbc:sqlserver://;servername="+url+";databaseName=central;user=***qa***;password=***mypassword***;"
    def sqlConnection = Sql.newInstance(conn,username,password,"com.microsoft.sqlserver.jdbc.SQLServerDriver")
</code>```

This results with the error:

mgroovy.lang.MissingPropertyException: No such property: connection
  for class: sqlKeyWords.checking[0;39m [31m    at
  sqlKeyWords.checking.connectDB(checking.groovy:60)[0;39m [31m at
  sqlKeyWords.checking.invokeMethod(checking.groovy)[0;39m [31m at
  com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:49)[0;39m
  [31m  at CreateOrg.run(CreateOrg:47)[0;39m [31m   at
  com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)[0;39m
  [31m  at
  com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:331)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:322)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:301)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:293)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:227)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:114)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:105)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown
  Source)[0;39m [31m    at
  TempTestCase1555589132729.run(TempTestCase1555589132729.groovy:21)

This error is not so descriptive, therefore here is an error that I found in the debug:

The driver could not establish a secure connection to SQL Server by
  using Secure Sockets Layer (SSL) encryption

I later tried this from http://docs.groovy-lang.org/latest/html/api/groovy/sql/Sql.html:

```<code>def db = [url:'jdbc:sqlserver:'+url+':central', user:username, password:password, driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
</code>```

and this resulted in:

No suitable driver found for jdbc:sqlserver:aaa-sql-qa.database.windows.bbb:dbName

I saw many answers, most of them say to play with the server's firewall, but I am able to connect to the DB via my python code or via the SSMS. Also, I don't have the ability to play with the firewall. I saw to use jTDS in this answer, but I was unable to proceed there with other issues (of course it also didn't connect)

答:
I don't know why but when running debug on the line where I connect to debug gave me this error. This occurred to me in automation tool Katalon (which uses groovy)

(Of course b/c it was not working I was trying to use debug exactly there)

Body:
I am trying to connect to my companies Microsoft sql via my groovy code. Using this code:

String conn= "jdbc:sqlserver://;servername="+url+";databaseName=central;user=***qa***;password=***mypassword***;"
    def sqlConnection = Sql.newInstance(conn,username,password,"com.microsoft.sqlserver.jdbc.SQLServerDriver")

This results with the error:

mgroovy.lang.MissingPropertyException: No such property: connection
  for class: sqlKeyWords.checking[0;39m [31m    at
  sqlKeyWords.checking.connectDB(checking.groovy:60)[0;39m [31m at
  sqlKeyWords.checking.invokeMethod(checking.groovy)[0;39m [31m at
  com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:49)[0;39m
  [31m  at CreateOrg.run(CreateOrg:47)[0;39m [31m   at
  com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)[0;39m
  [31m  at
  com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:331)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:322)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:301)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:293)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:227)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:114)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:105)[0;39m
  [31m  at
  com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown
  Source)[0;39m [31m    at
  TempTestCase1555589132729.run(TempTestCase1555589132729.groovy:21)

This error is not so descriptive, therefore here is an error that I found in the debug:

The driver could not establish a secure connection to SQL Server by
  using Secure Sockets Layer (SSL) encryption

I later tried this from http://docs.groovy-lang.org/latest/html/api/groovy/sql/Sql.html:

def db = [url:'jdbc:sqlserver:'+url+':central', user:username, password:password, driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

and this resulted in:

No suitable driver found for jdbc:sqlserver:aaa-sql-qa.database.windows.bbb:dbName

I saw many answers, most of them say to play with the server's firewall, but I am able to connect to the DB via my python code or via the SSMS. Also, I don't have the ability to play with the firewall. I saw to use jTDS in this answer, but I was unable to proceed there with other issues (of course it also didn't connect)


问:
C# WPF Check-up a ListView Item By Index?
I use C# WPF. I want to checkup list view items by their index. How do I accomplish that?

Code I tried-

```<code>int index= 10;
this.lstView1.Items[index].Checked=true;
</code>```

It worked in WinForms, but not working anymore after migrating to XAML.

My XAML:

```<code>    <ListView Height="400" Width="400"
      Name="lstView1"
      ItemsSource="{Binding}"
      IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                    <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                    <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock FontWeight="Bold" Text="Group"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</code>```

答:
```<code>int index= 10;

//selected
this.lstView1.SelectedItems.Add(this.lvUsers.Items[index]);

//checked
((User)this.lstView1.Items[index]).IsChecked = true;
</code>```

Body:
I use C# WPF. I want to checkup list view items by their index. How do I accomplish that?

Code I tried-

int index= 10;
this.lstView1.Items[index].Checked=true;

It worked in WinForms, but not working anymore after migrating to XAML.

My XAML:

    <ListView Height="400" Width="400"
      Name="lstView1"
      ItemsSource="{Binding}"
      IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                    <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                    <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock FontWeight="Bold" Text="Group"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>


问:
Obtaining host url of sftp server from a docker container
I am running django project in docker container. I have a sftp server running on another container, and wish to sftp into it from web container. Using python library paramiko from shell I can manually sftp into container by finding IP of server using docker inspect.

I wish to save sftp url in settings.py file and reference it later when needed.

Currently my docker-compose file has sftp image:

```<code>sftp:
    image: atmoz/sftp
    container_name: sftp
    volumes:
      - /host/upload:/home/
    ports:
        - "22:22"
    command:
      - foo:pass:::upload
</code>```

And web container has following environment variables:

```<code>environment:
  SFTP_USERNAME: foo
  SFTP_PASSWORD: pass
  SFTP_HOSTNAME: sftp
  SFTP_PORT: 20
</code>```

Then in settings.py I constructed url as follows:

```<code>SFTP_URL = 'sftp://' + SFTP_USERNAME + ':' + SFTP_PASSWORD + '@' + SFTP_HOSTNAME + ':' + SFTP_PORT + '/'
</code>```

this is used in tasks.py in a simple function for now, mostly just creating the sftp connection

```<code>def sftp():
    transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT)))
    transport.connect(username = settings.SFTP_USERNAME, password = settings.SFTP_PASSWORD)

    sftp = paramiko.SFTPClient.from_transport(transport)

    return sftp
</code>```

However instead of connecting, get following error message:

```<code>Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/opt/django/CustomerData/tasks.py", line 34, in sftp
    transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT)))
  File "/opt/venv/lib/python3.5/site-packages/paramiko/transport.py", line 357, in __init__
    hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
  File "/usr/lib/python3.5/socket.py", line 732, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known```
```

答: I think your code is bugged, simply change SFTP_URL to SFTP_HOSTNAME. As far as I understand, you are confusing the names of variables

Body:
I am running django project in docker container. I have a sftp server running on another container, and wish to sftp into it from web container. Using python library paramiko from shell I can manually sftp into container by finding IP of server using docker inspect.

I wish to save sftp url in settings.py file and reference it later when needed.

Currently my docker-compose file has sftp image:

sftp:
    image: atmoz/sftp
    container_name: sftp
    volumes:
      - /host/upload:/home/
    ports:
        - "22:22"
    command:
      - foo:pass:::upload

And web container has following environment variables:

environment:
  SFTP_USERNAME: foo
  SFTP_PASSWORD: pass
  SFTP_HOSTNAME: sftp
  SFTP_PORT: 20

Then in settings.py I constructed url as follows:

SFTP_URL = 'sftp://' + SFTP_USERNAME + ':' + SFTP_PASSWORD + '@' + SFTP_HOSTNAME + ':' + SFTP_PORT + '/'

this is used in tasks.py in a simple function for now, mostly just creating the sftp connection

def sftp():
    transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT)))
    transport.connect(username = settings.SFTP_USERNAME, password = settings.SFTP_PASSWORD)

    sftp = paramiko.SFTPClient.from_transport(transport)

    return sftp

However instead of connecting, get following error message:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/opt/django/CustomerData/tasks.py", line 34, in sftp
    transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT)))
  File "/opt/venv/lib/python3.5/site-packages/paramiko/transport.py", line 357, in __init__
    hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
  File "/usr/lib/python3.5/socket.py", line 732, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known```