text:
Q: conditional counting within/sum across and transformations Update at 2012-09-24 06:52:00Z
After David Robinson asked some really good questions I realized that my initial question wasn't accurate.
I'm thinking about my problem as a two step thing,
First I need to look thru my data to identify ids who only have the time intake_arm_1 and create a new row with only their # in id, v_001_arm_1 in time, and their # in c_n. To get the right match between their t_name and c_name I use the lookup table.
Second, I need to perform more or less the same precede within id on the 'v_001_arm_1' though v_010_arm_1 if latest arm have any ti_all registered, count these instances by ty_all, and write those number to the columns out_c and out_c. Furthermore, I also have to transport the name number from intake_arm_1 to this new row, again if the latest ti_all is not NA.
The # of the new v_00n_arm_1 should be "the current highlight number" (e.g. v_007_arm_1) + 1 (e.g. v_008_arm_1).
I will work on manually making a compel example of what I am aiming for.
lookup <- structure(list(c_name = c(1L, 2L, 4L, 5L, 6L, 7L), t_name = structure(1:6, .Label = c("Bob", "Julian", "Mitt", "Ricky", "Tom", "Victor"), class = "factor")), .Names = c("c_name", "t_name"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))
> lookup
  c_name t_name
1      1    Bob
2      2 Julian
3      4   Mitt
4      5  Ricky
5      6    Tom
6      7 Victor

