问:
Generate Multiple Mails with Outlook
I want to send an E-Mail to multiple customers with Outlook. For this I have a method in my Program that iterates the recipients, composes the message body and displays the first message as a Preview.

This is a simplified version of that method:

```<code>public void CreateMails(List<InfoMailRecipient> recipients)
{
    Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
    foreach (InfoMailRecipient recipient in recipients)
    {
        MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
        mail.SentOnBehalfOfName = "Sending User";
        mail.BCC = recipient.EMailAddress;

        mail.Subject = "TEST";
        mail.BodyFormat = OlBodyFormat.olFormatHTML;
        mail.HTMLBody = "<html><body>test</body></html>";
        mail.Display(true);
    }
}
</code>```

When the Outlook message window is displayed, no matter if I just close the window or click "Send", as soon as the next MailItemshould be created I get an exception "RPC Server unavailable". Obviously because Outlook has closed. I've found out that when I remove the line

```<code>mail.Display(true);
</code>```

and just call .Send(); all the messages are sent properly. But then Outlook stays open. Even if I call .Quit() after the foreach loop.

How do I handle this Outlook instance properly?

Update 1 - Manual GC-Call

```<code>public void CreateMails(List<InfoMailRecipient> recipients)
{
    Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
    foreach (InfoMailRecipient recipient in recipients)
    {
        MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
        mail.SentOnBehalfOfName = "Sending User";
        mail.BCC = recipient.EMailAddress;

        mail.Subject = "TEST";
        mail.BodyFormat = OlBodyFormat.olFormatHTML;
        mail.HTMLBody = "<html><body>test</body></html>";
        mail.Send();
    }
    outlook.Quit();
    GC.Collect();
    GC.WaitForPendingFinalizers();
}
</code>```

Outlook keeps running.

答:
This appears to work - can you let us know if it works for you too?

```<code>    public static void Main(string[] args)
    {
        CreateMails(new List<string>() {"emailaddresshere"});
        Console.WriteLine("finished");
        Console.ReadLine();
    }

    public static void CreateMails(List<string> recipients)
    {
        Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
        foreach (string recipient in recipients)
        {
            MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
            mail.SentOnBehalfOfName = "Sending User";
            mail.BCC = recipient;

            mail.Subject = "TEST";
            mail.BodyFormat = OlBodyFormat.olFormatPlain;
            mail.HTMLBody = "Hello";
            mail.Send();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(mail); // key change
        }
        GC.Collect();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        outlook.Application.Quit();
        outlook.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(outlook); // key change
        outlook = null;
        GC.Collect();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
</code>```

Also have a read of https://ausdotnet.wordpress.com/category/technical/com-interop/ and How to close outlook after automating it in c# .

Title: Generate Multiple Mails with Outlook

Body:
I want to send an E-Mail to multiple customers with Outlook. For this I have a method in my Program that iterates the recipients, composes the message body and displays the first message as a Preview.

This is a simplified version of that method:

public void CreateMails(List<InfoMailRecipient> recipients)
{
    Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
    foreach (InfoMailRecipient recipient in recipients)
    {
        MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
        mail.SentOnBehalfOfName = "Sending User";
        mail.BCC = recipient.EMailAddress;

        mail.Subject = "TEST";
        mail.BodyFormat = OlBodyFormat.olFormatHTML;
        mail.HTMLBody = "test";
        mail.Display(true);
    }
}

When the Outlook message window is displayed, no matter if I just close the window or click "Send", as soon as the next MailItemshould be created I get an exception "RPC Server unavailable". Obviously because Outlook has closed. I've found out that when I remove the line

mail.Display(true);

and just call .Send(); all the messages are sent properly. But then Outlook stays open. Even if I call .Quit() after the foreach loop.

How do I handle this Outlook instance properly?

Update 1 - Manual GC-Call