mydata <- structure(list(id = c(1L, 1L, 2L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 6L, 7L, 7L, 7L, 7L, 8L, 9L), time = c("intake_arm_1", "v_001_arm_1", "intake_arm_1", "intake_arm_1", "intake_arm_1", "v_001_arm_1", "v_002_arm_1", "v_003_arm_1", "v_004_arm_1", "v_005_arm_1", "v_006_arm_1", "v_007_arm_1", "intake_arm_1", "v_001_arm_1", "intake_arm_1", "intake_arm_1", "v_011_arm_1", "v_012_arm_1", "v_013_arm_1", "intake_arm_1", "intake_arm_1"), dat_all = c(NA, NA, NA, NA, NA, NA, NA, "2012-09-23", "2012-09-23", "2012-09-02", "2012-09-10", "2012-09-23", NA, NA, NA, NA, "2012-09-23", "2012-09-23", "2012-09-23", NA, NA), ti_all = c(NA, NA, NA, NA, NA, NA, NA, 6L, 44L, 33L, NA, 22L, NA, NA, NA, NA, 65L, NA, 10L, NA, NA),     ty_all = c(NA, NA, NA, NA, NA, NA, NA, "out_", "out_", "cma_",     NA, "cma_", NA, NA, NA, NA, "out_", "out_", "out_", NA, NA), out_c = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,     NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), cma_c = c(NA, NA,     NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,     NA, NA, NA, NA), c_n = c(NA, 1L, NA, NA, NA, NA, NA, 7L,     4L, 7L, NA, 1L, NA, 2L, NA, NA, 7L, 7L, 7L, NA, NA), t_name = c("Tom",     NA, "Ricky", "Ricky", "Victor", NA, NA, NA, NA, NA, NA, NA,     "Julian", NA, "Julian", "Bob", NA, NA, NA, "Mitt", "Mitt")), .Names = c("id", "time", "dat_all", "ti_all", "ty_all", "out_c", "cma_c", "c_n", "t_name"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21"))
> mydata
     id          time    dat_all ti_all ty_all out_c cma_c  c_n  t_name
1     1  intake_arm_1         NA     NA     NA    NA    NA   NA     Tom
2     1   v_001_arm_1         NA     NA     NA    NA    NA    1      NA
3     2  intake_arm_1         NA     NA     NA    NA    NA   NA   Ricky
4     3  intake_arm_1         NA     NA     NA    NA    NA   NA   Ricky
5     4  intake_arm_1         NA     NA     NA    NA    NA   NA  Victor
6     4   v_001_arm_1         NA     NA     NA    NA    NA   NA      NA
7     4   v_002_arm_1         NA     NA     NA    NA    NA   NA      NA
8     4   v_003_arm_1 2012-09-23      6   out_    NA    NA    7      NA
9     4   v_004_arm_1 2012-09-23     44   out_    NA    NA    4      NA
10    4   v_005_arm_1 2012-09-02     33   cma_    NA    NA    7      NA
11    4   v_006_arm_1 2012-09-10     NA     NA    NA    NA   NA      NA
12    4   v_007_arm_1 2012-09-23     22   cma_    NA    NA    1      NA
13    5  intake_arm_1         NA     NA     NA    NA    NA   NA  Julian
14    5   v_001_arm_1         NA     NA     NA    NA    NA    2      NA
15    6  intake_arm_1         NA     NA     NA    NA    NA   NA  Julian
16    7  intake_arm_1         NA     NA     NA    NA    NA   NA     Bob
17    7   v_011_arm_1 2012-09-23     65   out_    NA    NA    7      NA
18    7   v_012_arm_1 2012-09-23     NA   out_    NA    NA    7      NA
19    7   v_013_arm_1 2012-09-23     10   out_    NA    NA    7      NA
20    8  intake_arm_1         NA     NA     NA    NA    NA   NA    Mitt
21    9  intake_arm_1         NA     NA     NA    NA    NA   NA    Mitt

This is what I am aiming at (unless I have made a typo),
    id          time    dat_all ti_all ty_all out_c cma_c  c_n  t_name
1    1  intake_arm_1         NA     NA     NA    NA    NA   NA     Tom
2    1   v_001_arm_1         NA     NA     NA    NA    NA    1      NA
3    2  intake_arm_1         NA     NA     NA    NA    NA   NA   Ricky
4    2   v_001_arm_1         NA     NA     NA    NA    NA    5      NA
5    3  intake_arm_1         NA     NA     NA    NA    NA   NA   Ricky
6    3   v_001_arm_1         NA     NA     NA    NA    NA    5      NA
7    4  intake_arm_1         NA     NA     NA    NA    NA   NA  Victor
7    4   v_001_arm_1         NA     NA     NA    NA    NA   NA      NA
8    4   v_002_arm_1         NA     NA     NA    NA    NA   NA      NA
9    4   v_003_arm_1 2012-09-23      6   out_     1    NA    7      NA
10   4   v_004_arm_1 2012-09-23     44   out_     2    NA    4      NA
11   4   v_005_arm_1 2012-09-02     33   cma_     2     1    7      NA
12   4   v_006_arm_1 2012-09-10     NA     NA     2     1   NA      NA
13   4   v_007_arm_1 2012-09-23     22   cma_     2     2    1      NA
14   4   v_008_arm_1         NA     NA     NA     2     2    7      NA
15   5  intake_arm_1         NA     NA     NA    NA    NA   NA  Julian
16   5   v_001_arm_1         NA     NA     NA    NA    NA    2      NA
17   6  intake_arm_1         NA     NA     NA    NA    NA   NA  Julian
18   6   v_001_arm_1         NA     NA     NA    NA    NA    2      NA
19   7  intake_arm_1         NA     NA     NA    NA    NA   NA     Bob
20   7   v_011_arm_1 2012-09-23     65   out_     1    NA    7      NA
21   7   v_012_arm_1 2012-09-23     NA   out_     1    NA    7      NA
22   7   v_013_arm_1 2012-09-23     10   out_     2    NA    7      NA
23   7   v_014_arm_1         NA     NA     NA     2    NA    1      NA
24   8  intake_arm_1         NA     NA     NA    NA    NA   NA    Mitt
25   8   v_001_arm_1         NA     NA     NA    NA    NA    4      NA
26   9  intake_arm_1         NA     NA     NA    NA    NA   NA    Mitt
27   9   v_001_arm_1         NA     NA     NA    NA    NA    4      NA

ps: I've seen people do amazing things with aggregate and tapply.

A: Here's a solution using plyr:
lookup <- structure(list(c_name = c(1L, 2L, 4L, 5L, 6L, 7L), t_name = structure(1:6, .Label = c("Bob", "Julian", "Mitt", "Ricky", "Tom", "Victor"), class = "factor")), .Names = c("c_name", "t_name"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

mydata <- structure(list(id = c(1L, 1L, 2L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 6L, 7L, 7L, 7L, 7L, 8L, 9L), time = c("intake_arm_1", "v_001_arm_1", "intake_arm_1", "intake_arm_1", "intake_arm_1", "v_001_arm_1", "v_002_arm_1", "v_003_arm_1", "v_004_arm_1", "v_005_arm_1", "v_006_arm_1", "v_007_arm_1", "intake_arm_1", "v_001_arm_1", "intake_arm_1", "intake_arm_1", "v_011_arm_1", "v_012_arm_1", "v_013_arm_1", "intake_arm_1", "intake_arm_1"), dat_all = c(NA, NA, NA, NA, NA, NA, NA, "2012-09-23", "2012-09-23", "2012-09-02", "2012-09-10", "2012-09-23", NA, NA, NA, NA, "2012-09-23", "2012-09-23", "2012-09-23", NA, NA), ti_all = c(NA, NA, NA, NA, NA, NA, NA, 6L, 44L, 33L, NA, 22L, NA, NA, NA, NA, 65L, NA, 10L, NA, NA),     ty_all = c(NA, NA, NA, NA, NA, NA, NA, "out_", "out_", "cma_",     NA, "cma_", NA, NA, NA, NA, "out_", "out_", "out_", NA, NA), out_c = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,     NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), cma_c = c(NA, NA,     NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,     NA, NA, NA, NA), c_n = c(NA, 1L, NA, NA, NA, NA, NA, 7L,     4L, 7L, NA, 1L, NA, 2L, NA, NA, 7L, 7L, 7L, NA, NA), t_name = c("Tom",     NA, "Ricky", "Ricky", "Victor", NA, NA, NA, NA, NA, NA, NA,     "Julian", NA, "Julian", "Bob", NA, NA, NA, "Mitt", "Mitt")), .Names = c("id", "time", "dat_all", "ti_all", "ty_all", "out_c", "cma_c", "c_n", "t_name"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21"))

library(plyr)

newrows <- ddply(mydata, .(id), function(subdata) {
    subdata_ty = subdata[!is.na(subdata$ty_all), ]
    if (NROW(subdata) == 1) {
        r = subdata[1, ]
        c("v_001_arm_1", NA, NA, NA, NA, NA,
                    lookup$c_name[lookup$t_name == r$t_name], r$t_name)
    }
    else if (NROW(subdata_ty) > 0 & !is.na(subdata_ty[NROW(subdata_ty), ]$dat_all)) {
        numbers = sapply(strsplit(subdata$time, "_"), function(l)
            ifelse(l[1] != "intake", as.numeric(l[2]), 0))
        newname = paste(c("v", sprintf("%03d", max(numbers) + 1), "arm", "1"),
                            collapse="_")
        r1 = subdata[1, ]
        new_c_n = lookup$c_name[lookup$t_name == r1$t_name]

        new_out_c = sum(subdata$ty_all == "out_" & !is.na(subdata$ti_all))
        new_cma_c = sum(subdata$ty_all == "cma_" & !is.na(subdata$ti_all))

        # you want them to be NA instead of 0:
        new_out_c = ifelse(new_out_c == 0, NA, new_out_c)
        new_cma_c = ifelse(new_cma_c == 0, NA, new_cma_c)

        return(c(newname, NA, NA, NA, new_out_c, new_cma_c, new_c_n, NA))
    }
})

# recombine and sort
colnames(newrows) = colnames(mydata)
newdata = rbind(mydata, newrows)
newdata = newdata[order(newdata$id), ]


text:
Q: Pandas GroupBy by Multiple Period But Maintaining Copies of other LEts say that I have this dataset where if I use .size on it, it would present like this:
date                       created_at
2020-04                     2020-04       1
                            2020-05       1
                            2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-05                     2020-05       1
                            2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
2020-06                     2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-07                     2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-08                     2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-09                     2020-09       1
                            2020-10       1
                            2020-11       1
2020-10                     2020-10       1
                            2020-11       1
2020-11                     2020-11       1

When i use groupby with date and created_at it would look like that so im not able to achieve my goal where I want to aggregate values in all pairs of date and created_at so I want the order to not cut off their pairs when grouping by so somthing like this:
date                       created_at
2020-04                     2020-04       1
                            2020-05       1
                            2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-05                     2020-04       1
                            2020-05       1
                            2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
2020-06                     2020-04       1
                            2020-05       1
                            2020-06       1
                            2020-07       1
                            2020-08       1
                            2020-09       1
                            2020-10       1
                            2020-11       1
... and so on maintaining copies of all

Basically I want to group my dataframe like this before aggregation, I Already tried all types of joins groupby and sorts but I cant seem to achieve it, how does one do this in pandas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download XML file with Asp.Net MVC I've created an ActionResult in an MVC controller which returns a FileStreamResult of an XMLfile, but it's not downloading the file.
After the action returns the FileStream nothing happens; I'd like to make the user download the file from the web application.
Any help?
Thanks
public ActionResult EsportaProtocollo(int idProtocollo)
{
    AvvisoModel avviso = new AvvisoModel();

    string xml = _protocolliService.ProtocolloToXml(idProtocollo);

    var newStream = new System.IO.MemoryStream();
    var writer = new System.IO.StreamWriter(newStream);
    writer.Write(xml);
    writer.Flush();
    newStream.Position = 0;

    return File(newStream, "application/xml", "prova.xml");

}

Here's what I see on Fiddler

A: Solved! the problem was the javascript, i was calling the action with an ajax call, i've changed it to a window.open(url); and now it works!


text:
Q: Add custom js scripts to my components in Angular 2 My application consumes an API on a server I have set up.
For my front end, I am using Angular 2.
I would like to use custom js and jquery scripts to implement some of the features to make front-end appealing.
The css stylesheets are added through the styleUrls property in the component decorator.
How do I reference JS files to be able to incorporate libraries like WOW js and Jquery?

A: Install your libraries via npm install and add the files you need in angular-cli.json
https://github.com/angular/angular-cli#global-library-installation


text:
Q: express percent as a percentage of the total volume rather than ranked volume Given this query:
select      [Code],
            [EffectiveDate],
            [Volume] = Sum(Volume),
            [VolumeRank] = RANK() OVER (PARTITION BY EffectiveDate ORDER BY SUM(Volume) DESC),
            [VolumePercent] = PERCENT_RANK() OVER (PARTITION BY EffectiveDate ORDER BY SUM(Volume) ASC)
from        CodeTable
where       EffectiveDate between @start and @end
group by    DerivativeType, MemberCode, EffectiveDate

Which produces these results
X   2014-05-02 00:00:00.000 15683.00    1   1
X   2014-05-05 00:00:00.000 10524.00    1   1
Y   2014-05-05 00:00:00.000 8318.00     2   0.99236641221374
Y   2014-05-02 00:00:00.000 8264.00     2   0.991935483870968

The volume percent is calculating the ranked percentage, which makes sense!
I want to use a similar function to return the percentage volume of the total volume partitioned over the date, rather than a ranked percentage.
I am not seeing the wood for the trees...
Any ideas?

A: Then you want to use a window function to calculate the total volume.  I think the logic is:
select sum(volume) / sum(sum(volume)) over (partition by EffectiveDate)

If volume is an integer, you should convert it to a non-integer number.  Otherwise, the division will return an integer -- and be either 0 or 1.  I often do this by multiplying by 1.0:
select sum(volume*1.0) / sum(sum(volume)) over (partition by EffectiveDate)

The construct sum(sum(volume)) looks strange the first time you see it.  The inner sum() is for the group by.  The outer sum() is for the window function -- to get the total after the aggregation.


text:
Q: PHP & HTML: Create PDF from HTML table/page and then send it as an attachment I am trying to either copy a HTML page with a table made by jQuery and then create a PDF from that page. Or, I have also tried creating a PDF from a HTML page using FPDF but with no success.
What I am trying to do is to have my code create / make a PDF from the html page with the table and its contents in it (Note below that $txt is the table we suppose to bring over).  Once the PDF has been made, then send the PDF to the office email, and then to the client's emails with an HTML summary of the previous form they chose.
I have tried to create a message to PDF and then send as attachment, but the system will not send as attachment.  Nothing shows up and the HTML email is also wrecked.   I have also tried using FPDF and the writeHTML(), and I can then create the PDF but it doesn't show the table and doesn't send the PDF as attachment to the email.
I have tried multiple things, but cannot seem to get it to work. Is there a way to do this without using FPDF?  Is there a better way to create the PDF from html page and then just send it as an attachment?
Sample code of what I have been doing is below:
    <?php
    // download fpdf class (http://fpdf.org)
    require ("FPDF/fpdf.php");
    require ("WriteHTML.php");
    $pdf=new PDF_HTML();
    //$pdf-->AliasNbPages();
    $pdf->SetAutoPageBreak(true, 15);

    // fpdf object
    $pdf->AddPage();

    $pdf->SetFont('Arial','B',14);
    $pdf->WriteHTML('

Vanguard Appraisals Price Estimate

    ');

    $pdf->SetFont('Arial','B',7);

    $htmlTable='

                Contact Information

                Sales:

                '.$Sales.'

                Sales E-Mail:

                '.$from.'

                client Name:

                '.$client.'

                Company, State:

                '.$Company.', '.$state.'

                client Phone:

                '.$client_phone.'

                client E-mail:

                '.$email_from.'

                '.$txt.'

    ';

    $pdf->WriteHTML("

    $htmlTable

* Prices below are only an estimated price and is in no way an official cost from Vanguard Appraisals, Inc.

".$txt."

For an official price quote, or to get a quote on hardware items, please contact Vanguard Appraisals home office at (319)365-8625 or by e-mail at info@camavision.com.
");

    $pdf->SetFont('Arial','B',6);
    $pdf->Output();

    ?>

                            <?php

                                if(isset($_POST['send'])) {
                                    $to = "email@someemail.com";
                                    $txt = $_POST['data'];

                                    $filename = "Price_Estimate.pdf";
                                    $pdf->Output('Price_Estimate.pdf','D');
                                    $attachment = chunk_split(base64_encode($fileatt));
                                    $eol = PHP_EOL;
                                    $boundary = md5(time());

                                    function died($error) {
                                        // your error code can go here
                                        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
                                        echo "These errors appear below.

";
                                        echo $error."

";
                                        echo "Please go back and fix these errors.

";
                                        die();
                                    }
                                    // validation expected data exists
                                    if(!isset($_POST['Company']) ||
                                        !isset($_POST['state']) ||
                                        !isset($_POST['sales_rep']) ||
                                        !isset($_POST['email']) ||
                                        !isset($_POST['client']) ||
                                        !isset($_POST['client_email']) ||
                                        !isset($_POST['client_phone'])) {
                                        died('We are sorry, but there appears to be a problem with the form you submitted.');

                                    }
                                    $Company = $_POST['Company']; // required
                                    $state = $_POST['state']; // required
                                    $Sales = $_POST['sales_rep']; // required
                                    $from = $_POST['email']; // required
                                    $client = $_POST['client']; // required
                                    $client_email = $_POST['client_email']; // not required
                                    $client_phone = $_POST['client_phone']; // not required
                                    $date = date("F j, Y");

                                    $error_message = "";
                                    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
                                    if(!preg_match($email_exp,$from)) {
                                        $error_message .= 'The Email Address you entered does not appear to be valid.
';
                                    }
                                        $string_exp = "/^[A-Za-z .'-]+$/";
                                    if(!preg_match($string_exp,$Company)) {
                                        $error_message .= 'The Company you entered does not appear to be valid.
';
                                    }
                                    if(!preg_match($string_exp,$Sales)) {
                                        $error_message .= 'The Company you entered does not appear to be valid.
';
                                    }
                                    if(!preg_match($string_exp,$client)) {
                                        $error_message .= 'The Company you entered does not appear to be valid.
';
                                    }

                                    if(strlen($error_message) > 0) {
                                        died($error_message);
                                    }
                                        $email_message = "Form details below.\n\n";
                                    function clean_string($string) {
                                      $bad = array("content-type","bcc:","to:","cc:","href");
                                      return str_replace($bad,"",$string);
                                    }
                                    $subject = "Price Quote Submission";;
                                    $subject2 = "Sales Copy of Price Quote Submission";

                                    //Web Copy
                                    $web_message .=  "

 ";
                                            $web_message .= "Contact Information	";
                                        $web_message .= "

";
                                                $web_message .= "Representative:	";
                                                $web_message .= "".clean_string($representative)."	";
                                                $web_message .= "Rep's E-Mail:	";
                                                $web_message .= "".clean_string($from)."	";
                                            $web_message .= "

";
                                                $web_message .= "client's Name:	";
                                                $web_message .= "".clean_string($client)."	";
                                                $web_message .= "company, State:	";
                                                $web_message .= "".clean_string($company).", ".clean_string($state)."	";
                                            $web_message .= "

";
                                                $web_message .= "Assessor's Phone:	";
                                                $web_message .= "".clean_string($client_phone)."	";
                                                $web_message .= "client's E-mail:	";
                                                $web_message .= "".clean_string($email_from)."	";
                                            $web_message .= "
";
                                    $web_message .= "

";
                                    $web_message .= "
* Prices below are only an estimated price and is in no way an official cost .

".$txt."
";

                                        $web_message .= "
For an official price quote, or to get a quote on hardware items, please contact home office.
";

                                    //Office Copy
                                    $message .= "";
                                    $message .= "
Some Company
";
                                    $message .=  "

 ";
                                        $message .= "";
                                            $message .= "

";
                                                $message .= "	";
                                                $message .= "Address
City, State, Zip Code
Telephone | Fax 	";
                                            $message .= "

";
                                        $message .= "	";
                                    $message .= "

";
                                        $message .= "
Price Estimate
	";
                                    $message .= "

";
                                        $message .= "The following price quote was submitted on ".$date." from ".clean_string($sales).".	";
                                    $message .= "

";
                                        $message .= "
";
                                            $message .= "

";
                                                $message .= "sales:	";
                                                $message .= "".clean_string($sales)."	";
                                                $message .= "Rep's E-Mail:	";
                                                $message .= "".clean_string($from)."	";
                                            $message .= "

";
                                                $message .= "client's Name:	";
                                                $message .= "".clean_string($client)."	";
                                                $message .= "company, State:	";
                                                $message .= "".clean_string($company).", ".clean_string($state)."	";
                                            $message .= "

";
                                                $message .= "client's Phone:	";
                                                $message .= "".clean_string($client_phone)."	";
                                                $message .= "client's E-mail:	";
                                                $message .= "".clean_string($email_from)."	";

                                            $message .= "

";
                                        $message .= "	";

                                    $message .= "

";
                                        $message .= "* Prices below are only an estimated price and is in no way an official cost from Vanguard Appraisals, Inc.
".$txt."	";
                                    $message .= "

";
                                        $message .= " 	";
                                    $message .= "

";
                                        $message .= "* Please do not reply back to this E-Mail	 ";
                                    $message .= "

";

                                    //sales Copy
                                    $message2 .= "";
                                    $message2 .= "
Price Estimat
";
                                    $message2 .=  "

 ";
                                        $message2 .= "";
                                            $message2 .= "

";
                                                $message2 .= "	";
                                                $message2 .= "Address
City, State Zip
Telephone | Fax	";
                                            $message2 .= "

";
                                        $message2 .= "	";
                                    $message2 .= "

";
                                        $message2 .= "
Price Estimate
	";
                                    $message2 .= "

";
                                        $message2 .= "
".$date."
Thank you for submitting the following price quote on ".$date.". It has been successfully submited to the home office. You can see the items selected and an estimated cost below. Please remember that this is just an estimated cost and it is in no way an official cost . Please contact the home office .

	";
                                    $message2 .= "

";
                                        $message2 .= "
";
                                            $message2 .= "

";
                                                $message2 .= "client's Name:	";
                                                $message2 .= "".clean_string($client)."	";
                                                $message2 .= "company, State:	";
                                                $message2 .= "".clean_string($company).", ".clean_string($state)."	";
                                            $message2 .= "

";
                                                $message2 .= "client's Phone:	";
                                                $message2 .= "".clean_string($client_phone)."	";
                                                $message2 .= "client's E-mail:	";
                                                $message2 .= "".clean_string($email_from)."	";

                                            $message2 .= "

";
                                        $message2 .= "	";
                                    $message2 .= "

";
                                        $message2 .= "* Prices below are only an estimated price and is in no way an official cost.
".$txt."	";
                                    $message2 .= "

";
                                        $message2 .= "For an official price quote, or to receive a quote on hardware items, please contact home office .	";
                                    $message2 .= "

";
                                        $message2 .= " 	";
                                    $message2 .= "

";
                                        $message2 .= "* Please do not reply back to this E-Mail	 ";
                                    $message2 .= "

";

                                    // main header (multipart mandatory)
                                    $headers  = "From: ".clean_string($from);
                                    $headers .= "MIME-Version: 1.0";
                                    $headers .= "Content-Type: multipart/mixed;boundary=\"" . $boundary . "\"\r\n";

                                    // attachment
                                    $output = "--".$boundary."\r\n";
                                    $output .= "Content-Type: text/pdf; name=\"Price_Estimate.pdf\";\r\n";
                                    $output .= "Content-Disposition: attachment;\r\n\r\n";
                                    $output .= $attachment."\r\n\r\n";
                                    $output .= "--".$boundary."\r\n";
                                     $output .= "Content-type: text/html; charset=\"utf-8\"\r\n";
                                    $output .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
                                    $output .= $message."\r\n\r\n";
                                    $output .= "--".$boundary."--\r\n\r\n";

                                    // create sales email headers
                                    $headers2 = "From: ".$to. "\r\n";
                                    $headers2 .= "MIME-Version: 1.0\r\n";
                                    $headers2 .= "Content-Type: text/html; charset=UTF-8\r\n";
                                    $headers2 .= "Content-Transfer-Encoding: 8bit";
                                    $headers2 .= $message.$eol.$eol;

                                    mail($to,$subject,$output,$headers);
                                    mail($from,$subject2,$message2,$headers2);

                                    if(mail($to,$subject,$output,$headers))
                                       {
                                         echo "
Thank you for submitting the following price quote on ".$date.". It has been successfully submited to the home office. You can see the items selected and an estimated cost below. Please remember that this is just an estimated cost and it is in no way an official cost from Vanguard Appraisals, Inc. Please contact the home office .
";
                                       }
                                       else
                                       {
                                         echo "
We are very sorry, but there were error(s) found with the price quote you submitted. Please return back to the price quote page and try re-submitting the form again.  Any questions or to receive an official estimate by phone, please contact the home office.  Thank you.
";
                                       }
                            ?>

                            <?php echo $web_message ?>

                            <?php

                            }

                            ?>

A: Try this .. it opens a new window which contains your html data and pdf printing option.
var content = "
html content</div";
win = window.open();
self.focus();
win.document.open();
win.document.write(content);
win.document.close();
win.focus();
win.print();


text:
Q: Compiling LibSSH2 with specific LibSSL I have downloaded and compiled the latest version of libssl, the result of which is located at /usr/local/ssl. I want to compile libssh2 using the files in this folder, and to do that I've set the switch --with-libssl-prefix=/usr/local/ssl.
After performing ./configure --with-libssl-prefix=/usr/local/ssl and make, the resulting libssh2.so, according to the output of ldd, depends on the libssl found in the /usr/lib64, which is exactly what I don't want.
What can I do to force libssh2 to be compiled with the libssl I have in /usr/local/ssl?

A: If you compiled and installed libssl into the default /usr/local path, there is a /usr/local/ssl, but the lib is not in there; it's just directories like certs and misc -- stuff that other things would probably put in a share directory (e.g. /usr/local/share/ssl).
The actual library is installed in a normal place, /usr/local/lib.  Presuming you've already run ldconfig and that path is in a file in /etc/ld.so.conf.d, you should be able to then do:
ldconfig -p | grep ssl

And all the => paths should be into /usr/local/lib.   If so, you can use:
--with-libssl-prefix=/usr/local/

No ssl or lib, etc.  It should now be found properly.


text:
Q: Observable if the array element is changed How I can write this code with a single line?
public class RadGridColumnObservable
{
    public RadGridColumnObservable(RadGridView grid, IMessageBus messageBus)
    {
        this.grid = grid;
        this.messageBus = messageBus;
    }

    public IDisposable Initialize()
    {
        CreateStates();

        return Observable
            .Interval(TimeSpan.FromSeconds(1))
            .Subscribe(_ => CheckUp());
    }

    //

    private readonly RadGridView grid;
    private readonly IMessageBus messageBus;
    private readonly List<bool> states = new List<bool>();

    //

    private void CreateStates()
    {
        states.Clear();
        states.AddRange(grid.Columns.Select(it => it.IsVisible));
    }

    private void CheckUp()
    {
        if (states.SequenceEqual(grid.Columns.Select(it => it.IsVisible))) return;

        CreateStates();
        messageBus.Publish(new NotifyMessage(MessageTypes.HistoryColumnsChanged));
    }
}

The idea is: I want to check if the IsVisible property is changed.
I don't like to use this line:
private readonly List<bool> states = new List<bool>();

A: You could get your IsVisible values with something like this:
private IObservable<List<bool>> CreateStatesObservable()
{
    return Observable.Interval(TimeSpan.FromSeconds(1))
                        .Select(_ => grid.Columns.Select(it => it.IsVisible));
}

And then use Scan to keep track of your previous value:
public void Initialize()
{
    var observable =
            CreateStatesObservable()
                        .Scan(
                            (prev: default(List<bool>), actual: default(List<bool>)),
                            (acc, c) => (acc.actual, current))
                        .Where(values => !values.actual.SequenceEqual(values.prev))
                        .Select(_ => true);
}

Or you could use Defer and do something like this:
public void Initialize2()
{
    var observable = CreateStatesObservable();

    var deferred =
        Observable.Defer(
                      () =>
                      {
                          List<bool> previous = null;

                          return observable.Select(
                              values =>
                              {
                                  if (previous is null)
                                  {
                                      previous = values;
                                      return false;
                                  }

                                  if (!values.SequenceEqual(previous))
                                  {
                                      previous = values;
                                      return true;
                                  }

                                  return false;
                              });
                      })
                  .Where(value => value);
}

Both options should give you an observable which only produces a value when one of the columns IsVisible has changed. (That value just being a true)
Edit:
You can also use DistinctUntilChanged() with your own IEqualityComparer like this:
class ListComparer : IEqualityComparer<List<bool>>
{
    bool IEqualityComparer<List<bool>>.Equals(List<bool>? a, List<bool>? b)
    {
        if (a is null && b is null)
        {
            return true;
        }

        if (a is null || b is null)
        {
            return false;
        }

        return a.SequenceEqual(b);
    }

    int IEqualityComparer<List<bool>>.GetHashCode(List<bool> obj)
    {
        return obj.GetHashCode();
    }
}

And then use it like this:
public void Initialize()
{
    var observable =
            CreateStatesObservable()
                        .DistinctUntilChanged(new ListComparer())
                        .Select(_ => true);
}

A: I use now something like this:
public class RadGridColumnObservable
{
    public RadGridColumnObservable(RadGridView grid, IMessageBus messageBus)
    {
        this.grid = grid;
        this.messageBus = messageBus;
    }

    public IDisposable Initialize()
    {
        return Observable
            .Interval(TimeSpan.FromSeconds(1))
            .Scan((prev: grid.Columns.Select(it => it.IsVisible).ToList(), actual: grid.Columns.Select(it => it.IsVisible).ToList()),
                (acc, c) =>
                {
                    if (!acc.prev.SequenceEqual(acc.actual))
                        acc.prev = acc.actual;

                    acc.actual = grid.Columns.Select(it => it.IsVisible).ToList();
                    return acc;
                })
            .Where(it => !it.prev.SequenceEqual(it.actual))
            .Subscribe(it => messageBus.Publish(new NotifyMessage(MessageTypes.HistoryColumnsChanged)));
    }

    //

    private readonly RadGridView grid;
    private readonly IMessageBus messageBus;
}

but i don't like because i use 2nd time "SequenceEqual".

A: I think you can adjust your Initialize() to something like this:
public IDisposable Initialize()
{
    return Observable
        .Interval(TimeSpan.FromSeconds(1))
        .Select(v => grid.Columns.Select(it => it.IsVisible).ToList())
        .Scan((prev: new List<bool>(), actual: new List<bool>()),
            (acc, c) => (acc.actual, c))
        .Where(it => !it.actual.SequenceEqual(it.prev))
        .Subscribe(_ => messageBus.Publish(new NotifyMessage(MessageTypes.HistoryColumnsChanged)));
}

This should give you the same result and you only need SequenceEqual() once. The scan is just there so you have the "current" and the "previous" value. You don't really need to do a check inside it in your case.


text:
Q: Sending UTF-8 with sockets I'm tring to setup a little chat program in python. Everything was working fine until I
sent a string containing a non ascii character that caused the program to crash. The string are read from a wx.TestCtrl

*

*How can I send a string with UTF-8 encoding over sockets?

*Why does the program work without problems at the start? I have set the encoding to UTF-8
so wouldn't all character cause the program to crash?
Here is the error:
Traceback (most recent call last):
  File "./client.py", line 180, in sendMess
    outSock.sendto(s,self.serveraddr)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 26:
                    ordinal not in range(128)

Here is how I create the socket and try to send the message:
  outSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  ....
  outSock.sendto(s,self.serveraddr)

A: In Python 2, socket.sendto on a socket takes a "plain" string, not a unicode object. Therefore you must encode it, say using UTF-8:
outSock.sendto(s.encode('utf-8'), self.serveraddr)

Similarly, when you recvfrom (or similar) at the other end, you'll need to convert back to a Unicode object:
unicode_string = s.decode('utf-8')

(In Python 3, you'll be working with bytes, which makes the need to convert between it and unicode more explicit.)


text:
Q: How to pass make flags stored in text files in command line? I have a text file called OPTIONS.txt storing all flags of Makefile:
arg1=foo arg2="-foo -bar"

I want to pass all flags in this file to make. However,
make `cat OPTIONS.txt`

fails with make: invalid option -- 'a'. It seems that shell interprets it as:
make arg1=foo arg2="-foo -bar"
     ^argv[1] ^argv[2]   ^argv[3]

Is there any way to make it interpreted as:
make arg1=foo arg2="-foo -bar"
     ^argv[1] ^--------argv[2]

A: If you want the shell to interpret quotes after backtick expansion you need to use eval, like this:
eval make `cat OPTIONS.txt`

however just be aware that this evaluates everything, so if you have quoted content outside of the backticks you'll get the same issue:
eval make `cat OPTIONS.txt` arg4="one two"

will give an error.  You'd have to double-quote the arg4, something like this:
eval make `cat OPTIONS.txt` arg4='"one two"'

In general it's tricky to do stuff like this from the command line, outside of scripts.
ETA
The real problem here is that we don't have a set of requirements.  Why do you want to put these into a file, and what kind of things are you adding; are they only makefile variable assignments, or are there other make options here as well such as -k or similar?
IF the OP controls (can change) the format of the file AND the file contains content only used by make AND the OP doesn't care about the variables being command line assignments vs. regular assignments AND there are only variable assignments and not other options, then they can just (a) put each variable assignment on its own line, (b) remove all quotes, and (c) use include OPTIONS.txt from inside the makefile to "import" them.

A: Since you control the options file, store the options one per line:
arg1=foo
arg2="-foo -bar"

Then in the shell, you'll read the file into an array, one element per line:
readarray -t opts < OPTIONS.txt

Now you can invoke make and keep the options whole:
make "${opts[@]}"


text:
Q: How to map object with enums properties to object with values? I have the class.
public class ProductModel
{
    public long ProductId { get; set; }

    public int ContainerType { get; set; }

    public SolidForm SolidForm { get; set; }
}

SolidForm is Enum.
public enum SolidForm
{

    None = 0,

    Molten = 1,

    Solution = 2,

    InPowderedForm = 3
}

I need to create another model For Example
public class Product
{
    public long ProductId { get; set; }

    public int ContainerType { get; set; }

    public int SolidForm { get; set; }
}

Where property SolidForm is Value of Enum.
For example if I get in the first model SolidForm = SolidForm.Molten
after conversion in Product I want get int SolidForm = 1.

A: Though several answers exists, you could do the following:
public TType ConvertEnum<TType, TEnum>(TEnum content)
{
     var validated = typeof(TEnum);
     if(!validated.IsEnum)
          throw new Exception("Non enum passed.");

     var conversion = content as TType;
     if(conversion != null)
          return conversion;

     return default(TType);
}

A clean reusable method, plus it should support conversion of different types, checked the fiddle and appears to work correctly for most implementations.
So in your case, when you set a value of the property it would be:
Product.SolidForm = ConvertEnum<int, SolidForm>(SolidForm.Molten);

All though I believe that by default:
public enum SolidForm
{
     None,
     Molten,
     Solution
}

Your code doesn't appear to need the equal since it represents the default incremented approach, since you aren't overriding the values.

By default, the first enumerator has the value 0, and the value of
  each successive enumerator is increased by 1. For example, in the
  following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.
Copy enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};   Enumerators can
  use initializers to override the default values, as shown in the
  following example.
Copy enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};   In this
  enumeration, the sequence of elements is forced to start from 1
  instead of 0. However, including a constant that has the value of 0 is
  recommended. For more information, see Enumeration Types. Every
  enumeration type has an underlying type, which can be any integral
  type except char. The default underlying type of enumeration elements
  is int. To declare an enum of another integral type, such as byte, use
  a colon after the identifier followed by the type, as shown in the
  following example.

Update:
public static TDestination MapProperty<TSource, TDestination>(TSource source, TDestination destination)
{
    PropertyInfo[] sourceProperties = typeof(source).GetProperties();
    foreach(var property in sourceProperties)
    {
        var destinationProperty = typeof(TDestination).GetProperty(property.Name);
        if(destinationProperty != null)
        {
            // Error handling, validation of type, a bunch of other checks should go here.
            var value = ((destinationProperty.PropertyType)property.GetValue(source, null));
            destinationProperty.SetValue(destination, value, null);
        }
    }

    return destination;
}

Important to note, this will require a lot of exception handling.  Since you'll have to know about enum, nullable types, etc.  to avoid the conversion from failing.  Also, if your code has such large objects the reflection may be slow.
The basics of this code, loop through source object, find match on destination object, then do a raw cast, then set value, then return the destination object.  You may also need Activator.CreateInstance(typeof(Destination)); I wrote the code without a compiler really quick, so bank on refinement as I denoted above.  This should be a solid starting point though.

A: like that?
        Product p = new Product
        {
            SolidForm = (int)SolidForm.Solution
        };

A: Enum to int

(int)ProductModel.SolidForm

int to enum

(SolidForm)Enum.ToObject(typeof(SolidForm), ProductModel.SolidForm)

What mapper are you using?
You can just list the enums in your enum declaration if they are going in order like that

A: You can directly convert from enum to int just use typecasting
(int) SolidForm;


text:
Q: How to Reload in ReactJS without refreshing the page? I want to reload my ReactJS Page without refreshing it! There will be 'reload icon' in the page if some person click it then it should not Reload the page it should be single Page only!
Don't tell window.location.reload();

A: consider conditionally early returning the Redirect component : https://reactrouter.com/web/api/Redirect
so on your button click; setReload(true);
in your page component:
// before your regular return
if(reload) return <Redirect to={window.location.pathname} />;

A: If your component is a class component you can use this code below in the click function. this.forceUpdate().
if your component is a functional one you can follow this answer


text:
Q: Getting values from data attribute into an array I am trying to get values from data attribute (data-price) from different div on submit and put it into an array but can't get it working

var item_arr = new Array();

$('input[name^="item_price"]').each(function() {
  var MyVar = $(this).data('price');
  alert(MyVar);
  item_arr.push(MyVar);
});

console.log(item_arr);

I expect the output to be item_arr = ["150","175","125"] currently it just return an empty array

A: Your main issue is your selector: input[name^="item_price"]
You have input instead of div, because your element tags are type
.
Change it to: div[name^="item_price"]

Alternative jQuery approach
You can map the data value of every element and return a native array.

/** jQuery plugin */
(($) => {
  /**
   * Returns an array of data values for the selected elements.
   * @param {string} dataKey the data attribute key
   * @param {function} convertFn a post-processing function to convert the raw value
   * @return return an array of processed data values
   */
  $.fn.dataArray = function(dataKey, convertFn) {
    return this.map((i, el) => ((v) => convertFn ? convertFn(v) : v)($(el).data(dataKey))).toArray();
  }
})(jQuery);

console.log($('div[name^="item_price"]').dataArray('price', parseInt));
.as-console-wrapper { top: 0; max-height: 100% !important; }

A: Just change input[name^="item_price"] to div[name^="item_price[]"].
See below working code-

var item_arr = new Array();

$('div[name="item_price[]"]').each(function() {
  var MyVar = $(this).data('price');
  item_arr.push(MyVar);
});

console.log(item_arr);


text:
Q: How to search for a word through a csv file? This may be a very easy question but I'm new to python and I've searched the net however I couldn't solve the problem. I have a csv file which I need to search for a specific word in the columns of its first row. How can I do that?

A: I used the default csv module of python to read a csv file line by line. Since you specified that we have to search only in the first row, that's why I used break-to stop execution after searching the first row of the csv. You can remove the break, to search throughout the csv. Hope this works.
import csv
a='abc'     #String that you want to search
with open("testing.csv") as f_obj:
    reader = csv.reader(f_obj, delimiter=',')
    for line in reader:      #Iterates through the rows of your csv
        print(line)          #line here refers to a row in the csv
        if a in line:      #If the string you want to search is in the row
            print("String found in first row of csv")
        break

A: import csv
a='abc'     #String that you want to search
with open("testing.csv") as f_obj:
    reader = csv.reader(f_obj, delimiter=',')
    for line in reader:      #Iterates through the rows of your csv
        print(line)          #line here refers to a row in the csv
        if a in str(line):      #If the string you want to search is in the row
            print("String found in first row of csv")
        break

You'll have to add "str(line)" to convert the line to string and then compare it.


text:
Q: Short answer questions on integration by parts Here are the questions I'm supposed to answer:

For what kind of integrands is integration by parts an appropriate technique to try? What additional condition is needed for the tabular method to be used?

For the first question, I answered that the integrand must be the product of two terms. However, this is actually true for every integrand since they are just equal to $1$ times themselves.
And so, I have no idea what the best answer is to both questions.

Just to refresh your memory, the tabular method is where you have two columns, one for integration and one for differentiation, and with each row, the coefficient alternates from negative to positive. You can find examples here.

A: For when you should try integration by parts, I don't think that there is a clear cut answer. Rather, you should keep the technique in your toolbag, and whenever you come across an integral that you are struggling with, take it out and try to apply it.
To show why I don't think that there is a clear answer, here is one integral where integration by parts is an obvious choice:
$$
\int x^2e^xdx
$$
It is a product of two terms and one of the terms, $x^2$, gets simpler as we take derivatives.
Here is another integral which is easiest to solve with integration by parts
$$
\int \ln(x)dx
$$
Without having seen this before, I think it would be very difficult on first sight to guess that the correct method here would by integration by parts.


text:
Q: integrals of positive and negative parts for integrable function If $a>0$ and $\int\limits_{a}^{\infty}f(x)dx < \infty$,
can we claim that $\int\limits_{a}^{\infty}f(x)dx=\int\limits_{a}^{\infty}f^{+}(x)dx-\int\limits_{a}^{\infty}f^{-}(x)dx$
and what can we say about integrals of positive and negative parts?


text:
Q: Mysql Trigger comes up with error I have this trigger which should do this :
BEFORE a new entry is created in the entry log table , it will take the driver_id from that table , put it into the if statement and then set the allowed field from the new entry to either Y or No based on the outcome .
    create trigger xxx before insert on entrylog for each row
if  exists (select *
              from driver
              join card_driver
                on driver.id = card_driver.driver_id
              join card
                on card_driver.card_id = card.id
             where driver.id = new.driver_id) then
    set new.allowed = 'Y';
end if

The only problem is that it dosent work . I keep getting this error if I try an put it into phpmyadmin :
    Error

SQL query: Documentation

CREATE trigger allowedupdate before INSERT ON entrylog
FOR each
ROW
IF EXISTS (

SELECT *
FROM driver
JOIN card_driver ON driver.id = card_driver.driver_id
JOIN card ON card_driver.card_id = card.id
WHERE driver.id = new.driver_id
)
THEN
SET new.allowed = 'Y';

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 9

The if statement is taken from this and should produce the same outcome (just not echoing messages)
$sql ="SELECT *
  FROM driver AS d
INNER
  JOIN card_driver AS cd
    ON cd.driver_id = d.id
INNER
  JOIN card AS c
    ON c.id = cd.card_id
 WHERE d.ID = $id";
mysql_select_db('damp');
$result = mysql_query( $sql, $conn );
$row = mysql_fetch_assoc($result);
switch($row['state_id'])
{
case "1":
   echo "Authorisation Granted!";
   break; // This should be a Y , the rest are N
case "2":
   echo "Your card has expired and authorisation is denied";
   break;
case "3":
   echo "Your card has been cancelled and authorisation is denied";
   break;
default:
   echo "The Card ID does not exist";
}

A: This is a very subtle problem, but you are missing the final end if.  It is there, but the semicolon ends the trigger definition.  This is why MySQL has the delimiter keyword.
The trigger definition should look like:
delimiter $$
create trigger xxx before insert on entrylog for each row
begin
    if  exists (select *
                  from driver
                  join card_driver
                    on driver.id = card_driver.driver_id
                  join card
                    on card_driver.card_id = card.id
                 where driver.id = new.driver_id) then
        set new.allowed = 'Y';
    end if;
end;$$
delimiter ;

I also added the begin/end.  Although not strictly necessary, I always use them.  And, you would have gotten a compile time error if your original statement had them.


text:
Q: Loading help documentation alters irb results I'm learning Ruby, and went into irb to test something out with the Date class. In short, I did the following:
$ irb
irb(main):001:0> Date.new
=> #<Date:0x007f983103ee60>
irb(main):002:0> Date.constants
=> []
irb(main):003:0> help Date
=> nil
irb(main):004:0> Date.constants
=> [:MONTHNAMES, :ABBR_MONTHNAMES, :DAYNAMES, :ABBR_DAYNAMES, :ITALY, :ENGLAND, :JULIAN, :GREGORIAN, :Infinity]
irb(main):005:0>

I'm so confused by this. Questions:

*

*Why would reading help documentation cause the output of Date.constants to change?

*Presumably help is loading/initializing something. What is it? And why did Date.new work?

*Is whatever this is something I need to worry about when writing .rb files?

This is tough to Google for. I'm on ruby 2.1.2 and irb 0.9.6.

A: The most likely cause of the addition of the Date constants after running help Date is that somewhere in the execution of the command, require 'date' (or require 'time') is called:
2.1.0 :001 > Date.constants
 => []
2.1.0 :002 > require 'date'
 => true
2.1.0 :003 > Date.constants
 => [:MONTHNAMES, :ABBR_MONTHNAMES, :DAYNAMES, :ABBR_DAYNAMES, :ITALY, :ENGLAND, :JULIAN, :GREGORIAN, :Infinity]

As for Date.new, it works because Date comes with a default constructor.
I doubt this will ever be problematic for you.


text:
Q: Why does conversion of a range object to generator result in a `range_iterator` object? This is not a duplicate of Why a range_iterator when a range is reversed? You'll know why if you take a look at it.
My question pertains to the distinction between a generator resulting from range versus any other iterator, and why that distinction is made:
In [500]: iter(range(5))
Out[500]: <range_iterator at 0x10987f810>

Whereas...
In [506]: (i for i in range(4))
Out[506]: <generator object <genexpr> at 0x10a025fc0>

So, why is this distinction made and what merit does it have?

A: Simple, range is not an iterator:
In [32]: r = range(10)

In [33]: next(r)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-0b5056469c9c> in <module>()
----> 1 next(r)

TypeError: 'range' object is not an iterator

range is a sequence type, and like all other containers, iter returns a corresponding iterator object:
In [34]: iter(list())
Out[34]: <list_iterator at 0x112197cc0>

In [35]: iter(tuple())
Out[35]: <tuple_iterator at 0x112107be0>

In [36]: iter(dict())
Out[36]: <dict_keyiterator at 0x1142eef98>

Generally, containers are iterables, not iterators. They implement __iter__, whereas an iterator implements __iter__ and __next__.
Note, the terminology in your title is a bit off, and frankly, I think you are conflating generators, iterators, and iterables. iter(obj) doesn't return a generator, it returns an iterator object. A generator is a language construct that allows for succinctly writing iterators. The generator objects returned by a generator function are iterators:
In [37]: def mygen():
    ...:     yield 1
    ...:     yield 2
    ...:

In [38]: g = mygen()

In [39]: g
Out[39]: <generator object mygen at 0x1121778e0>

In [40]: next(g)
Out[40]: 1

In [41]: iter(g) is g
Out[41]: True

Finally, a generator expression is just an even handier way of writing generators!
In [44]: (i for i in range(10) if i % 2 == 0)
Out[44]: <generator object <genexpr> at 0x10de89990>

In [45]: next(_)
Out[45]: 0


text:
Q: Current Post ID is not fetching in function.php in wordpress I want to fetch the current post id in function.php file for some reason.
I have used the below code :
<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo $postid;
?>

But not getting any thing...

A: The post ID isn't available to you right when functions.php runs. You'll need to hook into 'template_redirect' (or later):
function get_current_post_ID() {
    $postid = get_queried_object_id();
}
add_action( 'template_redirect', 'get_current_post_ID' );

A: There is another word press hook 'wp' which return current post ID in function.php
function mypostID()
{
    global $wp_query;
    return $wp_query->get_queried_object_id();
}
add_action('wp','mypostID');


text:
Q: UseState altera para undefined no momento de salvar a foto Estou precisando salvar o caminho da foto tirada através do método camera.takePictureAsync. Criei a variável através do conceito do Hook conforme a definição abaixo:
const [path,setPath] = useState('');

Quando  o método setPath é utilizado e executo o  console.log('Caminho : ',path); aparece o valor undefined. Aparentemente a variável path não está sendo alterada. Não sei o que pode estar acontecendo.
segue a function que estou utilzando.
async function  takePicture(camera){
          const options = {quality:0.5,base64:true};
          const data = await camera.takePictureAsync(options);
          console.log('URI: ',data.uri);
          setCapturedPhoto(data.uri);
          setOpen(true);

          let v = '"' + data.uri + '"';

          setPath(v)
          console.log('Caminho : ',path);

          //chama função salvar a foto
          await savePicture(data.uri);

        }

A: Encontrei a resposta. Para quem precisar segue o link abaixo:
https://stackoverflow.com/questions/65505954/image-picker-save-uri-with-hook


text:
Q: Open a chrome profile in python that is already signed into google I'm trying to open up my chrome profile which is signed into google however am not having any luck.
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument(r'user-data-
dir=G:\Users\Kareem\AppData\Local\Google\Chrome\User Data\Profile 10')
chrome_path= r"G:\Users\Kareem\Documents\Work\Computer
Science\Selenium\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.google.co.uk/webhp?source=search_app")

A: When you create the driver, you're not actually passing the options to it.
driver = webdriver.Chrome(chrome_options=options)


text:
Q: How to solve encoding when piping file from NodeJs Cloud Function? I'm attempting to pipe a file in Firebase bucket through a nodeJS cloud function to the client (browser). The client will use file-saver.js to start the download on the browser.
This works well with text/plain mime types but produces corrupt files with images and pngs. The issue is with encoding, as I can see the data that reaches the client is not encoded properly.
Here is an example response on client side w/ an image:
data: "�PNG↵↵IHDR%�*���sBIT|d�...

How should I properly pipe the file back to maintain the correct encoding?
Here is the current cloud function:
const filesBucket = admin.storage().bucket(FILES_BUCKET_NAME);

function getFile(fileName, res){
  const filePath = fileName
  const file = filesBucket.file(filePath)

  res.setHeader('Content-Type', getMimeType(fileName));
  res.setHeader('Content-Disposition', 'attachment; filename='+fileName);

  file.createReadStream()
    .on('error', err => {
        // not good
    })
    .on('response', function(response) {
        // ok
    })
    .on('end', function() {
        // The file is fully downloaded.
    })
    .pipe(res); // pipe the file back to client
}

Here is the client side part:
export const getFile = (filename) =>{
   ...
   axios.get(fileUrl, config)
     .then(resp => {
         downloadFile(resp.data, filename, getMimeType(filename))
     }).catch(err => {
         console.log("getCurrentUserFile | err", err)
         reject(err)
     })

function downloadFile(data, filename, mimeType){
    var blob = new Blob([data], {type: mimeType});
    FileSaver.saveAs(blob, filename);
}

A: I am not sure how file-saver save file but I was able to download files with below setup and might help you.
index.html
<!DOCTYPE html>

Hello World!

Nodejs:
const express = require('express')
const fs = require('fs')
const app = express()
const port = 3000

app.use(express.static('public'))

app.get('/getfile', (req, res) => {
    res.setHeader('Content-Type', 'image/png');
    //res.setHeader('Content-Disposition', 'attachment; filename='+'test.png');
    fs.createReadStream('./demo.png').pipe(res)
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

A: The problem was on the client side, using FileSaver.js and nothing with encoding.
Once I used this,it worked:
axios({
    url: fileUrl,
    method: 'GET',
    params:{...},
    responseType: 'blob', // <--important
}).then((resp) => {
     const url = window.URL.createObjectURL(new Blob([resp.data]));
     const link = document.createElement('a');
     link.href = url;
     link.setAttribute('download', filename);
     document.body.appendChild(link);
     link.click();
});

Credit where credit it due


text:
Q: Embed camera frame in web app html5 I want to beuild web app that the user will upload a image from device camera.
I know that I can use <input type="file" accept="image/*" capture="camera">.
My question is that if there is a way to "embed" the camera screen in the page itself. In other words, I want that the screen will look like this:

A: I suggest you can read the article Capturing Audio & Video in HTML5.
Here is the code to access your camera:
<video autoplay></video>

<script>
  var errorCallback = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, errorCallback);
</script>

Taking screenshots:
<video autoplay></video>
<img src="">
<canvas style="display:none;"></canvas>

<script>
  var video = document.querySelector('video');
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d');
  var localMediaStream = null;

  function snapshot() {
    if (localMediaStream) {
      ctx.drawImage(video, 0, 0);
      // "image/webp" works in Chrome.
      // Other browsers will fall back to image/png.
      document.querySelector('img').src = canvas.toDataURL('image/webp');
    }
  }

  video.addEventListener('click', snapshot, false);

  // Not showing vendor prefixes or code that works cross-browser.
  navigator.getUserMedia({video: true}, function(stream) {
    video.src = window.URL.createObjectURL(stream);
    localMediaStream = stream;
  }, errorCallback);
</script>

A: Video tag is there HTML5 to handle this. and you need to use getUserMedia api to handle the streaming. most of the modern browsers supports it. To validate whether it is supported, use javascript to check that. You can try this:
if(navigator.getUserMedia()) ....

A: Here's a good tutorial on how to use a web cam to capture images. The same person also has a tutorial on capturing video to GIFs.
http://davidwalsh.name/browser-camera
HTML 5 Image capture tutorial & demo


text:
Q: Leading Zeros to organise project folders within columns Hi I am a complete newbie and I want to organise the Projects by JobPac numbers which start with leading Zeros - 0001, 0002 is there some way I can do this? Or would it be best to ask the JobPac team to renumber and drop leading zeros? I found an answer from 2014 which suggested this-  concat(substring('00', 1, 3 - string-length(field)), field)
However I tried but it didn't work displayed 5 not 0005.

A: If you only want to add 3 leading zeros, JSON formatting will help you do that.
How to start using JSON formatting.
A bit more explanation: The JSON I provide simple add 3 leading zeros on the original pac number. So no need to worry about the input. If user enters, say '11', then in the list you will see '00011'.
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "txtContent": "=('000'+'@currentField')"
}

The original code number is M123456789.

A: You could create a calculated column that references the JobPac number field and use something like this for the formula:
=Text([jobPacField],"0000")

Update
If you're having difficulty with the formula, it might be easier to double click on the column from the "Insert Column" box.

Another thing that might cause an issue is pasting the double quotes from this website. Perhaps try typing the formula instead of copying & pasting?

A: You want the new padStart operator
From
https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/formatting-syntax-reference
padStart: pads the current string with another string until the resulting string reaches the given length. The padding is applied from the start of the current string.
"txtContent":"=padStart('DogFood', 10, 'A')" results in AAADogFood
"txtContent":"=padStart('DogFood', 10, 'AB')" results in ABADogFood
"txtContent":"=padStart('DogFood', 5, 'A')" results in DogFood

The way I have implemented it on a number column is as below:
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
   "elmType": "div",
   "txtContent":"=padStart(toString(@currentField), 4, '0')"
}


text:
Q: What is Firebase current timestamp is for? I have a chat app where conversations are deleted within 7 days if they don't meet certain requirements. So when the conversation is created I save the current time which goes as the creation time and later on I compare it to the current time the moment of the comparison to find out how much time it has been. I do that using Date.now() but I noticed that other developers use Firebase current timestamp. Question is why ?
Update:
I understand now that Date.now() can't be trusted with the app side of things as it is manipulable by the user. So what about the cloud functions ... Date.now() is good enough in there ?


text:
Q: Why for a large displacement of a mass tied to a string is not SHM Why if a mass tied to an ideal string is given a small displacement, its motion is SHM. However, for a large displacement it is not SHM but oscillatory?

A: If you are talking about the motion of a pendulum, its equation is given by $\frac{d^2 \theta}{d t^2} = - \frac{g}{L} \sin \theta$. However, the simple harmonic motion is described by $\frac{d^2 \theta}{d t^2} = - \frac{g}{L}\theta$ - note the absence of the sine here. For small displacements we can approximate $\sin \theta \simeq \theta$, using a Taylor series expansion, which means that for small angular displacements the motion is indeed simple harmonic to a reasonable degree of accuracy. As $\theta$ becomes larger, the non-linearity of the sine function become more pronounced, and the motion departs from the simple harmonic form. This has a solution in terms of elliptic integrals.


text:
Q: Adding more text to a post, after it was published I'm trying to build a wp plugin, which will basically add some text for every post, in the post itself, I'm afraid that the codex is too large for me to even know what to look for, so I'd appreciate if someone could point me in the right direction.
Edit: As per request, the info should be added to the post's text on the database, at the end of the post, it's not static, it's a random embed from a tube site, based on a query I run on the tubesite.

A: Your best bet is to use the the_content filter hook and add your content to the post
"on the fly" for ex:
add_filter('the_content','add_my_extra_content');

function add_my_extra_content($content){
   $my_extra = "
this is the extra content
';

   //add before post content
   // return $my_extra.$content;

   //add after post content
   return $content.$my_extra.;

}


text:
Q: how do I make my essay impactful? I have the ideas but I cant pen them down.I get the following problems while writing an essay:
1. I dont know where to start or end.
2. I cant maintain continuity in my essay.
3. my language skills arent impactful at all.
I know the solution lies in practising writing . but maybe it will be easier if I can get some tips.
thank you in advance :)

A: If you have thoughts it should not be difficult.
1. Write down your thoughts as they are (brainstorming)
2. Create a simple outline (intro, body, conclusion).
3. Organize your writing according to your outline.
4. Read your essay to see if it makes sense.

A: My brother, who takes lots of courses (in travel writing, modern literature, journalism) always picks my writing to bits. He says that what I ought to do is write a first paragraph which includes all those ideas (the ones you jotted down before you started). What you're saying is : listen up this is what I have to say.
Then you write a paragraph for each of these ideas. Ideally finish each paragraph with a link.  That's dealt with. Now, for the next.
Your first paragraph probably helped you see the order and sequence of ideas.
When you have mastered this master plan, then push the boundaries. That's the only bit I'm good at.
Then, my brother says, you write a final paragraph which mentions all your ideas and says 'That 's what I have to say.'


text:
Q: Android Webservices with php i want create web service with php code , PHP file containing the text and I want to show this text android textVeiw
I connection with URL via openConnection() but i have error in  class InputStreamReader
public class MainActivity extends AppCompatActivity {
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.textView4);
    }

    public void onClick(View view) throws Exception {

        URL hellofileurl = null;
        try {
            hellofileurl = new URL("http://waaddev.ahosti.net/web.php");
            HttpURLConnection myfirstconnection = (HttpURLConnection) hellofileurl.openConnection();
            InputStream stream = new InputStream(myfirstconnection.getInputStream());//i have error in this line
            BufferedReader b = new BufferedReader(stream);
            String hello = b.readLine();

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

A: InputStream class has been deprecated.
You can use:
    URL url = new URL("http://waaddev.ahosti.net/web.php");
    URLConnection urlConnection = url.openConnection();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

    String line;
    while ((line = bufferedReader.readLine()) != null)
    {
         content.append(line + "\n");
    }
    bufferedReader.close();
    String hello = content.toString();

A: You can see my repository which is a clear example how to make a simple call to a PHP web service (with MySQL also).
In this example you have a list of product in a remote MySQL database and you get them through a PHP Web Service into your app.
You can also add an item into the DB through your app.
Hope it can solve your doubts.
The repository is:
https://github.com/alessandroargentieri/AndroidToWebService


text:
Q: Is there a better way to determine the distance between two enum values? I have an enum with 8 bit shifted values. I would like to be able to determine how far apart any two values are. This would be simple if the values were simply increasing integers. Here is what I've got for now.
typedef NS_ENUM(NSInteger, TestEnum) {
    TestEnumValue1 = 1 << 0,
    ...
    TestEnumValue8 = 1 << 7
};

TestEnum left = TestEnumValue8;
TestEnum right = TestEnumValue3;

TestEnum high = MAX(left, right);
TestEnum low = MIN(left, right);

int distance = 0;
int maximumEnum = 8;
int cumulativeResult = high;
for (int i = 0; i < maximumEnum; i++)
{
    cumulativeResult = cumulativeResult / 2;
    if (cumulativeResult == low)
    {
        distance = i;
        break;
    }
}
NSLog (@"Distance is %d", distance);

The above seems to be working well, but is it the best way?

A: Ignoring whether using an enum is appropriate or not, try this:
TestEnum left = TestEnumValue8;
TestEnum right = TestEnumValue3;

TestEnum high = MAX(left, right);
TestEnum low = MIN(left, right);

int distance = 0;
while (low < high) {
    low <<= 1;
    distance++;
}

NSLog (@"Distance is %d", distance);

Keep in mind that this only works if both left and right have a single "flag" set.

A: Here's a potential solution: Add the two (positive) integers and count the zero bits between the one bits. The commutativity of addition obviates the fiddly need to figure out which operand is bigger.
int distance;
int k = left + right;
int started = 0;
while (k > 1) {
        if (!started && (k & 1)) {
                started = 1;
                distance = 0;
        }
        if (started) distance++;
        k >>= 1;
}

printf("%d\n", distance);

A: I hacked together something nasty, but which sort of works and allows use of enum values that aren't contiguous powers-of-2.
The following is the 'enum' definition, with the actual enum values being defined in the DEFINE_MYENUM(x,y) statements:
#include <cmath>
#include <map>

class Value {
public:
    virtual operator int() const = 0;
    int getIndex() const { return index; }

    static const Value& fromValue(int val)
    {
        return *(getReverseMap().find(val)->second);
    }

protected:
    int index;
    static int getNextIndex() {
        static int curIndex = 0;
        return curIndex++;
    }
    static std::map<int, Value*>& getReverseMap() {
        static std::map<int, Value*> reverseMap = std::map<int, Value*>();
        return reverseMap;
    }
};

template<int y> class ValueImpl : Value {
public:
    ValueImpl() {
        index = Value::getNextIndex();
        Value::getReverseMap()[y] = this;
    }
    virtual operator int() const override { return y; }
};

#define DEFINE_MYENUM(NAME, VALUE) const ValueImpl<VALUE> NAME
class MyEnumDefs {
public:
    DEFINE_MYENUM(Value1, 2);
    DEFINE_MYENUM(Value2, 4);
    DEFINE_MYENUM(Value3, 8);
    DEFINE_MYENUM(Value4, 16);
    DEFINE_MYENUM(Value5, 20);
    DEFINE_MYENUM(Value6, 25);

    int distance(const Value& x, const Value& y) {
        return std::abs(x.getIndex() - y.getIndex());
    }
    int distance(int x, int y) {
        const Value& xx = Value::fromValue(x);
        const Value& yy = Value::fromValue(y);
        return distance(xx, yy);
    }
};
#undef DEFINE_MYENUM

class MyEnum {
public:
    static MyEnumDefs& inst() {
        static MyEnumDefs internalInst = MyEnumDefs();
        return internalInst;
    }
};
#define MyEnum MyEnum::inst()

The following is the test code:
int main(int argc, const char * argv[])
{
    int a = MyEnum.Value1;
    int b = MyEnum.Value2;
    int c = MyEnum.Value3;
    int d = MyEnum.Value4;
    int e = MyEnum.Value5;
    int f = MyEnum.Value6;
    printf("a b c d e f: %d %d %d %d %d %d\n", a, b, c, d, e, f);

    printf("Distance b d: %d\n", MyEnum.distance(b, d));
    printf("Distance d b: %d\n", MyEnum.distance(d, b));

    printf("Distance e f: %d\n", MyEnum.distance(e, f));
    return 0;
}

Output:
a b c d e f: 2 4 8 16 20 25
Distance b d: 2
Distance d b: 2
Distance e f: 1

Obviously this is not perfect, e.g. syntax MyEnum.XXX instead of XXX or MyEnum::XXX, lack of ability to use 'MyEnum' as a type etc... but figured it's a good start on something that could be pretty neat :)


text:
Q: How can I access the arguments of a function in a decorator for that function? I want to write a decorator to easily print the type of all arguments that were given to a function in R.
So far I managed to write code that does that for me, but I want to avoid copy-pasting it to the required functions.
    fun <- function(...){
        c = as.list(match.call())
        d= lapply(c, print(typeof))
        print(d)}

This prints the expected result.
Now i wanna embed this behaviour in a decorator, but I can't access the arguments of the function within the decorator.
    print_arguments <- function(f){
        function(...){
        arguments_of_f = ???
        d= lapply(arguments_of_f, print(typeof))
        print(d)
        return(f(...))
        }
    }

How do I get the arguments of f in this case?
Thanks for your help!

A: Not completely sure why you are using match.call. The easiest way get the arguments is to use list(...). This you can also use in your decorator:
print_arguments <- function(f){
  function(...){
    d <- sapply(list(...), typeof)
    print(d)
    return(f(...))
  }
}

I am using sapply instead of lapply as the output can easily be converted to a vector and this gives a cleaner output.
Output:
> foo <- print_arguments(plot)
> foo(iris, pch = 20)
              pch
  "list" "double"

Note
As remarked by @MrFlick, this does not work when the decorated function uses non-standard argument evaluation. For example:
> subset_deco <- print_arguments(subset)
> subset_deco(iris, Sepal.Length > 1)
 Error in lapply(X = X, FUN = FUN, ...) : object 'Sepal.Length' not found


text:
Q: Multithreading issues with Pandas I have a very large excel file of 1000+ street intersections that I need to find the Longitude and latitudes for and then write that info to file/list for a different program to consume.
What I'm stuck on is on how to build a more efficient script using multithreading/multiprocessing, I have looked through other questions/post but I'm i find it all a bit confusing. The code below takes roughly ~ 10+ mins. Any help would be great.
from geopy.geocoders import ArcGIS
import pandas
from datetime import datetime

start_time = datetime.now()
def my_LatLong(address):
    n = ArcGIS().geocode(address)
    if n != None:
        return n
    else:
        return [address,"None"]

df = pandas.read_excel("street_sample.xlsx",sheet_name=0)
count = 0
street_list = df.loc[:,"Description"]

new_list =[]
for i in list(street_list):
    location = my_LatLong(f"{i.split('-')[0]}, Vancouver, Canada")
    if location != None:
        new_list.append([f"{len(street_list)}, {list(location)}"])
        print(f"{count}/{len(street_list)} - {i} = Completed\t\t\t\t" ,end='\r')
    else:
        print(f"{count}/{len(street_list)} - {i} == None value \t\t\t",end='\r')

    count += 1

# doing something with new_list

endtime_time = datetime.now()

print (f"Program ran for:  {endtime_time -start_time}")

street_sample.xlsx

ID
Description

12501x
1900 W Georgia - ONAT_STREET:

12501x
4th/6th Diversion & 6th Ped - ONAT_STREET:

12501x
4th/6th Diversion & 6th Semi - ONAT_STREET:

12501x
Abbott & Cordova - ONAT_STREET:

12501x
Abbott & Expo - ONAT_STREET:

12501x
Abbott & Hastings - ONAT_STREET:

12501x
Abbott & Keefer - ONAT_STREET:

12501x
Aberdeen & Kingsway - ONAT_STREET:

12501x
Alberta & 49th - ONAT_STREET: 70175

12501x
Alder & 12th - ONAT_STREET:

12501x
Alder & 6th - ONAT_STREET:

12501x
Alder & Broadway - ONAT_STREET:

12501x
Alexandra & King Edward - ONAT_STREET:

12501x
Alma & 10th - ONAT_STREET:

12501x
Alma & 4th - ONAT_STREET:

12501x
Alma & 6th - ONAT_STREET:

12501x
Alma & Broadway - ONAT_STREET:

12501x
Alma & Point Grey Road - ONAT_STREET:

12501x
Anderson & 2nd / Lamey's Mill - ONAT_STREET:

12501x
Anderson (Granville) & 4th - ONAT_STREET:

12501x
Angus & 41st - ONAT_STREET:

12501x
Angus & Marine - ONAT_STREET:

12501x
Arbutus & 10th - ONAT_STREET:

12501x
Arbutus & 11th - ONAT_STREET:

12501x
Arbutus & 12th - ONAT_STREET:

12501x
Arbutus & 16th - ONAT_STREET:

12501x
Arbutus & 20th  - ONAT_STREET:

12501x
Arbutus & 33rd - ONAT_STREET:

12501x
Arbutus & 4th - ONAT_STREET:

12501x
Arbutus & 8th - ONAT_STREET:

12501x
Arbutus & Broadway - ONAT_STREET:

12501x
Arbutus & Cornwall - ONAT_STREET:

12501x
Arbutus & King Edward - ONAT_STREET:

12501x
Arbutus & Lahb - ONAT_STREET:

A: The problem does not comes from Pandas but ArcGIS().geocode(address) which is insanely slow. Indeed, on my machine, this line takes 400 ms/request. Each request send a slow network query to the online ArcGIS API. Using multiprocessing will not help much as you will quickly reach additional limitations (limited rate of API request, saturation of the website). You need to send batch requests. Unfortunately this does not seems supported by the geopy package. If you are tied to ArcGIS, you need to use their own API. You can find more information about how to do that on the ArcGIS documentation.


text:
Q: Two 'boxes' under one another and another on the right please click for updated imageCurrently, my webpage looks like this:

But I want the bottom box to fit right under the top one while keeping the box on the right in the same place.
This is what i have now
#intro-chemistry{
    background-color: #C7C7C7;
    border-top: 7px solid rgb(177, 177, 177);
    width: 242px;
    height: 103px;
    padding: 13.75px;
    margin: 13.75px 13.75px;
    text-align: left;
    float: left;
}

#intro-physics{
    background-color: #C7C7C7;
    border-top: 7px solid rgb(177, 177, 177);
    width: 238px;
    height: 285px;
    padding: 13.75px;
    margin: 13.75px 13.75px;
    text-align: 10, 10, 10, 10;
    float: left;
}

#intro-classic{
    background-color: #C7C7C7;
    border-top: 7px solid rgb(177, 177, 177);
    width: 242px;
    height: 103px;
    padding: 13.75px;
    margin: 13.75px 13.75px;
    text-align: left;
    float: left;
}

I'm trying to get the box "classic" to fit right under the box "chemistry' whilst the box 'physics' stays put.

A: You have to change your HTML structure.
HTML

    Chemistry

    Classic

    Physics

CSS
.col-left{
  float: left;
  width: 242px;
}
.col-right{
  float: right;
}


text:
Q: how to access a non static member from a static method in java? I have a situation where i have to access a non static member from inside a static method. I can access it with new instance, but current state will be lost as non static member will be re-initialized. How to achieve this without losing data?

A: Maybe you want a singleton. Then you could get the (only) instance of the class from within a static method and access its members.
The basic idea is
public class Singleton {
  private static Singleton instance = null;

  private Singleton() {}

  public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
  }
}

and then in some static method:
public static someMethod() {
    Singleton s = Singleton.getInstance();
    //do something with s
}

A: What you are asking for doesn't really make sense. Just make your method non-static because your static method cannot be tied to an instance.

A: Static methods do not apply to a particular instance/object, they're a class-level thing. Because of that, they're not given an instance reference. So, no you cannot do this.
If you can work out which instance reference to use another way, you could access the non-static methods of it.
Or, alternatively, re-architect your classes so that it's a non-static method.

A: You can't. A static method is not associated with any particular state (aka any non-static members). In other words, they operate independently of any particular instance of the class so they cannot depend on non-static members.

A: A non static member variable "is state". It's the state of a specific instance of that class.
When you say you want to access a non-static member variable, it's as good as saying "want to access a non-static member variable of a specific instance of class XXX", I mean the bolded part is implicit.
So it doesn't make sense to say "I can access it with new instance".


text:
Q: Cannot see Trace logs when loglevel set to Trace in azure function Steps to reproduce:
Create a new V2 function app in VS
Select HTTP trigger, paste in the following code:
log.LogTrace("This is a trace log");
log.LogDebug("This is a debug log");
log.LogInformation("This is an information log");
log.LogWarning("This is a warning log");
log.LogError("This is an error log");
log.LogCritical("This is a critical log");
return new OkResult();

Go to host.json, configure as follows:
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": false
      },
      "fileLoggingMode": "always",
      "logLevel": {
        "default": "Trace",
        "Host.Results": "Error",
        "Function": "Trace",
        "Host.Aggregator": "Trace"
      }
    }
  }
}

Run the host, trigger the HTTP function
Expected result - trace message should appear in the application insights
Actual result:
Query in Application insights
union traces
| union exceptions
|union requests
| where timestamp > ago(30d)
| where operation_Id == 'be439155fd015344badd3839da2652a8'
| where customDimensions['InvocationId'] == '6057a32f-0f59-4193-8845-a5f9d972169f'
| order by timestamp asc
| project timestamp, message = iff(message != '', message, iff(innermostMessage != '', innermostMessage, customDimensions.['prop__{OriginalFormat}'])), logLevel = customDimensions.['LogLevel']

timestamp [UTC]             message
8/31/2020, 4:00:58.764 PM   Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=6057a32f-0f59-4193-8845-a5f9d972169f)              Information
8/31/2020, 4:00:58.764 PM   Information Logged
8/31/2020, 4:00:58.953 PM   error Logged
8/31/2020, 4:00:58.954 PM   Warning Logged
8/31/2020, 4:00:58.954 PM   Executed 'Function1' (Succeeded, Id=6057a32f-0f59-4193-8845-a5f9d972169f, Duration=190ms)

A: That json file is not correct. fileLoggingMode is not a property of the applicationInsights object. Also, the log levels for the Host.Result and Host.Aggregator categories should not be set inside the application insights section. See the reference.
But, besides that, you are having issues because the minimum log category filtering for functions should be lower or equal to the log level of application insights. The default log level in azure functions is Information so a trace won't pass through.
Try this:
{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host.Results": "Information",
      "Function": "Trace",
      "Host.Aggregator": "Information"
    },
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": false
      },
      "logLevel": {
        "default": "Trace"
      }
    }
  }
}