public void CreateMails(List<InfoMailRecipient> recipients)
{
    Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
    foreach (InfoMailRecipient recipient in recipients)
    {
        MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
        mail.SentOnBehalfOfName = "Sending User";
        mail.BCC = recipient.EMailAddress;

        mail.Subject = "TEST";
        mail.BodyFormat = OlBodyFormat.olFormatHTML;
        mail.HTMLBody = "test";
        mail.Send();
    }
    outlook.Quit();
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

Outlook keeps running.

Body:
This appears to work - can you let us know if it works for you too?

    public static void Main(string[] args)
    {
        CreateMails(new List<string>() {"emailaddresshere"});
        Console.WriteLine("finished");
        Console.ReadLine();
    }

    public static void CreateMails(List<string> recipients)
    {
        Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
        foreach (string recipient in recipients)
        {
            MailItem mail = outlook.CreateItem(OlItemType.olMailItem);
            mail.SentOnBehalfOfName = "Sending User";
            mail.BCC = recipient;

            mail.Subject = "TEST";
            mail.BodyFormat = OlBodyFormat.olFormatPlain;
            mail.HTMLBody = "Hello";
            mail.Send();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(mail); // key change
        }
        GC.Collect();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        outlook.Application.Quit();
        outlook.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(outlook); // key change
        outlook = null;
        GC.Collect();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

Also have a read of https://ausdotnet.wordpress.com/category/technical/com-interop/ and How to close outlook after automating it in c# .


来源: stackexchange

问:
Run lagged regressions for finance data
I am trying to run lagged regression for each of the 30 assets in my data frame.

My table looks like this:

```<code> date          rx1   rx2   rx3
    1930-01-31  0     0     0
    1930-02-28  0     0    -0.3
    1930-03-31  0     0    -0.1
    ....              -0.1  ...
    1975-02-28  -0.4  -0.2  ...
    2016-12-31  -0.03  ...  ...
</code>```

Then I tried to run lagged regressions with this line(dataframe:Rx3.df):

```<code>model <- dyn$lm(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1, 2))
</code>```

But I kept getting this result that does not make any sense:

```<code>Call:
lm(formula = dyn(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1,
    2)))

Coefficients:
       (Intercept)  lag(Rx3.df$rx1, 1)  lag(Rx3.df$rx1, 2)
         3.297e-16           1.000e+00                  NA
</code>```

Can anyone figure out the problem? Thanks!

答:
I apologize in advance for the long answer. It seems that for some reason (NO IDEA WHY?) dyn$lm doesn't omit the NAs. If for, example you type summary(model), you'll get this warning message:

```<code>Warning message:
In summary.lm(lm(rx1 ~ lag(rx1, 1), data = df, model = T)) :
  essentially perfect fit: summary may be unreliable
</code>```

Also, if you type nobs(model), you will get the the same as nrow(Rx3.df), which shouldn't happen because you'll be dropping at least 1 observation per lag.

I recreated part of your data as follows:

```<code>> df<- data.frame(rx1 = runif(1000, 1, 100))
> head(df, 5)
       rx1
1 56.63239
2 89.99562
3 37.35498
4  7.47771
5 92.77819
</code>```

And as in your case, I get:

```<code>> summary(dyn$lm(rx1~lag(rx1, 1) + lag(rx1, 2), data=df))

Call:
lm(formula = dyn(rx1 ~ lag(rx1, 1) + lag(rx1, 2)), data = df)

Residuals:
       Min         1Q     Median         3Q        Max
-3.982e-13 -5.400e-16  3.600e-16  1.230e-15  1.211e-14

Coefficients: (1 not defined because of singularities)
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 2.876e-14  8.219e-16 3.499e+01   <2e-16 ***
lag(rx1, 1) 1.000e+00  1.424e-17 7.024e+16   <2e-16 ***
lag(rx1, 2)        NA         NA        NA       NA
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.275e-14 on 998 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 4.934e+33 on 1 and 998 DF,  p-value: < 2.2e-16

Warning message:
In summary.lm(dyn$lm(rx1 ~ lag(rx1, 1) + lag(rx1, 2), data = df)) :
  essentially perfect fit: summary may be unreliable
</code>```

However, if I lag the variables manually:

```<code>> library(dplyr)
> df_lag<- mutate(df, lag1_rx1 = lag(rx1), lag2_rx1 = lag(rx1, 2))
> head(df_lag, 5)
       rx1 lag1_rx1 lag2_rx1
1 56.63239       NA       NA
2 89.99562 56.63239       NA
3 37.35498 89.99562 56.63239
4  7.47771 37.35498 89.99562
5 92.77819  7.47771 37.35498
</code>```

The results are correct:

```<code>> summary(dyn$lm(rx1~lag1_rx1+lag2_rx1, data=df_lag))

Call:
lm(formula = dyn(rx1 ~ lag1_rx1 + lag2_rx1), data = df_lag)

Residuals:
    Min      1Q  Median      3Q     Max
-50.325 -23.271  -0.471  24.763  50.864

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 50.84681    2.46790  20.603   <2e-16 ***
lag1_rx1    -0.03664    0.03170  -1.156    0.248
lag2_rx1     0.02494    0.03170   0.787    0.432
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 28.34 on 995 degrees of freedom
  (2 observations deleted due to missingness)
Multiple R-squared:  0.002033,  Adjusted R-squared:  2.741e-05
F-statistic: 1.014 on 2 and 995 DF,  p-value: 0.3633
</code>```

Note that in the second case, right under the Residual standard error, I get a notification that (2 observations deleted due to missingness), which should happen! This is also mirrored on the degrees of freedom, which should be equal to the number of observations you have, minus the number of parameters you're estimating.

I hope this helps!

MAJOR EDIT for multiple variables
You will need to use data.table for this solution. I also created a new df to match the example you gave.

```<code>library(data.table)
> df<- data.table(date= sample(seq(as.Date('1900/01/01'), as.Date('2000/01/01'), by="day"), 1000), rx1 = runif(1000, 1, 100), rx2 = rnorm(1000), rx3 = rpois(1000, 1))
> head(df, 5)
         date       rx1         rx2 rx3
1: 1989-01-16  9.642232 -1.14117351   0
2: 1964-05-10 55.946293  1.21938225   1
3: 1911-11-24  8.609234 -0.77489439   1
4: 1914-09-29 57.253969  0.02277709   0
5: 1902-08-09 69.454322 -0.10850359   1
</code>```

The next two pieces of code create the lags:

```<code>> df[, paste0("lag1_", names(df)[like(names(df), "^rx")]) := shift(.SD), .SDcols = like(names(df), "^rx")]
> df[, paste0("lag2_", names(df)[like(names(df), "^rx")]) := shift(.SD, 2), .SDcols = like(names(df), "^rx")]
> head(df, 5)
         date       rx1         rx2 rx3  lag1_rx1    lag1_rx2 lag1_rx3  lag2_rx1   lag2_rx2
1: 1989-01-16  9.642232 -1.14117351   0        NA          NA       NA        NA         NA
2: 1964-05-10 55.946293  1.21938225   1  9.642232 -1.14117351        0        NA         NA
3: 1911-11-24  8.609234 -0.77489439   1 55.946293  1.21938225        1  9.642232 -1.1411735
4: 1914-09-29 57.253969  0.02277709   0  8.609234 -0.77489439        1 55.946293  1.2193823
5: 1902-08-09 69.454322 -0.10850359   1 57.253969  0.02277709        0  8.609234 -0.7748944
   lag2_rx3
1:       NA
2:       NA
3:        0
4:        1
5:        1
</code>```

And finally the results:

```<code>> formula<- paste0(paste0("rx", 1:3),"~", paste0("lag1_rx", 1:3), "+", paste0("lag2_rx", 1:3))
> results<- lapply(formula, function(x) lm(x, data=df))
> names(results)<- paste0("rx", 1:3)
</code>```

Obviously, change the 3 above to how ever many variables you have. I'm not providing the output because it's too big. For rx1 you can access the results by typing summary(results[["rx1"]].

PS: It doesn't seem to make a difference if you use dyn$lm compared to regular old lm.

ContentLicense: CC BY-SA 3.0

Title: Run lagged regressions for finance data

Body:
I am trying to run lagged regression for each of the 30 assets in my data frame.

My table looks like this:

 date          rx1   rx2   rx3
    1930-01-31  0     0     0
    1930-02-28  0     0    -0.3
    1930-03-31  0     0    -0.1
    ....              -0.1  ...
    1975-02-28  -0.4  -0.2  ...
    2016-12-31  -0.03  ...  ...

Then I tried to run lagged regressions with this line(dataframe:Rx3.df):

model <- dyn$lm(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1, 2))

But I kept getting this result that does not make any sense:

Call:
lm(formula = dyn(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1,
    2)))

Coefficients:
       (Intercept)  lag(Rx3.df$rx1, 1)  lag(Rx3.df$rx1, 2)
         3.297e-16           1.000e+00                  NA

Can anyone figure out the problem? Thanks!

Body:
I apologize in advance for the long answer. It seems that for some reason (NO IDEA WHY?) dyn$lm doesn't omit the NAs. If for, example you type summary(model), you'll get this warning message:

Warning message:
In summary.lm(lm(rx1 ~ lag(rx1, 1), data = df, model = T)) :
  essentially perfect fit: summary may be unreliable

Also, if you type nobs(model), you will get the the same as nrow(Rx3.df), which shouldn't happen because you'll be dropping at least 1 observation per lag.

I recreated part of your data as follows:

> df<- data.frame(rx1 = runif(1000, 1, 100))
> head(df, 5)
       rx1
1 56.63239
2 89.99562
3 37.35498
4  7.47771
5 92.77819

And as in your case, I get:

> summary(dyn$lm(rx1~lag(rx1, 1) + lag(rx1, 2), data=df))

Call:
lm(formula = dyn(rx1 ~ lag(rx1, 1) + lag(rx1, 2)), data = df)

Residuals:
       Min         1Q     Median         3Q        Max
-3.982e-13 -5.400e-16  3.600e-16  1.230e-15  1.211e-14

Coefficients: (1 not defined because of singularities)
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 2.876e-14  8.219e-16 3.499e+01   <2e-16 ***
lag(rx1, 1) 1.000e+00  1.424e-17 7.024e+16   <2e-16 ***
lag(rx1, 2)        NA         NA        NA       NA
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.275e-14 on 998 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 4.934e+33 on 1 and 998 DF,  p-value: < 2.2e-16

Warning message:
In summary.lm(dyn$lm(rx1 ~ lag(rx1, 1) + lag(rx1, 2), data = df)) :
  essentially perfect fit: summary may be unreliable

However, if I lag the variables manually:

> library(dplyr)
> df_lag<- mutate(df, lag1_rx1 = lag(rx1), lag2_rx1 = lag(rx1, 2))
> head(df_lag, 5)
       rx1 lag1_rx1 lag2_rx1
1 56.63239       NA       NA
2 89.99562 56.63239       NA
3 37.35498 89.99562 56.63239
4  7.47771 37.35498 89.99562
5 92.77819  7.47771 37.35498

The results are correct:

> summary(dyn$lm(rx1~lag1_rx1+lag2_rx1, data=df_lag))

Call:
lm(formula = dyn(rx1 ~ lag1_rx1 + lag2_rx1), data = df_lag)

Residuals:
    Min      1Q  Median      3Q     Max
-50.325 -23.271  -0.471  24.763  50.864

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 50.84681    2.46790  20.603   <2e-16 ***
lag1_rx1    -0.03664    0.03170  -1.156    0.248
lag2_rx1     0.02494    0.03170   0.787    0.432
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 28.34 on 995 degrees of freedom
  (2 observations deleted due to missingness)
Multiple R-squared:  0.002033,  Adjusted R-squared:  2.741e-05
F-statistic: 1.014 on 2 and 995 DF,  p-value: 0.3633

Note that in the second case, right under the Residual standard error, I get a notification that (2 observations deleted due to missingness), which should happen! This is also mirrored on the degrees of freedom, which should be equal to the number of observations you have, minus the number of parameters you're estimating.

I hope this helps!

MAJOR EDIT for multiple variables
You will need to use data.table for this solution. I also created a new df to match the example you gave.

library(data.table)
> df<- data.table(date= sample(seq(as.Date('1900/01/01'), as.Date('2000/01/01'), by="day"), 1000), rx1 = runif(1000, 1, 100), rx2 = rnorm(1000), rx3 = rpois(1000, 1))
> head(df, 5)
         date       rx1         rx2 rx3
1: 1989-01-16  9.642232 -1.14117351   0
2: 1964-05-10 55.946293  1.21938225   1
3: 1911-11-24  8.609234 -0.77489439   1
4: 1914-09-29 57.253969  0.02277709   0
5: 1902-08-09 69.454322 -0.10850359   1

The next two pieces of code create the lags:

> df[, paste0("lag1_", names(df)[like(names(df), "^rx")]) := shift(.SD), .SDcols = like(names(df), "^rx")]
> df[, paste0("lag2_", names(df)[like(names(df), "^rx")]) := shift(.SD, 2), .SDcols = like(names(df), "^rx")]
> head(df, 5)
         date       rx1         rx2 rx3  lag1_rx1    lag1_rx2 lag1_rx3  lag2_rx1   lag2_rx2
1: 1989-01-16  9.642232 -1.14117351   0        NA          NA       NA        NA         NA
2: 1964-05-10 55.946293  1.21938225   1  9.642232 -1.14117351        0        NA         NA
3: 1911-11-24  8.609234 -0.77489439   1 55.946293  1.21938225        1  9.642232 -1.1411735
4: 1914-09-29 57.253969  0.02277709   0  8.609234 -0.77489439        1 55.946293  1.2193823
5: 1902-08-09 69.454322 -0.10850359   1 57.253969  0.02277709        0  8.609234 -0.7748944
   lag2_rx3
1:       NA
2:       NA
3:        0
4:        1
5:        1

And finally the results:

> formula<- paste0(paste0("rx", 1:3),"~", paste0("lag1_rx", 1:3), "+", paste0("lag2_rx", 1:3))
> results<- lapply(formula, function(x) lm(x, data=df))
> names(results)<- paste0("rx", 1:3)

Obviously, change the 3 above to how ever many variables you have. I'm not providing the output because it's too big. For rx1 you can access the results by typing summary(results[["rx1"]].

PS: It doesn't seem to make a difference if you use dyn$lm compared to regular old lm.


问:
$rootScope:inprog $apply already in progress .change event error
In my project, I'm trying to upload an image, read it as a dataURL and store it into my database.

my HTML ng-click's call these methods with either true or false as a parameter (one does body image and the other a profile image)

Depending on whether true or false is called, it changes the id's for the event.

For some reason, when its "true" everything works perfectly fine.  The user can pick the image, it gets sent to the database properly, and the image is loaded properly.

However, when "false" is called, I get the error:

[$rootScope:inprog] $apply already in progress

and then the console.log() test "2222" does not get called.

Html

```<code><img src="{{controller.myCause.causeImage}}" ng-click="controller.uploadImage('true')" alt="Your Image Here" class="cause-img" id="profileImage" style="width: 80%; height: 35%;" height="300" />
<input id="imageUpload" type='file'>

<img src="{{controller.myCause.causeThumbnailImage}}" ng-click="controller.uploadImage('false')" alt="Your Thumbnail Here" id="profileImageThumb" class="cause-img" style="width: 80%; height: 20%;" height="200" />
<input id="profileImageUpload" type='file'>
</code>```

Client Side

/////////////////////////////////////
//Begin Uploading Cause Profile Image
public uploadImage(bool) {
    if (bool === "true") {
        $("#imageUpload").click();
        this.imgUpload(bool);
    } else {
        $("#profileImageThumb").click();
        this.imgUpload(bool);
    }
}

public imgUpload(bool) {
    console.log(bool);
    var _this = this;
    var id = "";
    var imgId = "";

    if (bool === "true") {
        id = "#imageUpload";
        imgId = "#profileImage";
    } else {
        id = "#profileImageUpload";
        imgId = "#profileImageThumb";
    }

    console.log("111");

    $(id).change(function () {
        console.log("2222");
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(this.files[0]);
            $(imgId).attr('src', this.files[0]);
            _this.convertFileToBase64AndSet(this.files, bool);
        }
    });

};

convertFileToBase64AndSet(fileList: FileList, bool) {
    var self = this;
    if (fileList.length > 0) {
        var reader = new FileReader();

        reader.onloadend = (e: Event) => {
            self.postProfileImage(reader.result, bool);
        }
        reader.readAsDataURL(fileList[0]);
    }
}

public postProfileImage(file, bool) {

    if (bool === "true") {
        this.$http.put(`api/causes/profpic`, JSON.stringify(file)).then((res) => {
            this.$state.reload();
        });
    } else {
        this.$http.put(`api/causes/thumbpic`, JSON.stringify(file)).then((res) => {
            this.$state.reload();
        });
    }
}
//End Cause Profile Image Upload
////////////////////////////////```

答:
Your click event is running digest cycle which is conflicting with current digest cycle.

you can use setTimeout()

Can you try this

```<code>public uploadImage(bool) {
    if (bool === "true") {
        setTimeout(function({$("#imageUpload").click();})
        this.imgUpload(bool);
    } else {
        setTimeout(function({$("#profileImageThumb").click();})
        this.imgUpload(bool);
    }
}
</code>```

Body:
In my project, I'm trying to upload an image, read it as a dataURL and store it into my database.

my HTML ng-click's call these methods with either true or false as a parameter (one does body image and the other a profile image)

Depending on whether true or false is called, it changes the id's for the event.

For some reason, when its "true" everything works perfectly fine.  The user can pick the image, it gets sent to the database properly, and the image is loaded properly.

However, when "false" is called, I get the error:

[$rootScope:inprog] $apply already in progress

and then the console.log() test "2222" does not get called.

Html

<input id="imageUpload" type='file'>

<input id="profileImageUpload" type='file'>

Client Side

/////////////////////////////////////
//Begin Uploading Cause Profile Image
public uploadImage(bool) {
    if (bool === "true") {
        $("#imageUpload").click();
        this.imgUpload(bool);
    } else {
        $("#profileImageThumb").click();
        this.imgUpload(bool);
    }
}

public imgUpload(bool) {
    console.log(bool);
    var _this = this;
    var id = "";
    var imgId = "";

    if (bool === "true") {
        id = "#imageUpload";
        imgId = "#profileImage";
    } else {
        id = "#profileImageUpload";
        imgId = "#profileImageThumb";
    }

    console.log("111");

    $(id).change(function () {
        console.log("2222");
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(this.files[0]);
            $(imgId).attr('src', this.files[0]);
            _this.convertFileToBase64AndSet(this.files, bool);
        }
    });

};