Given the example above the log level for the Function category matches the log level of application insights. Otherwise the application insights log provider won't be able to pick up the logs and send them as TraceTelemetry to Application Insights.


text:
Q: Problem with special characters in .toc files I have an odd problem with special characters (in this case the Swedish åäö), that pops up in my .toc file. If I remove the .toc file everything works OK except I get an empty table of contents. When I re-run pdflatex, I get errors on every line in the .toc file that has either of åäö in it (which, as it happens, is every line...).
I've tried to produce a MWE example of this, but I'm unable to reproduce the problem with other files. However, I've noticed that for other files, åäö in the .toc file are replaced as follows:
å -> \IeC {\r a}
ä -> \IeC {\"a}
ö -> \IeC {\"o}

In the .toc file for the failing document, only å is replaced. Why could this be? What can I do about it?
Clarification: As I said, I have tried but been unable to reproduce this error in a MWE. (The full version is a pretty advanced structure with templates, frame and content files compiled by a python script calling pdflatex via os.system(), so I can't really just "scale off" one piece after another...) However, I can give the following information:

*

*All files are saved in utf-8.

*I'm using \usepackage[utf8]{inputenc} and \usepackage[swedish]{babel}.

*The python file starts with #coding: utf8

A: When the non-ascii-chars like ä or ö get in the toc, this means that they are not active. Perhaps you are storing some of your titles in commands before inputenc has been loaded:
\documentclass{article}
\def\test{ÅÄÖ}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}
\tableofcontents

\section{\test}

\end{document}

My example doesn't give an error, but its possible that your python code insert an utf8 char tex can't handle.

A: From the inputenc documentation:

1.3.3 Unicode char <charcode> is not set up for use with LaTeX
This is the dreaded error message that one will receive if the document contains an
  UTF-8 character that isn't known to LATEX. It is quite possible that the character
  looks very unsuspicious and is rendered perfectly in the editor.
...
However, even if LATEX can type that character in question it may not
  have been set up in which case you would need to do that yourself via
  \DeclareUnicodeCharacter.

So, something like \DeclareUnicodeCharacter{00E4}{\"a} might work. You'd probably need to see which Unicode glyph is the one you're trying to use (this example straight from the manual, section 1.2).
Hope this helps.

A: Use a meaningful encoding such as
\usepackage[utf8]{inputenc}

but also take care that your editor uses the same encoding and that the file itself has this encoding too. For instance, one may download a latin1 encoded file but edit it with utf8 option and the other way round.


text:
Q: How to get user's mail address with Identity and ASP.Net Core I'm using ASP.NET Core and ASP.NET Identity.
I'm trying to get user's mail address (not the current user one).
For the current user, I have no trouble, I did this and it's working :
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

And in my Controller's method:
ApplicationUser curUser = await GetCurrentUserAsync();
string mail = curUser.Email;

It's working, but I want another user's mail address too, from his identifier.
How can I do that ?


text:
Q: In practice, is there a limit to the insulating properties of a transistor acting as switch? I would like to know if there a limit to the insulating properties of a transistor acting as switch?

A: There is a limit to the insulating properties of everything - air, rubber, glass, switches, transistors, everything. This is called the "insulation breakdown voltage".
Exactly how high it is depends on the device. The breakdown voltage for tiny transistors can be as small as a few volts.

A: Transistors are based on semiconductor junctions, and thus have what we typically call a breakdown voltage. It varies, depending on the transistor, from less than 5 V to multiple kV. You'll need to look up the numbers in your transistor's datasheet.

A: One must not forget that the signal frequency affects the transistor insulation as well. For instance, a RF signal cannot be switched by transistors, you need either a relay (for low speed switching) or PIN diodes (for high speed switching).
That said, your switch insulation may drop drastically if the signal frequencies are too high.

A: Transistors can be used as switches for RF, if the RF rides atop a DC pedestal.
A diffpair works fine [I've seen this in mixer/modulator/multipler ICs] to steer the DC+RF to the left or right.
The capacitive properties will set the high-frequency "insulating" behavior.


text:
Q: import QtQuick.Controls 2.1 QML MODULE NOT FOUND I am using Qt Creator 2.4.1 base on Qt 4.7.4(32 bit) on windows. I have to create a table in QML using Table View. When i try import QtQuick.Controls 2.1 i get the error QML MODULE NOT FOUND. Same error on Qt Creator 2.6.2 based on Qt 5.0.1.
Any help appreciated.

A: In my case running qmake fixed issue.
Update 2020 (new way):
In some cases it not helped. Instead this solution helped greatly.
In the QtCreator, open settings/preferences and go to QtQuick > QtQuick Designer and select Use QML emulation layer... option in Qml Emulation Layer section and get your most newer version of Qt to it as follow:

A: The module QtQuick.Controls has been added on Qt 5.1 and is currently at the 1.0 version. It also requires you having QtQuick version 2.0, introduced with Qt 5 So if you want to use TableView you would have to update your current Qt version to at least 5.1 and then use these import statement:
import QtQuick 2.0
import QtQuick.Controls 1.0

Also, as indicated by Armaghast in the comment, if you are moving to the latest Qt version (currently Qt 5.2.1) you should use
import QtQuick 2.2
import QtQuick.Controls 1.1

A: In October 2016, Qt Qtuick Controls 2.1 were released as part of Qt 5.8
If anybody (like me) stumbles upon this error when using someone else code, you need to install Qt 5.8 or newer. Lower versions will fail to run the QML GUI.
More info at: http://blog.qt.io/blog/2016/10/06/qt-quick-controls-2-1-and-beyond/


text:
Q: Android compile - class not found - org.ibex.classgen.CGConst When I try to run my project on Android, it's showing me this error message:
java.lang.ClassNotFoundException: org.ibex.classgen.CGConst
I've run the project many times before. Googling seems to relate to SQLlite, which I do use in the app, but is presumably wrapped with Android. Has anyone else run into this?


text:
Q: Save timestamps for REST in Offline App I am writing an app with offline capabilities, with a REST interface as my middleware.
It's about a timetracking system for employees.
The employees should be able start the timetracking, while their phone is offline. When the phone turns online, it should sync the time of the start/stop.
I'm using simple REST requests, which will be cached and send afterwards.
This REST contains a timestamp of the start/stop time for the timetracking.
Now the question:
How i can make sure, that the timestamp is not manipulated ?
Because it's a native app, i cant protect the REST interface by Access-Control-Origin.

A: simply encrypt the timestamp from client side. On your server side decrypt the timestamp if there is a decryption failure that means somebody has manipulated the payload.