convertFileToBase64AndSet(fileList: FileList, bool) {
    var self = this;
    if (fileList.length > 0) {
        var reader = new FileReader();

        reader.onloadend = (e: Event) => {
            self.postProfileImage(reader.result, bool);
        }
        reader.readAsDataURL(fileList[0]);
    }
}

public postProfileImage(file, bool) {

    if (bool === "true") {
        this.$http.put(`api/causes/profpic`, JSON.stringify(file)).then((res) => {
            this.$state.reload();
        });
    } else {
        this.$http.put(`api/causes/thumbpic`, JSON.stringify(file)).then((res) => {
            this.$state.reload();
        });
    }
}
//End Cause Profile Image Upload
////////////////////////////////

Body:
Your click event is running digest cycle which is conflicting with current digest cycle.

you can use setTimeout()

Can you try this

public uploadImage(bool) {
    if (bool === "true") {
        setTimeout(function({$("#imageUpload").click();})
        this.imgUpload(bool);
    } else {
        setTimeout(function({$("#profileImageThumb").click();})
        this.imgUpload(bool);
    }
}


问:
Eval list within quotes
I am writing a program in Python that takes in user input (not using Python's built-in input) that is a string that contains a list of strings, ie. '["hello", "world"]'. However, some inputs will have multiple quotes inside, ie. '["Hello", "wor"ld"]'. I need the string to always eval() to a list. Any advice on cleansing the input string to ensure that it will always eval? Already tried .replace('"', '\"').

答: This is a somewhat difficult problem because it is hard for the computer to know which of the quotations are extraneous and which are the intended ones. The best solution which i can think of would be to first remove all double quotes and spaces, then add back in double quotes after any instance of the characters "[", insert a space and double quotes after any comma, and insert double quotes before every comma and "]". This is not an elegant solution and may take a few lines of code but unless you can sanitize the input earlier in the program this is probably the best solution.</p>

Title: Eval list within quotes


问:
The pyvirtualdisplay Error in python
I'm getting the following error when i try to run the python code
File_1.py actually import File_2.py to call the function.

```<code>Traceback (most recent call last):
File "File_1.py", line 1, in <module>
import File_2
File "/home/eduser/shashank/File_2.py", line 8, in <module>
display = Display(visible=0, size=(800, 600))
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/display.py",
line 34, in __init__
self._obj = self.display_class(
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/display.py",
line 52, in display_class
cls.check_installed()
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/xvfb.py", line
38, in check_installed
ubuntu_package=PACKAGE).check_installed()
File "/usr/local/lib/python2.7/dist-packages/easyprocess/__init__.py", line
180, in check_installed
raise EasyProcessCheckInstalledError(self)
easyprocess.EasyProcessCheckInstalledError: cmd=['Xvfb', '-help']
OSError=None
Program install error!
</code>```

here is the section of code to which the error points

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import File_3_1

from pyvirtualdisplay import Display

display = Display(visible=0, size=(800, 600))
display.start()
</code>```

Any help will be appreciated.

答:
You might just need to have xvfv installed. Try:

```<code>sudo apt-get install xvfb xserver-xephyr vnc4server
</code>```

See: http://pyvirtualdisplay.readthedocs.io/en/latest/#installation

Title: The pyvirtualdisplay Error in python

Body:
I'm getting the following error when i try to run the python code
File_1.py actually import File_2.py to call the function.

Traceback (most recent call last):
File "File_1.py", line 1, in <module>
import File_2
File "/home/eduser/shashank/File_2.py", line 8, in <module>
display = Display(visible=0, size=(800, 600))
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/display.py",
line 34, in __init__
self._obj = self.display_class(
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/display.py",
line 52, in display_class
cls.check_installed()
File "/usr/local/lib/python2.7/dist-packages/pyvirtualdisplay/xvfb.py", line
38, in check_installed
ubuntu_package=PACKAGE).check_installed()
File "/usr/local/lib/python2.7/dist-packages/easyprocess/__init__.py", line
180, in check_installed
raise EasyProcessCheckInstalledError(self)
easyprocess.EasyProcessCheckInstalledError: cmd=['Xvfb', '-help']
OSError=None
Program install error!

here is the section of code to which the error points

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import File_3_1

from pyvirtualdisplay import Display

display = Display(visible=0, size=(800, 600))
display.start()

Any help will be appreciated.

Body:
You might just need to have xvfv installed. Try:

sudo apt-get install xvfb xserver-xephyr vnc4server

See: http://pyvirtualdisplay.readthedocs.io/en/latest/#installation


问:
Insert cell in tableview in swift
I'm currently doing an app in swift and doing a menubar that scrolls from the right of the screen and display a list of possibilities.

I created the UITableView on my storyboard as a view that I sticked over the Navigation Controller.

I want now to add cells to this tableview to create a navigation bar, but I don't know how do it since there's no controller managing the item menuView.
Here is my ViewControllerClass:

```<code>import CoreData

class ViewController: UIViewController {

@IBOutlet weak var menuView: UITableView!

var menuShowing = false
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    menuView.layer.shadowOpacity = 1
    menuView.layer.shadowRadius = 6

}

@IBAction func openMenu(_ sender: Any) {
    if (menuShowing)
    {
        leadingConstraint.constant = -200
        UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
    } else {
        leadingConstraint.constant = 0
        UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
    }
    menuShowing  = !menuShowing
}
}
</code>```

My questions are :
Is my menuView object well done or should I reconsider my previous work?

Can I add a cell in the menuView object simply with a simple function like:
    MenuView.addRow( * something *)?

答:
You can set the UITableViewDataSource and if you want to UITableViewDelegate to ViewController to make the tableView be controlled by ViewController. </p>

```<code>import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

 @IBOutlet weak var menuView: UITableView!

var menuShowing = false
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()

menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 6
menuView.dataSource = self
menuView.delegate = self

 }

// Handle TableView like you normally do:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return UITableViewCell()
}

 @IBAction func openMenu(_ sender: Any) {
if (menuShowing)
{
    leadingConstraint.constant = -200
    UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
} else {
    leadingConstraint.constant = 0
    UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
}
menuShowing  = !menuShowing
 }
   }
</code>```

Title: Insert cell in tableview in swift

Body:
I'm currently doing an app in swift and doing a menubar that scrolls from the right of the screen and display a list of possibilities.

I created the UITableView on my storyboard as a view that I sticked over the Navigation Controller.

I want now to add cells to this tableview to create a navigation bar, but I don't know how do it since there's no controller managing the item menuView.
Here is my ViewControllerClass:

import CoreData

class ViewController: UIViewController {

@IBOutlet weak var menuView: UITableView!

var menuShowing = false
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    menuView.layer.shadowOpacity = 1
    menuView.layer.shadowRadius = 6

}

@IBAction func openMenu(_ sender: Any) {
    if (menuShowing)
    {
        leadingConstraint.constant = -200
        UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
    } else {
        leadingConstraint.constant = 0
        UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
    }
    menuShowing  = !menuShowing
}
}

My questions are :
Is my menuView object well done or should I reconsider my previous work?

Can I add a cell in the menuView object simply with a simple function like:
    MenuView.addRow( * something *)?

Body:
You can set the UITableViewDataSource and if you want to UITableViewDelegate to ViewController to make the tableView be controlled by ViewController.

import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

 @IBOutlet weak var menuView: UITableView!

var menuShowing = false
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()

menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 6
menuView.dataSource = self
menuView.delegate = self

 }

// Handle TableView like you normally do:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return UITableViewCell()
}

 @IBAction func openMenu(_ sender: Any) {
if (menuShowing)
{
    leadingConstraint.constant = -200
    UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
} else {
    leadingConstraint.constant = 0
    UIView.animate(withDuration:  0.3, animations: {self.view.layoutIfNeeded()})
}
menuShowing  = !menuShowing
 }
   }


问:
Assigning DDnames by the user in jcl
I want to specify the ddname of the file "ABC.DEF.XXX" in which XXX is the input given by the user through sysin in jcl.How it can be achieved?</p>

答:
For completeness, there is a slightly different way to do this that doesn't involve DYNALLOC (SVC 99).

The drawback of DYNALLOC is that your job could wait for resources quite a while, tying up resources (such as a batch initiator) while conflicts are resolved. For example, if the dataset or volume you need aren't immediately available, it's possible to wait indefinitely, depending on how you code your DYNALLOC.

If all you need to do is change the name of a dataset, you can sometimes do it with RDJFCB and OPEN TYPE=J. The JFCB (Job File Control Block) is how z/OS knows about an allocated dataset...the DSN and most of the information from the dataset label are stored in there. The RDJFCB macro gets you access to the JFCB, and then OPEN TYPE=J gives you a way to modify the system-built JFCB - for instance, to change the dataset name to something you compute, rather than what was in the JCL.

A common way to do this is to just have a DD statement with the basic allocation data - it doesn't even need a DSN (the system will cook up a temporary DSN for you if you don't specify one in JCL). Your program uses OPEN TYPE=J to modify the JFCB, changing the dataset name to whatever you like. This is sort of the best of both worlds - you get to do what you want, and the system gets to resolve any resource conflicts before your job even starts.

There are some authorization requirements for OPEN TYPE=J, and it's certainly not for beginners, but if you're interested, it's all documented. Anyone trying this will definitely learn a lot about z/OS in the process!

Title: Assigning DDnames by the user in jcl


问:
How can I format my string in SQL so that it is interpreted properly in Powershell?
I'm currently working on a simple SQL Script that I want to run from SSMS. What the script is supposed to do is take a database, make a backup of it, and then make a .zip file of that backup.

The problem I am running into is when attempting to zip up the backup. I declared all of my variables at the beginning of the file and I believe that when I attempt to execute @sqlcmd the string is not being read by Powershell properly.

```<code>    SET @sqlcmd = ('powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("' + @bkpath + '", "C:\'+ @fileName + '.zip")')
    PRINT @sqlcmd
    -- this statement returns (powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip"))
    EXEC xp_cmdshell @sqlcmd
</code>```

Running this code returns the following output in my results window:

```<code>At line:1 char:47
+ [IO.Compression.ZipFile]::CreateFromDirectory(C:\Backup", C:\Scriptin ...
+                                               ~
Missing ')' in method call.
At line:1 char:56
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
At line:1 char:47
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'C:\Backup", C:\ScriptingTestDB_20170607.zip)' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
NULL
</code>```

After some testing I think I figured out that the problem lies with how Powershell interprets the SQL string. Because of the many quotes It's possible that even though SQL prints out the string correctly, when Powershell gets ahold of it the format gets messed up so something needs to be changed there, but still not sure what. Does anyone know of any guidelines I can use to find out how the SQL code should be written such that Powershell reads the following:

```<code>[IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip")
</code>```

答:
You need to escape "-characters, with \. My working script:

```<code>declare @sqlcmd varchar(1000), @bkpath nvarchar(max) = 'C:\i1\tmp', @filename nvarchar(max) = 'file'

SET @sqlcmd = 'powershell.exe Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::CreateFromDirectory(\"' + @bkpath + '\", \"C:\i1\'+ @fileName + '.zip\")'
EXEC xp_cmdshell @sqlcmd
</code>```

Body:
I'm currently working on a simple SQL Script that I want to run from SSMS. What the script is supposed to do is take a database, make a backup of it, and then make a .zip file of that backup.

The problem I am running into is when attempting to zip up the backup. I declared all of my variables at the beginning of the file and I believe that when I attempt to execute @sqlcmd the string is not being read by Powershell properly.

    SET @sqlcmd = ('powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("' + @bkpath + '", "C:\'+ @fileName + '.zip")')
    PRINT @sqlcmd
    -- this statement returns (powershell.exe [IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip"))
    EXEC xp_cmdshell @sqlcmd

Running this code returns the following output in my results window:

At line:1 char:47
+ [IO.Compression.ZipFile]::CreateFromDirectory(C:\Backup", C:\Scriptin ...
+                                               ~
Missing ')' in method call.
At line:1 char:56
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
At line:1 char:47
+ ... le]::CreateFromDirectory(C:\Backup", C:\ScriptingTestDB_20170607.zip)
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'C:\Backup", C:\ScriptingTestDB_20170607.zip)' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
NULL

After some testing I think I figured out that the problem lies with how Powershell interprets the SQL string. Because of the many quotes It's possible that even though SQL prints out the string correctly, when Powershell gets ahold of it the format gets messed up so something needs to be changed there, but still not sure what. Does anyone know of any guidelines I can use to find out how the SQL code should be written such that Powershell reads the following:

[IO.Compression.ZipFile]::CreateFromDirectory("C:\Backup\", "C:\ScriptingTestDB_20170607.zip")

Body:
You need to escape "-characters, with \. My working script:

declare @sqlcmd varchar(1000), @bkpath nvarchar(max) = 'C:\i1\tmp', @filename nvarchar(max) = 'file'

SET @sqlcmd = 'powershell.exe Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::CreateFromDirectory(\"' + @bkpath + '\", \"C:\i1\'+ @fileName + '.zip\")'
EXEC xp_cmdshell @sqlcmd


问:
How to draw text onto an image in Android
I have looked through countless ways of doing this but still haven't achieved the desired result; what I am trying to achieve is:

Draw a rectangle that is the full width of the screen and about 1/3 of the screen height where the rectangle has 50% visibility / alpha (so the image can be seen slightly underneath the rectangle) and the rectangle would be placed at the very bottom of the screen

Place a multi-line String within the rectangle where the text is centralised to the middle of the rectangle

Above is the basic concept that I am looking to achieve but also, if possible, I would like to generate a map that would be a small square and positioned on the left, within the rectangle - how to add this to a bitmap / canvas would also be really useful.

My current implementation (which doesn't have the correct shape or text size) can be seen below:

```<code>Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
Bitmap newBitmap = ImageUtils.drawMultilineTextToBitmapV2(MainActivity.this, bitmap, imageText);
</code>```

...

```<code>public static Bitmap drawMultilineTextToBitmapV2(Context context, Bitmap bitmap, String text) {

    Bitmap.Config bitmapConfig = bitmap.getConfig();

    if (bitmapConfig == null) {
        bitmapConfig = Bitmap.Config.ARGB_8888;
    }

    Bitmap alteredBitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(alteredBitmap);

    // Add image to canvas
    Paint paint = new Paint();
    canvas.drawBitmap(bitmap, 0, 0, paint);

    // Add background for text
    Paint p2 = new Paint();
    p2.setStyle(Paint.Style.FILL);
    p2.setColor(Color.GRAY);
    p2.setAlpha(0x80);

   // int padding = 50;
    int padding = 1000;
    Rect rect = new Rect(
            canvas.getWidth() - padding, // Left
            canvas.getHeight() - padding, // Top
            padding, // Bottom
            canvas.getWidth() + padding // Right
    );
    canvas.drawRect(rect, p2);

    // Add text
    paint.setColor(Color.WHITE);
    paint.setTextSize(250);
    canvas.drawText(text, bitmap.getWidth(), bitmap.getHeight(), paint);

    canvas.save();
    return alteredBitmap;
}
</code>```

Any help with this would be greatly appreciated.

UPDATE:

```<code>String saveFilePath = FileUtils.saveImageToInternalStorage(newBitmap, fileDirectory, fileName, dateObject);
</code>```

...

The bitmap / canvas gets saved to a file so it can then be accessed again by the user.

```<code>public static String saveImageToInternalStorage(Bitmap finalBitmap, File fileDirectory, String fileName, Date date) {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm", Locale.UK);
    String now = simpleDateFormat.format(date);

    fileDirectory = new File(fileDirectory + DCA_FILE_PATH);
    fileDirectory.mkdirs();

    if (fileName.isEmpty()) {
        DecimalFormat df = new DecimalFormat("000000");
        int i = 1;
        String startingNumber = df.format(i);
        fileName = now + "-" + startingNumber + ".jpg";
    } else {
        fileName = now + "-" + fileName + ".jpg";
    }

    File file = new File(fileDirectory, fileName);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d(TAG, "Saving Internal File to: " + file.getAbsolutePath());
    return file.getAbsolutePath();

}
</code>```

UPDATE 2:

Process of application:

Take photo in-app using camera view

Photo is returned as a byte and converted to Bitmap

Bitmap is converted to a canvas where the text and rectangle needs to be created and then converted back to a Bitmap

Bitmap is then saved as a file

User clicks on file to view photo which would contain the text / rectangle

答:
You can do that by using relative layout (it is possible by frame also),you can set the image view in the layout and add the square or any other layout above it with any position you want.Something like this code in your xml layout:

```<code><RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@drawable/bg_gv_item"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/img_gv_medical_guide_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    />
<TextView
    android:id="@+id/txt_category_title"
    android:layout_gravity="center"
    android:textColor="@color/colorWhite"
    android:background="@drawable/bg_category_title_rounded_rectangle"
    android:gravity="center_horizontal"
    android:layout_centerInParent="true"
    android:textStyle="bold"
    android:textSize="15sp"
    android:text=""
    android:layout_margin="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</code>```

with the drawable bg for your textview, you can control it as you like (1/3) of the screen or whatever you want. Hope this can help you a little bit.

Body:
I have looked through countless ways of doing this but still haven't achieved the desired result; what I am trying to achieve is:

Draw a rectangle that is the full width of the screen and about 1/3 of the screen height where the rectangle has 50% visibility / alpha (so the image can be seen slightly underneath the rectangle) and the rectangle would be placed at the very bottom of the screen

Place a multi-line String within the rectangle where the text is centralised to the middle of the rectangle

Above is the basic concept that I am looking to achieve but also, if possible, I would like to generate a map that would be a small square and positioned on the left, within the rectangle - how to add this to a bitmap / canvas would also be really useful.

My current implementation (which doesn't have the correct shape or text size) can be seen below:

Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
Bitmap newBitmap = ImageUtils.drawMultilineTextToBitmapV2(MainActivity.this, bitmap, imageText);

...

public static Bitmap drawMultilineTextToBitmapV2(Context context, Bitmap bitmap, String text) {

    Bitmap.Config bitmapConfig = bitmap.getConfig();

    if (bitmapConfig == null) {
        bitmapConfig = Bitmap.Config.ARGB_8888;
    }

    Bitmap alteredBitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(alteredBitmap);

    // Add image to canvas
    Paint paint = new Paint();
    canvas.drawBitmap(bitmap, 0, 0, paint);

    // Add background for text
    Paint p2 = new Paint();
    p2.setStyle(Paint.Style.FILL);
    p2.setColor(Color.GRAY);
    p2.setAlpha(0x80);

   // int padding = 50;
    int padding = 1000;
    Rect rect = new Rect(
            canvas.getWidth() - padding, // Left
            canvas.getHeight() - padding, // Top
            padding, // Bottom
            canvas.getWidth() + padding // Right
    );
    canvas.drawRect(rect, p2);

    // Add text
    paint.setColor(Color.WHITE);
    paint.setTextSize(250);
    canvas.drawText(text, bitmap.getWidth(), bitmap.getHeight(), paint);

    canvas.save();
    return alteredBitmap;
}

Any help with this would be greatly appreciated.

UPDATE:

String saveFilePath = FileUtils.saveImageToInternalStorage(newBitmap, fileDirectory, fileName, dateObject);

...

The bitmap / canvas gets saved to a file so it can then be accessed again by the user.

public static String saveImageToInternalStorage(Bitmap finalBitmap, File fileDirectory, String fileName, Date date) {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm", Locale.UK);
    String now = simpleDateFormat.format(date);

    fileDirectory = new File(fileDirectory + DCA_FILE_PATH);
    fileDirectory.mkdirs();

    if (fileName.isEmpty()) {
        DecimalFormat df = new DecimalFormat("000000");
        int i = 1;
        String startingNumber = df.format(i);
        fileName = now + "-" + startingNumber + ".jpg";
    } else {
        fileName = now + "-" + fileName + ".jpg";
    }

    File file = new File(fileDirectory, fileName);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d(TAG, "Saving Internal File to: " + file.getAbsolutePath());
    return file.getAbsolutePath();

}

UPDATE 2:

Process of application:

Take photo in-app using camera view

Photo is returned as a byte and converted to Bitmap

Bitmap is converted to a canvas where the text and rectangle needs to be created and then converted back to a Bitmap

Bitmap is then saved as a file

User clicks on file to view photo which would contain the text / rectangle

Body:
You can do that by using relative layout (it is possible by frame also),you can set the image view in the layout and add the square or any other layout above it with any position you want.Something like this code in your xml layout:

<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@drawable/bg_gv_item"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/img_gv_medical_guide_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    />
<TextView
    android:id="@+id/txt_category_title"
    android:layout_gravity="center"
    android:textColor="@color/colorWhite"
    android:background="@drawable/bg_category_title_rounded_rectangle"
    android:gravity="center_horizontal"
    android:layout_centerInParent="true"
    android:textStyle="bold"
    android:textSize="15sp"
    android:text=""
    android:layout_margin="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

with the drawable bg for your textview, you can control it as you like (1/3) of the screen or whatever you want. Hope this can help you a little bit.


问:
How to create user on firebase from actions.google.com Streamlined Identity Flows
I am in the process of creating a google assistant for a firebase app. In the process, I want to implement the Streamlined Identity Flows and create the users on my firebase application when they provide consent through the flow.

But the catch is, I should be creating the firebase user with

```<code>// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);

// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(err) {...});
</code>```

But for this I would need the id_token which I will not be getting from the assretion flow. All I get from assertion flow is the unique id of the google user.

To get id_token, seems I need to pass in the scopes as openid email profile. Gone through the Openid Connect but couldn't gather whether I should implement this flow in the token endpoint? if so what will be the intents in such flow?

答:
You can use the NodeJS jsonwebtoken library to decode the provided ID token, as documented in the Assertion Flows page, to get the email address and then call

adminSDK.auth().getUserByEmail()

or

createUser()

as appropriate that'll create users for you

Body:
I am in the process of creating a google assistant for a firebase app. In the process, I want to implement the Streamlined Identity Flows and create the users on my firebase application when they provide consent through the flow.

But the catch is, I should be creating the firebase user with

// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);

// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(err) {...});

But for this I would need the id_token which I will not be getting from the assretion flow. All I get from assertion flow is the unique id of the google user.

To get id_token, seems I need to pass in the scopes as openid email profile. Gone through the Openid Connect but couldn't gather whether I should implement this flow in the token endpoint? if so what will be the intents in such flow?


问:
In firefox, how to change color of text in a treecell using javascript
BACKGROUND:
I have the following XUL fragment

```<code><tree id="treeToChange" flex="1">
  <treecols>
    <treecol label = "First Column" id="c1" flex="1"/>
    <treecol label = "Second Column" id="c2" flex="1"/>
  </treecols>
  <treechildren>
    <treeitem>
      <treerow>
        <treecell label="Data for Column 1"/>
        <treecell label="Data for Column 2"/>
      </treerow>
    </treeitem>
  </treechildren>
</tree>
</code>```

and the following css fragment

```<code>tree {  font-size: 120%; color: green;}
</code>```

This causes my column data to be displayed in green text.

I have many such tree objects on the XUL page

QUESTION:
In firefox, in response to a click event, which calls a javascript routine, how do I set the data for the object "treeToChange" in column 1 red and the data in column blue?

答:
To set the colour of any element, you can use:

```<code>function changecolour(elid, nc) {
    document.getElementById(elid).style.color = nc;
}
</code>```

So

```<code>changecolour("c1", "red");
var x = document.getElementsByClassName("cell");
for ( var i = 0; i < x.length; i ++ ) {
    changecolour(x, "blue");
}
</code>```

will change the colour of the data, if you add a cell class to the cells (to avoid conflicting with other trees in the doc)

BTW, here is document.getElementsByClassName:

```<code>function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i=0; i<length; i++){
    current = elements[i];
    if(testClass.test(current.className)){
        returnElements.push(current);
    }
}
return returnElements;
</code>```

}

OwnerDisplayName: Noah

ContentLicense: CC BY-SA 2.5

Body:
BACKGROUND:
I have the following XUL fragment

<tree id="treeToChange" flex="1">
  <treecols>
    <treecol label = "First Column" id="c1" flex="1"/>
    <treecol label = "Second Column" id="c2" flex="1"/>
  </treecols>
  <treechildren>
    <treeitem>
      <treerow>
        <treecell label="Data for Column 1"/>
        <treecell label="Data for Column 2"/>
      </treerow>
    </treeitem>
  </treechildren>
</tree>

and the following css fragment

tree {  font-size: 120%; color: green;}

This causes my column data to be displayed in green text.

I have many such tree objects on the XUL page

QUESTION:
In firefox, in response to a click event, which calls a javascript routine, how do I set the data for the object "treeToChange" in column 1 red and the data in column blue?

LastEditorDisplayName: Noah

Body:
To set the colour of any element, you can use:

function changecolour(elid, nc) {
    document.getElementById(elid).style.color = nc;
}

So

changecolour("c1", "red");
var x = document.getElementsByClassName("cell");
for ( var i = 0; i < x.length; i ++ ) {
    changecolour(x, "blue");
}

will change the colour of the data, if you add a cell class to the cells (to avoid conflicting with other trees in the doc)

BTW, here is document.getElementsByClassName:

function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i=0; i<length; i++){
    current = elements[i];
    if(testClass.test(current.className)){
        returnElements.push(current);
    }
}
return returnElements;

}

OwnerDisplayName: person-b


问:
How to refresh the multiple select box when the model is updated in AngularJs
Please see the following jsfiddle. I put a simple example here to explain what I want to achieve.

https://jsfiddle.net/nz9h6aje/1/

html page:

```<code><div ng-app="testApp" ng-controller="testCtrl">
1- <md-input-container>
<label>Question</label>
<input ng-model="models.Question1">
</md-input-container>
2- <md-input-container>
<label>Question</label>
<input ng-model="models.Question2">
</md-input-container>
<md-select  placeholder="Dependency" ng-model="models.Denpendency" md-on-open="getQuestionSet()" style="min-width: 300px;" multiple>
<md-option ng-value="setQuestion" ng-repeat="setQuestion in setQuestions">{{setQuestion}}</md-option>
</md-select>
</div>
</code>```

js file:

```<code>angular.module('testApp', ['ngAnimate',
'ngAria',
'ngMaterial']).controller('testCtrl',function($scope){
$scope.models={
Question1:"",
Question2:"",
Dependency:[]
}

$scope.getQuestionSet = function() {
  $scope.setQuestions = [];
  var tmpQuestion = 1 + " - " +$scope.models.Question1;
    $scope.setQuestions.push(tmpQuestion);
    tmpQuestion = 2 + " - " +$scope.models.Question2;
    $scope.setQuestions.push(tmpQuestion);
};

 $scope.$watch('models', function (newVal, oldVal) {
  if (newVal.Question1 !== oldVal.Question1) {
        var tmpQuestion = 1 + " - " +$scope.models.Question1;
      $scope.models.Dependency[0] = tmpQuestion;
  }
  if (newVal.Question2 !== oldVal.Question2) {
        var tmpQuestion = 2 + " - " +$scope.models.Question2;
      $scope.models.Dependency[1] = tmpQuestion;
  }
}, true);

});
</code>```

The value of the multiple selected box will change when the question changes. I have a model models.Dependency that stores the selected value of this multiple selected box. When the two questions changes, the selected value stored in the models.Dependency will changed as well. My codes now can change the models.Dependency when the questions changes. But the display of the selected box won't change. What should I do to refresh the multiple selected box to reflect the new data in models.Dependency.

For example, the two questions are 1- Question 1, 2-Question 2. Then when I click the multiple select box, I will see two options: 1-Question 1, 2-Question 2. When I changes the Questions, the options will change as well.
If I selected both of these two Questions, the multiple select box will display as "1-Question 1, 2-Question 2". If I changes the value of Question 1 to "New Question 1". The display of the multiple select remains the same. But if you click it, you will see the options has already been changed. The changed option is not selected. This is not correct. I want the changed option is selected and the display of this multiple select box also changes to "1-New Question 1, 2-Question 2".

I hope I explain my requirement clearly.
Thank you.

答:
Take a look at: https://jsfiddle.net/u2nvj4fs/2/

A few things:

your ng-model for md-select has a typo (Denpendency instead of Dependency)

You are overwriting the whole set list every time you open the dropdown so it's overwriting the items and removing them from the list.

This "more or less" does what you're looking for. It should get you headed in the right direction. I'd be happy to elaborate as needed

Body:
Please see the following jsfiddle. I put a simple example here to explain what I want to achieve.

https://jsfiddle.net/nz9h6aje/1/

html page:

1- <md-input-container>
Question
<input ng-model="models.Question1">
</md-input-container>
2- <md-input-container>
Question
<input ng-model="models.Question2">
</md-input-container>
<md-select  placeholder="Dependency" ng-model="models.Denpendency" md-on-open="getQuestionSet()" style="min-width: 300px;" multiple>
<md-option ng-value="setQuestion" ng-repeat="setQuestion in setQuestions">{{setQuestion}}</md-option>
</md-select>

js file:

angular.module('testApp', ['ngAnimate',
'ngAria',
'ngMaterial']).controller('testCtrl',function($scope){
$scope.models={
Question1:"",
Question2:"",
Dependency:[]
}

$scope.getQuestionSet = function() {
  $scope.setQuestions = [];
  var tmpQuestion = 1 + " - " +$scope.models.Question1;
    $scope.setQuestions.push(tmpQuestion);
    tmpQuestion = 2 + " - " +$scope.models.Question2;
    $scope.setQuestions.push(tmpQuestion);
};

 $scope.$watch('models', function (newVal, oldVal) {
  if (newVal.Question1 !== oldVal.Question1) {
        var tmpQuestion = 1 + " - " +$scope.models.Question1;
      $scope.models.Dependency[0] = tmpQuestion;
  }
  if (newVal.Question2 !== oldVal.Question2) {
        var tmpQuestion = 2 + " - " +$scope.models.Question2;
      $scope.models.Dependency[1] = tmpQuestion;
  }
}, true);

});

The value of the multiple selected box will change when the question changes. I have a model models.Dependency that stores the selected value of this multiple selected box. When the two questions changes, the selected value stored in the models.Dependency will changed as well. My codes now can change the models.Dependency when the questions changes. But the display of the selected box won't change. What should I do to refresh the multiple selected box to reflect the new data in models.Dependency.

For example, the two questions are 1- Question 1, 2-Question 2. Then when I click the multiple select box, I will see two options: 1-Question 1, 2-Question 2. When I changes the Questions, the options will change as well.
If I selected both of these two Questions, the multiple select box will display as "1-Question 1, 2-Question 2". If I changes the value of Question 1 to "New Question 1". The display of the multiple select remains the same. But if you click it, you will see the options has already been changed. The changed option is not selected. This is not correct. I want the changed option is selected and the display of this multiple select box also changes to "1-New Question 1, 2-Question 2".

I hope I explain my requirement clearly.
Thank you.


问:
Load java properties inside static initializer block
I have a static util class that does some string manipulation on a bit sensitive data.
Prior to use of this class I need to initialize certain static variables with values, such as usernames/password, that I prefer to store in a .properties file.

I am not very familiar with how loading of .properties file work in Java, especially outside of *Spring DI *container.
Anyone can give me a hand/insight on how this can be done?

Thank you!

Addition: .properties file precise location is unknown, but it will be on the classpath. Sorta like classpath:/my/folder/name/myproperties.propeties

答:
for me MyClass.class.getClassLoader().getResourceAsStream(..) did the trick:

```<code>private static final Properties properties;

static {
    Properties fallback = new Properties();
    fallback.put(PROP_KEY, FALLBACK_VALUE);

    properties = new Properties(fallback);

    try {
        try (InputStream stream = MyClass.class.getClassLoader().getResourceAsStream("myProperties.properties")) {
            properties.load(stream);
        }
    } catch (IOException ex) {
        // handle error
    }
}
</code>```

Body:
for me MyClass.class.getClassLoader().getResourceAsStream(..) did the trick:

private static final Properties properties;

static {
    Properties fallback = new Properties();
    fallback.put(PROP_KEY, FALLBACK_VALUE);

    properties = new Properties(fallback);

    try {
        try (InputStream stream = MyClass.class.getClassLoader().getResourceAsStream("myProperties.properties")) {
            properties.load(stream);
        }
    } catch (IOException ex) {
        // handle error
    }
}


问:
How to run a function for each row in a nested list?
I'm a Python newbie and trying to write code that checks if a nested list has a valid set of numbers. Each row and each column have to be valid. I have written a function called check_sequence which validates if a list has a valid set of numbers. How would I call that function from another to check to see if the row is valid? So for example, I need something like this for check_rows:

```<code>check_sequence(list):
  checks if list is valid

check_rows(list):
  For each of the rows in the nested list call check_sequence
</code>```

Here is my code for check_sequence:

```<code>def check_sequence(mylist):
    pos = 0
    sequence_counter = 1
    while pos < len(mylist):
        print "The pos is: " + " " + str(pos)
        print "The sequence_counter is:" + " " + str(sequence_counter)
        for number in mylist:
            print "The number is:" + " " + str(number)
            if number == sequence_counter:
                sequence_counter = sequence_counter + 1
                pos = pos + 1
                break
            else:
                # if list is at the last position on the last item
                if sequence_counter not in mylist:
                    print "The pos is:" + " " + str(pos) + " and the last position is:"  + " "  + str(mylist[len(mylist) - 1])
                    print "False"
                    return False
    print "True"
    return True
</code>```

So I'd call the main method like below:

```<code>check_square([[1, 2, 3],
           [2, 3, 1],
           [3, 1, 2]])

def check_square(list):
   if check_rows() and check_columns() == True:
       return True
   else:
       return False
</code>```

答:
Here's a solution that'll work for any arbitrary 2D list.

```<code>l = [[1,2,3],[1,2],[1,4,5,6,7]]
try:
    if len([1 for x in reduce(lambda x, y :x + y, l) if type(x) != type(0)]) > 0:
        raise Exception

catch Exception:
   pass # error, do something
</code>```

The intuition is to flatten the list and then successively check if its type is int.

Body:
I'm a Python newbie and trying to write code that checks if a nested list has a valid set of numbers. Each row and each column have to be valid. I have written a function called check_sequence which validates if a list has a valid set of numbers. How would I call that function from another to check to see if the row is valid? So for example, I need something like this for check_rows:

check_sequence(list):
  checks if list is valid

check_rows(list):
  For each of the rows in the nested list call check_sequence

Here is my code for check_sequence:

def check_sequence(mylist):
    pos = 0
    sequence_counter = 1
    while pos < len(mylist):
        print "The pos is: " + " " + str(pos)
        print "The sequence_counter is:" + " " + str(sequence_counter)
        for number in mylist:
            print "The number is:" + " " + str(number)
            if number == sequence_counter:
                sequence_counter = sequence_counter + 1
                pos = pos + 1
                break
            else:
                # if list is at the last position on the last item
                if sequence_counter not in mylist:
                    print "The pos is:" + " " + str(pos) + " and the last position is:"  + " "  + str(mylist[len(mylist) - 1])
                    print "False"
                    return False
    print "True"
    return True

So I'd call the main method like below:

check_square([[1, 2, 3],
           [2, 3, 1],
           [3, 1, 2]])

def check_square(list):
   if check_rows() and check_columns() == True:
       return True
   else:
       return False

Body:
Here's a solution that'll work for any arbitrary 2D list.

l = [[1,2,3],[1,2],[1,4,5,6,7]]
try:
    if len([1 for x in reduce(lambda x, y :x + y, l) if type(x) != type(0)]) > 0:
        raise Exception

catch Exception:
   pass # error, do something

The intuition is to flatten the list and then successively check if its type is int.


问:
How to does indexing work in assembly 8086?
I'm having problems with my indexing in assembly 8086, I have a procedure in assembly that I call from C and the procedure takes an array of pointers of type long int defined like this long int *arr_ptr[3], code is like this (I consider my SI to be my row pointer and DI to be my column pointer):

```<code>MOV SI,[BP+6]   ;now si points to the first row
MOV DI,[SI]     ;now DI is pointing to the first row
                ; and at the first column column
ADD SI,2        ;here i can move the SI pointer to the next row,
                ; but i want to do this in a loop so i thought
                ; ill define a variable cnt in my data and do this
MOV DI,[SI+cnt]
</code>```

That last line when cnt is 2 is not the same as ADD SI,2 what can I do? I just want to simply loop through my matrix.

答:
First you must pass down the count of rows (assuming that's variable), or terminate the row pointers with a NULL ptr (my preference).  Or build a struct containing all the needed info -- row count, data addr -- and pass its ptr to your processing routine.

Assuming you've NULL terminated the row ptrs, the assembly code might look like this:

```<code>    mov   si,[bp+6]
    jmp short rowloopentry
rowloop:
    << process row data pointed to by di >>
rowloopentry:
    mov   di,[si]                   ;get next row data ptr, and advance index
    add   si,2
    test  di,di                     ;process next row if not at end
    jnz   rowloop
</code>```

Alternatively if the row count is passed as an argument the prototype might become func(long int *arr_ptr[], unsigned rowcnt); and the processing code could loop as follows:

```<code>    mov   cx,[bp+8]
    mov   si,[bp+6]
    test  cx,cx
    jz    zerorows
rowloop:
    mov   di,[si]                   ;get next row data ptr, and advance index
    add   si,2
    << process row data pointed to by di >>
    loop  rowloop                   ;process next row if not at end
zerorows:
</code>```

The above ignores optimizing for a particular processor architecture.

Body:
I'm having problems with my indexing in assembly 8086, I have a procedure in assembly that I call from C and the procedure takes an array of pointers of type long int defined like this long int *arr_ptr[3], code is like this (I consider my SI to be my row pointer and DI to be my column pointer):

MOV SI,[BP+6]   ;now si points to the first row
MOV DI,[SI]     ;now DI is pointing to the first row
                ; and at the first column column
ADD SI,2        ;here i can move the SI pointer to the next row,
                ; but i want to do this in a loop so i thought
                ; ill define a variable cnt in my data and do this
MOV DI,[SI+cnt]

That last line when cnt is 2 is not the same as ADD SI,2 what can I do? I just want to simply loop through my matrix.

Body:
First you must pass down the count of rows (assuming that's variable), or terminate the row pointers with a NULL ptr (my preference).  Or build a struct containing all the needed info -- row count, data addr -- and pass its ptr to your processing routine.

Assuming you've NULL terminated the row ptrs, the assembly code might look like this:

    mov   si,[bp+6]
    jmp short rowloopentry
rowloop:
    << process row data pointed to by di >>
rowloopentry:
    mov   di,[si]                   ;get next row data ptr, and advance index
    add   si,2
    test  di,di                     ;process next row if not at end
    jnz   rowloop

Alternatively if the row count is passed as an argument the prototype might become func(long int *arr_ptr[], unsigned rowcnt); and the processing code could loop as follows:

    mov   cx,[bp+8]
    mov   si,[bp+6]
    test  cx,cx
    jz    zerorows
rowloop:
    mov   di,[si]                   ;get next row data ptr, and advance index
    add   si,2
    << process row data pointed to by di >>
    loop  rowloop                   ;process next row if not at end
zerorows:

The above ignores optimizing for a particular processor architecture.


问:
how to install a python extension for php on windows 8?
I want to know how to install a python extention for php on windows 8 ?

This extension allows the Python interpreter to be embedded inside of PHP, allowing for the instantiate and manipulation of Python objects from within PHP.

I found out that "The easiest way to install the Perforce extension is by using the PECL installer" : (depending on that guide)

```<code>pecl install python
</code>```

I try to run it with my command prompt but I get this error :

'pecl' n'est pas reconnu en tant que commande interne ou externe, un
  programme exécutable ou un fichier de commandes.

I found also a video in YouTube that shows how to Add PECL Extensions to PHP on Windows, but it wasn't useful for me because the package I downloaded has not any file that has an extension .dll

So please help me, what should I do ?

答:
In order to perform this command you're going to need to open up the command line in order to actually be able to have your computer run this. Here is a guide on how to use command line on a windows computer so that you can input the command which they suggested.

https://www.lifewire.com/how-to-open-command-prompt-2618089

Body:
I want to know how to install a python extention for php on windows 8 ?

This extension allows the Python interpreter to be embedded inside of PHP, allowing for the instantiate and manipulation of Python objects from within PHP.

I found out that "The easiest way to install the Perforce extension is by using the PECL installer" : (depending on that guide)

pecl install python

I try to run it with my command prompt but I get this error :

'pecl' n'est pas reconnu en tant que commande interne ou externe, un
  programme exécutable ou un fichier de commandes.

I found also a video in YouTube that shows how to Add PECL Extensions to PHP on Windows, but it wasn't useful for me because the package I downloaded has not any file that has an extension .dll

So please help me, what should I do ?


问:
What does completing function do in Clojure?
I've came across completing function on clojuredocs but there is no doc at the moment.

Could you provide some examples?

答:
completing is used to augment a binary reducing function that may not have a unary overload with a unary "completion" arity.

The official transducers reference page hosted @ clojure.org explains the purpose of the nullary, unary and binary overloads of transducing functions and includes a good example of when the unary "completion" arity is useful in the section called "Creating Transducers" (the example used is partition-all which uses completion to produce the final block of output).

In short, the completion arity is used after all input is consumed and gives the transducing function the opportunity to perform any work to flush any buffers that the transducing process might maintain (as in the case of partition-all), apply any final transformations to the output (see below for an example of that) etc. Here by "transducing function" I mean the transducing function actually passed to transduce (or eduction or any similar function that sets up a transducing process) together with all the wrapping transducers.

For an interesting example of completing used with a non-trivial completion function, have a look at Christophe Grand's xforms: net.cgrand.xforms.rfs/str is a transduce-friendly version of clojure.core/str that will build up a string in linear time when used in a transduce call. (In contrast, clojure.core/str, if used in reduce/transduce, would create a new string at each step, and consequently run in O(n²) time.1) It uses completing to convert the StringBuilder that it uses under to hood to a string once it consumes all input. Here's a stable link to its definition as of the current tip of the master branch.

1 Note, however, that clojure.core/str runs in linear time if used with apply – it uses a StringBuilder under the hood just like net.cgrand.xforms.rfs/str. It's still convenient from time to time to have a transduce-friendly version (for use with transducers, or in higher-order contexts, or possibly for performance reasons when dealing with a large collection that can be reduced be efficiently than via first/next looping that str uses).


问:
3 Nested for loop in macro
I'm trying to list out all the plans in column A, and all the areas for each plan in column B. So it would be plan 1 with area 1 and 2, plan 2 with area 1 and 2, etc. My codes currently list out plan 1, plan 2, etc in column A, but it only lists out area 1 and 2 for plan 1, and it stops there. How do you make it to keep going and list out Area 1 and 2 for the rest of the plans? Thank you :))

So Column A would have plan 1, plan 2, etc in order. And, column B would be area 1, area 2, area 1, area 2, etc

```<code>  'List out all areas for all plans

For Plan = 0 To 5

    'List out all areas within a plan

For Area = 0 To 6

    'List out one Area

    For Row = 2 To 10
        Sheets("S").Cells(Area * 51 + Row, 2) = Sheets("S").Cells(Area + 2, 31)
        Next Row
Next Area
Next Plan
</code>```

(The one on the left in picture is what I have now, and I'm trying to get to the picture on the right. Thanks :))

答:
Given the number of loops you have, it sounds like you would be better off just using a counter for your output row.

```<code>Dim FirstPlan As Long:  FirstPlan = 0
Dim LastPlan As Long:   LastPlan = 5
Dim Plan As Long

Dim FirstArea As Long:  FirstArea = 0
Dim LastArea As Long:   LastArea = 6
Dim Area As Long

Dim FirstRow As Long:   FirstRow = 2
Dim LastRow As Long:    LastRow = 10
Dim myRow As Long    ' Avoid "Row" as a variable name
Dim OutputRow As Long

OutputRow = 2 'Specify first row to be written to

'List out all areas for all plans
For Plan = FirstPlan To LastPlan

    'List out all areas within a plan
    For Area = FirstArea To LastArea

        'List out one Area
        For myRow = FirstRow To LastRow
            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "A").Value = _
                   Sheets("S").Cells(Plan - FirstPlan + 2, "AD").Value

            Sheets("S").Cells(OutputRow, "B").Value = _
                   Sheets("S").Cells(Area - FirstArea + 2, "AE").Value

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "C").Value = _
                   Sheets("S").Cells(myRow - FirstRow + 2, "AF").Value

            'Set up ready for the next row to be written
            OutputRow = OutputRow + 1
        Next
    Next
Next
</code>```

Alternatively OutputRow could be calculated every time it is needed:

```<code>Dim FirstPlan As Long:  FirstPlan = 0
Dim LastPlan As Long:   LastPlan = 5
Dim Plan As Long

Dim FirstArea As Long:  FirstArea = 0
Dim LastArea As Long:   LastArea = 6
Dim Area As Long

Dim FirstRow As Long:   FirstRow = 2
Dim LastRow As Long:    LastRow = 10
Dim myRow As Long    ' Avoid "Row" as a variable name
Dim OutputRow As Long

'List out all areas for all plans
For Plan = FirstPlan To LastPlan

    'List out all areas within a plan
    For Area = FirstArea To LastArea

        'List out one Area
        For myRow = FirstRow To LastRow
            OutputRow = ((Plan - FirstPlan) * (LastArea - FirstArea + 1) + _
                         (Area - FirstArea)) * (LastRow - FirstRow + 1) + _
                         (myRow - FirstRow) + 2

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "A").Value = _
                   Sheets("S").Cells(Plan - FirstPlan + 2, "AD").Value

            Sheets("S").Cells(OutputRow, "B").Value = _
                   Sheets("S").Cells(Area - FirstArea + 2, "AE").Value

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "C").Value = _
                   Sheets("S").Cells(myRow - FirstRow + 2, "AF").Value

        Next
    Next
Next
</code>```

If you are not used to the control flow of loops, try running the following example in an empty worksheet:

```<code>Dim colA As Long, colB As Long, colC As Long
Dim r As Long
With ActiveSheet
    For colA = 11 To 12
        For colB = 21 To 23
            For colC = 31 To 34
                r = r + 1
                .Cells(r, "A").Value = colA
                .Cells(r, "B").Value = colB
                .Cells(r, "C").Value = colC
            Next colC
'The following statement will be executed AFTER processing colC as 34
        Next colB
'The following statement will be executed AFTER processing colB as 23
    Next colA
'The following statement will be executed AFTER processing colA as 12
End With
</code>```

Title: 3 Nested for loop in macro

Body:
I'm trying to list out all the plans in column A, and all the areas for each plan in column B. So it would be plan 1 with area 1 and 2, plan 2 with area 1 and 2, etc. My codes currently list out plan 1, plan 2, etc in column A, but it only lists out area 1 and 2 for plan 1, and it stops there. How do you make it to keep going and list out Area 1 and 2 for the rest of the plans? Thank you :))

So Column A would have plan 1, plan 2, etc in order. And, column B would be area 1, area 2, area 1, area 2, etc

  'List out all areas for all plans

For Plan = 0 To 5

    'List out all areas within a plan

For Area = 0 To 6

    'List out one Area

    For Row = 2 To 10
        Sheets("S").Cells(Area * 51 + Row, 2) = Sheets("S").Cells(Area + 2, 31)
        Next Row
Next Area
Next Plan

(The one on the left in picture is what I have now, and I'm trying to get to the picture on the right. Thanks :))

Body:
Given the number of loops you have, it sounds like you would be better off just using a counter for your output row.

Dim FirstPlan As Long:  FirstPlan = 0
Dim LastPlan As Long:   LastPlan = 5
Dim Plan As Long

Dim FirstArea As Long:  FirstArea = 0
Dim LastArea As Long:   LastArea = 6
Dim Area As Long

Dim FirstRow As Long:   FirstRow = 2
Dim LastRow As Long:    LastRow = 10
Dim myRow As Long    ' Avoid "Row" as a variable name
Dim OutputRow As Long

OutputRow = 2 'Specify first row to be written to

'List out all areas for all plans
For Plan = FirstPlan To LastPlan

    'List out all areas within a plan
    For Area = FirstArea To LastArea

        'List out one Area
        For myRow = FirstRow To LastRow
            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "A").Value = _
                   Sheets("S").Cells(Plan - FirstPlan + 2, "AD").Value

            Sheets("S").Cells(OutputRow, "B").Value = _
                   Sheets("S").Cells(Area - FirstArea + 2, "AE").Value

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "C").Value = _
                   Sheets("S").Cells(myRow - FirstRow + 2, "AF").Value

            'Set up ready for the next row to be written
            OutputRow = OutputRow + 1
        Next
    Next
Next

Alternatively OutputRow could be calculated every time it is needed:

Dim FirstPlan As Long:  FirstPlan = 0
Dim LastPlan As Long:   LastPlan = 5
Dim Plan As Long

Dim FirstArea As Long:  FirstArea = 0
Dim LastArea As Long:   LastArea = 6
Dim Area As Long

Dim FirstRow As Long:   FirstRow = 2
Dim LastRow As Long:    LastRow = 10
Dim myRow As Long    ' Avoid "Row" as a variable name
Dim OutputRow As Long

'List out all areas for all plans
For Plan = FirstPlan To LastPlan

    'List out all areas within a plan
    For Area = FirstArea To LastArea

        'List out one Area
        For myRow = FirstRow To LastRow
            OutputRow = ((Plan - FirstPlan) * (LastArea - FirstArea + 1) + _
                         (Area - FirstArea)) * (LastRow - FirstRow + 1) + _
                         (myRow - FirstRow) + 2

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "A").Value = _
                   Sheets("S").Cells(Plan - FirstPlan + 2, "AD").Value

            Sheets("S").Cells(OutputRow, "B").Value = _
                   Sheets("S").Cells(Area - FirstArea + 2, "AE").Value

            'I'm guessing at this line
            Sheets("S").Cells(OutputRow, "C").Value = _
                   Sheets("S").Cells(myRow - FirstRow + 2, "AF").Value

        Next
    Next
Next

If you are not used to the control flow of loops, try running the following example in an empty worksheet:

Dim colA As Long, colB As Long, colC As Long
Dim r As Long
With ActiveSheet
    For colA = 11 To 12
        For colB = 21 To 23
            For colC = 31 To 34
                r = r + 1
                .Cells(r, "A").Value = colA
                .Cells(r, "B").Value = colB
                .Cells(r, "C").Value = colC
            Next colC
'The following statement will be executed AFTER processing colC as 34
        Next colB
'The following statement will be executed AFTER processing colB as 23
    Next colA
'The following statement will be executed AFTER processing colA as 12
End With


问:
change emacs python-mode interpreter to python3.5
I've tried this and this with no success, in both cases when I C-c C-p I still get python2.7..

答:
The above solution did not work for me. What did work was:

(setq py-shell-name "python3")

According to py-choose-shell in python-mode.el, it chooses the shell via the following methods:

This does the following:

look for an interpreter with `py-choose-shell-by-shebang'

examine imports using `py--choose-shell-by-import'

look if Path/To/File indicates a Python version

if not successful, return default value of `py-shell-name'


问:
How to recode variables in table 1 using info from table 2 (in SAS)

The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

```<code>data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;
</code>```

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

```<code>/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));
</code>```

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

```<code>data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;
</code>```

sample of desired output

答:
No need for all of that code generation. Just use an array.  Basically load the percentiles from the dataset generated by PROC UNIVARIATE into an two dimensional array and then find the decile rank for your actual values.

```<code>%macro stratify(varlist,in=,out=,pcts=pcts);
%local nvars pctls droplist recodes ;
%let varlist=%sysfunc(compbl(&varlist));
%let nvars=%sysfunc(countw(&varlist));
%let pctls=pctl_%sysfunc(tranwrd(&varlist,%str( ),%str( pctl_)));
%let droplist=pctl_%sysfunc(tranwrd(&varlist,%str( ),%str(: pctl_))):;
%let recodes=recode_%sysfunc(tranwrd(&varlist,%str( ),%str( recode_)));

proc univariate data=&in noprint ;
  var &varlist;
  output out=&pcts pctlpre=&pctls
         pctlpts = 10 20 30 40 50 60 70 80 90 100
  ;
run;

data want ;
  if _n_=1 then set &pcts ;
  array _pcts (10,&nvars) _numeric_;
  set test;
  array _in &varlist ;
  array out &recodes ;
  do i=1 to dim(_in);
    do j=1 to 10 while(_in(i) > _pcts(j,i));
    end;
    out(i)=j;
  end;
  drop i j &droplist;
run;
%mend stratify;
</code>```

So if I use your generated sample here is what the log looks like with the MPRINT option turned on.

```<code>1093  %stratify(a b c,in=test,out=want);
MPRINT(STRATIFY):   proc univariate data=test noprint ;
MPRINT(STRATIFY):   var a b c;
MPRINT(STRATIFY):   output out=pcts pctlpre=pctl_a pctl_b pctl_c pctlpts = 10 20 30 40 50
60 70 80 90 100 ;
MPRINT(STRATIFY):   run;

NOTE: The data set WORK.PCTS has 1 observations and 30 variables.
NOTE: PROCEDURE UNIVARIATE used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

MPRINT(STRATIFY):   data want ;
MPRINT(STRATIFY):   if _n_=1 then set pcts ;
MPRINT(STRATIFY):   array _pcts (10,3) _numeric_;
MPRINT(STRATIFY):   set test;
MPRINT(STRATIFY):   array _in a b c ;
MPRINT(STRATIFY):   array out recode_a recode_b recode_c ;
MPRINT(STRATIFY):   do i=1 to dim(_in);
MPRINT(STRATIFY):   do j=1 to 10 while(_in(i) > _pcts(j,i));
MPRINT(STRATIFY):   end;
MPRINT(STRATIFY):   out(i)=j;
MPRINT(STRATIFY):   end;
MPRINT(STRATIFY):   drop i j pctl_a: pctl_b: pctl_c:;
MPRINT(STRATIFY):   run;

NOTE: There were 1 observations read from the data set WORK.PCTS.
NOTE: There were 1000 observations read from the data set WORK.TEST.
NOTE: The data set WORK.WANT has 1000 observations and 6 variables
</code>```

And the first five observations are:

Body:
The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;

sample of desired output

Body:
No need for all of that code generation. Just use an array.  Basically load the percentiles from the dataset generated by PROC UNIVARIATE into an two dimensional array and then find the decile rank for your actual values.

%macro stratify(varlist,in=,out=,pcts=pcts);
%local nvars pctls droplist recodes ;
%let varlist=%sysfunc(compbl(&varlist));
%let nvars=%sysfunc(countw(&varlist));
%let pctls=pctl_%sysfunc(tranwrd(&varlist,%str( ),%str( pctl_)));
%let droplist=pctl_%sysfunc(tranwrd(&varlist,%str( ),%str(: pctl_))):;
%let recodes=recode_%sysfunc(tranwrd(&varlist,%str( ),%str( recode_)));

proc univariate data=&in noprint ;
  var &varlist;
  output out=&pcts pctlpre=&pctls
         pctlpts = 10 20 30 40 50 60 70 80 90 100
  ;
run;

data want ;
  if _n_=1 then set &pcts ;
  array _pcts (10,&nvars) _numeric_;
  set test;
  array _in &varlist ;
  array out &recodes ;
  do i=1 to dim(_in);
    do j=1 to 10 while(_in(i) > _pcts(j,i));
    end;
    out(i)=j;
  end;
  drop i j &droplist;
run;
%mend stratify;

So if I use your generated sample here is what the log looks like with the MPRINT option turned on.

1093  %stratify(a b c,in=test,out=want);
MPRINT(STRATIFY):   proc univariate data=test noprint ;
MPRINT(STRATIFY):   var a b c;
MPRINT(STRATIFY):   output out=pcts pctlpre=pctl_a pctl_b pctl_c pctlpts = 10 20 30 40 50
60 70 80 90 100 ;
MPRINT(STRATIFY):   run;

NOTE: The data set WORK.PCTS has 1 observations and 30 variables.
NOTE: PROCEDURE UNIVARIATE used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

MPRINT(STRATIFY):   data want ;
MPRINT(STRATIFY):   if _n_=1 then set pcts ;
MPRINT(STRATIFY):   array _pcts (10,3) _numeric_;
MPRINT(STRATIFY):   set test;
MPRINT(STRATIFY):   array _in a b c ;
MPRINT(STRATIFY):   array out recode_a recode_b recode_c ;
MPRINT(STRATIFY):   do i=1 to dim(_in);
MPRINT(STRATIFY):   do j=1 to 10 while(_in(i) > _pcts(j,i));
MPRINT(STRATIFY):   end;
MPRINT(STRATIFY):   out(i)=j;
MPRINT(STRATIFY):   end;
MPRINT(STRATIFY):   drop i j pctl_a: pctl_b: pctl_c:;
MPRINT(STRATIFY):   run;

NOTE: There were 1 observations read from the data set WORK.PCTS.
NOTE: There were 1000 observations read from the data set WORK.TEST.
NOTE: The data set WORK.WANT has 1000 observations and 6 variables

And the first five observations are:


问:
How can I join these two select statements?
First statement

```<code>SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6
</code>```

Second statement

```<code>SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6
</code>```

答:
I don't know for sure if this is what you're looking for, but you can UNION them.</p>

```<code>(SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6)
UNION
(SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6)
</code>```

Body:
First statement

SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6

Second statement

SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6

Body:
I don't know for sure if this is what you're looking for, but you can UNION them.

(SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6)
UNION
(SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6)