Triangles area question

Question: This question came in RMO, an olympiad in India. I solved it but with the assumption that the lines are parallel, though we are not given this info in the question.

In acute $\triangle ABC$, let D be the foot of perpendicular from A on BC. Consider points K, L, M on segment AD such that AK= KL= LM= MD. Suppose the sum of the areas of the shaded region equals the sum of the areas of the unshaded regions in the following picture. Prove that BD= DC.

Taken from India Regional Mathematical Olympiad 2014 Question 1 of Region 1

Please help, thank you. This is not a homework question, just saying.
Comment: There are 3 line segments in the triangle that intersect the perpendicular AD. They do so at K,L,M respectively (from top to bottom). The line segments don't intersect each other but aren't given to be parallel.
Comment: From the provided links, found:-(1) The question was re-posted by an author known as "AnonymousBunny" in AoPS Forum. (2) He/she admitted (on Dec 07, 2014) the following "Umm, yeah, you're given that those lines are parallel (though that wasn't explicitly stated in the paper)."
Comment: In what way is it mentioned that they are parallel?
Comment: Someone proposed a solution for it by assuming the triangles are similar. Another person queried the validity of such assumption if there were no parallel lines. "AnonymousBunny" then gave the quoted reply. You can find that all out from AoPS.
Comment: @Ayan, have any of the answers below satisfied your curiosity about this question?
Answer: Assuming the lines are parallel with the base of the triangle.
Let's give names to the horizontal line segments in this fashion (forgive the poor visualization):
<code>      A
   a     e
   b     f
   c     g
B  d  D  h  C
</code>
Assuming the lines are parallel, and if we call the length of $AK = x$,
the size of the shaded area is:
$$ \frac{ax}{2} + \frac{(b+c)x}{2} + \frac{(e+f)x}{2} + \frac{(g+h)x}{2} = x\frac{a+b+c+e+f+g+h}{2} $$
and the size of the unshaded area is:
$$ \frac{ex}{2} + \frac{(a+b)x}{2} + \frac{(c+d)x}{2} + \frac{(f+g)x}{2} = x\frac{a+b+c+d+e+f+g}{2} $$
Since the description says these areas are equal,
we have:
$$ x\frac{a+b+c+e+f+g+h}{2} = x\frac{a+b+c+d+e+f+g}{2} $$
$$ a+b+c+e+f+g+h = a+b+c+d+e+f+g $$
$$ h = d $$
If we cannot make the assumption of parallel lines,
then I need to think harder.
Probably that's the whole point:
proving that if the shaded and unshaded areas are equal,
then the lines are inevitably parallel with the base,
and therefore $BC = BD$.
Comment: Yes as I said, with that assumption we can solve it easily using similarity, but I'm quite sure that this was not given in the question, and so we cannot assume so. Thanks though!
Answer: There is no way to prove that $\overline {BD}$ = $\overline {DC}$ without the assumption that the lines at K, L, and M are parallel to $\overline {BC}$
There simply is not enough information if we say that lines K, L, and M are not parallel.
to Support this answer I point to the Forum on the site where the question resides.
Dividing the altitude of a triangle into four equal parts
The Forum Post is labeled assuming that the lines are parallel even.
I would say that the assumption that the lines are parallel is a valid assumption given all the information that is available.
some posts from the forum:

@Bunny da :P : Are we given that those small triangles are similar? Or any such extra information about those small triangles?
Umm, yeah, you're given that those lines are parallel (though that wasn't explicitly stated in the paper). :P
Answer: The OP has stressed that the problem doesn't explicitly assume that the lines that pass through $AD$ at $K$, $L$, and $M$ are parallel, so that's the only issue I'm addressing in this answer.
I don't think the result is true if you don't make that assumption.  In particular, it's possible to create an extreme case where $B=D$:  Let the line at $L$ be perpendicular to $AD$, but slant the lines at $K$ and $M$ so that each shaded region has area equal to the unshaded region just below it.  (The line from $K$ will slant down to intersect the perpendicular from $L$ exactly on $AC$, producing two triangles of equal area.)
Added later:  If considering the extreme case isn't convincing, consider what happens if you shave a little bit from the left side of the (isosceles) triangle by moving to a point $B'$ just to the right of $B$.  It's easy to see that this shaves off more shaded region than unshaded, creating a momentary imbalance with more unshaded area than shaded in what remains.  But now if you tilt any of the three lines through $K$, $L$, or $M$ to an appropriate (slight) angle, you can clearly restore the balance.  So unless you make some assumption about those lines (e.g., that they are all parallel, or all perpendicular to $AD$), you cannot draw the conclusion that the problem requires.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/19328/discussion-between-malachi-and-barry-cipra).

Triangles area question


How to pass props into a component extracted from a component lookup using typescript?

Question: I am having a problem with typescript when attempting to pass props into and render a component which has been pulled out of a lookup.
The lookup is defined as:
type TableElements = {
  row: typeof DocumentRow | typeof ValuationRow;
};

const TableLookup: Record<string, TableElements> = {
  document: {
    row: DocumentRow,
  },
  valuation: {
    row: ValuationRow,
  },
};

I then use the tabletype (here it is declared as 'valuation') to pull the row component from the lookup:
const tableElements = TableLookup[tableType];
const TableRowComponent = tableElements.row;

I then try to render this component with:
{rows.map((row) => (
   <TableRowComponent
      rowData={row}
   />
 ))}

where "rows" is of type:
Array<RowDataType>

and RowDataType is of type:
type RowDataType = DocumentRowDataType | ValuationRowDataType;

but typescript gives me the error:
Type 'RowDataType' is not assignable to type 'DocumentRowDataType & ValuationRowDataType'.

I'm unsure why the type I am attempting to assign to is 'DocumentRowDataType & ValuationRowDataType'. I was expecting it to be 'DocumentRowDataType | ValuationRowDataType'
both DocumentRow and ValuationRow have a "rowData" prop, with one rowData being of type "DocumentRowDataType" and the other being "ValuationRowDataType".
"rows" is an array of RowDataType ('DocumentRowDataType | ValuationRowDataType') and each element of rows is assigned to either a DocumentRow or ValuationRow's rowData prop which can be either DocumentRowDataType or ValuationRowDataType, so I'm unsure why typescript isn't happy with this?
Would very much appreciate some help if anyone notices something I am missing, or if I'm misunderstanding something
Cheers
Answer: For anyone who is interested in this, I managed to fix this by explicitly giving a type to the TableRowComponent:
const TableRowComponent = tableElements.row as React.ComponentType<{
    rowData: RowDataType;
}>;


C++ Builder 11 - TCheckBox Scales When Form Scaled is False - Work around?

Question: I submitted a bug (RSP-30892) to Embarcadero over 1.5 years ago (since Rad Studio 10.4) regarding the following issue:
TCheckBox is scaling when it shouldn't when Windows 10 is set to 150% scaling. The form property is set to Scaled=false, the checkbox still scales 150%. Other controls conform to the form property.
While I have patiently waited for a fix on their end, it has yet to occur. I have tried to override the PixelsPerInch property of the control, but it is ignored.
The big question: Has anyone had any success with a work around, or, a way to override this behavior?
In case it is needed, here is how to reproduce:

Create VCL C++ Forms project.
Set form's "Scaled" property to false.
Add a TCheckBox to the form.
Apply a style to the application in the project options (like Windows 10 Dark).
Under project options->Packages, turn off dynamic RTL in linker. Turn off runtime packages.
Under project options->Application, Manifest, check Enable Runtime Themes and set DPI awareness to Per Monitor v2.
Run on a Windows with scaling set to 150%.
Answer: There is another bug report according to which this works as designed: https://quality.embarcadero.com/browse/RSP-24216
Scaled only affects the font size, not the boxes. To fully prevent scaling you must set DPI awareness to "None" in Options -> Application -> Manifest.
You have set the DPI awareness to "Per Monitor v2", which will not work.
When I set DPI awareness to "None", the entire form is scaled. So it seems there is intentionally no way to leave the form small.
Comment: Thanks for the response, however, the "Per Monitor v2" is a setting for the entire app. That setting works in 10.3 with the Form->Scaled set to false. 10.4 on up breaks this. Setting the entire app to "None" doesn't work anymore (as you said), and it is not a solution for apps that have mixed scaled forms. This is definitely a bug, not "as expected" - "closed" result given by Embarcadero in RSP-24216. Its like there is an erroneous GetSystemMetrics call when there shouldn't be? The glyph portions of TCheckBox and TRadio... scale. They shouldn't. Thanks though! I appreciate the attempt!


how to make a html page change background color acording to time

Question: I am making an asset for a digital signage (pi signage) to display the weather on a TV along with other stuff and I would like the page automatically switching to a 'dark mode' during night but my digital signage software doesn't let me add a folder so only the html file can by upload and use.
Can someone help me?
Because I am new to html code I tried to google the problem but couldn't find the answer other random stuff with any success
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title>Weather at Le thillay for piSignage</title>

    <link href="https://fonts.googleapis.com/css?family=Lato:100,300" rel="stylesheet"/>

So I would like the background line to change to something like:
background: linear-gradient(to top, rgb(102, 102, 102), rgb(43, 41, 41));
after the sunset an return to the blue gradient in the morning
Comment: Bro, this are 2 HTML-Docs in one file?
Answer: You can use javascript/jquery for it like this:
if(sunset == true){
  $('body').css({
    background: "linear-gradient(to top, rgb(102, 102, 102), rgb(43, 41, 41))"
  });
}else if(morning == true){
  $('body').css({
    background: "linear-gradient(to top, rgb(15, 45, 80), rgb(25, 134, 223))"
  });
}

you need to workout the logic for finding the sunset and morning ;)
Warning: Did not tested the code.


Page can only be seen by members with a certain rank

Question: In my members database I have a section called rank.
Basically what im trying to do is make certain pages viewable to members with a rank higher than 12 for example, and if the rank is lower than 12 then they are redirected back to the home page. (obviously their will be lots of different pages for rank 5+ members, Rank 7+ members, rank 20+ members etc)
Can anyone help me with a tutorial or something please?
I did ask for help earlier with my current code, but I dont think that code is ever going to work, Ive been changing it and playing with it for a week now and can not possibly see any other ways to get it to work Members Rank only area's
I am still learning php, So ideally a nice easy explaining tutorial would be nice.
Database:
id int(11)
username varchar(200) latin1_swedish_ci
password varchar(216) latin1_swedish_ci
security varchar(200) latin1_swedish_ci
email varchar(216) latin1_swedish_ci
ip varchar(200) latin1_swedish_ci
rank varchar(216) latin1_swedish_ci
name varchar(30) latin1_swedish_ci
age varchar(40) latin1_swedish_ci
gender varchar(40) latin1_swedish_ci
location varchar(40) latin1_swedish_ci
helpfaerie int(11)
profile text latin1_swedish_ci
about text latin1_swedish_ci
tasks text latin1_swedish_ci
joined varchar(216) latin1_swedish_ci
laston int(200)
icedmutereason text latin1_swedish_ci
icedmutedetails text latin1_swedish_ci
icedmuteby varchar(200) latin1_swedish_ci
icedmutedate int(200)
posts int(11)
signature varchar(216) latin1_swedish_ci
avatar varchar(216) latin1_swedish_ci
neohtml text latin1_swedish_ci
siggy text latin1_swedish_ci
verify int(11)
changedpass int(1)

Header.inc.php
<?php

include ($_SERVER['DOCUMENT_ROOT'].'/dblink.php');
include ($_SERVER['DOCUMENT_ROOT'].'/addon.php');

$geterror= $_GET['error'];

$error= stripplus($geterror);

$extra = mysql_fetch_array(mysql_query("SELECT * FROM extra WHERE id='1'"));

$cp = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE username = '$username'"));

$weather = $extra[weather];
$wurl = $extra[wurl];
$games = $extra[games];
$xword = $extra[xword];
$xword2 = $extra[xword2];
$xworddate = date("M j Y",$extra[xworddate]);
$userinfo = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE username='$username'"));
$rank = $userinfo[rank];

if (!$checkrank) { $checkrank = 0; }
if (!$rank) { $rank = 0; }
if (!$rank == ' ') { $rank = 0; }
if ($rank < $checkrank)
{

     header("Location: $baseurl/index.php?error=You+can+not+view+this+page.");
}

if ($rank >= 30)
{

    $admin = "Admin";
}

if ($username)
{

mysql_query("UPDATE members SET laston = $timestamp+120 WHERE username='$username'");

mysql_query("UPDATE members SET ip = '$ip' WHERE username='$username'");

    $login = "Welcome $username :) Logout";

$helpfaerie = "Help Faerie";

}

else
{
$login = "<form name=\"login\" action=\"$baseurl/login.pro.php\" method=\"post\"  > <input type=\"hidden\" name=\"act\" value=\"doLogin\" color=\"#000000\" valign=\"middle\" > Username: <input type=\"text\" name=\"username\" color=\"#000000\"  style=\"width:100px; height:20px;font-size:10px;\">
Password: <input type=\"password\" name=\"password\"  style=\"width:100px; height:20px;font-size:10px;\"> <input type=\"submit\" name=\"submit\" value=\"Login\" style=\"width:42px; height:20px;font-size:10px;\"></form>";

}

ECHO <<<END

and then the font.php
<?php
$pagetitle = "Add Font";

session_start();

// Rank Limit
       $limit = 10;

        // Using a session
    $rank = $_SESSION['rank'];

       // Using a cookie
       $rank = $_COOKIE['rank'];

    if ($rank < $limit) {
        header("$baseurl/index.php?error=You+can+not+view+this+page.");
        exit();
        die();
    }

include ($_SERVER['DOCUMENT_ROOT'].'/staff/header.inc.php');

ECHO <<<END

Answer: What you are looking for is an ACL (access control list) probably combined with authentication. An ACL will allow you to specify which resources a user with specific credentials has access to.
I have located a few tutorials, but this is not for the faint of heart.

http://phpmaster.com/role-based-access-control-in-php/
http://blog.davidjclarke.co.uk/database-driven-zend-acl-tutorial-part-one.html
http://www.developer.com/lang/php/creating-a-custom-acl-in-php.html

and maybe you could use a class from phpclasses to get you started:
PHPClasses ACL search result
Also as far as I know all of the popular frameworks have ACL and Authentication resources. (Zend Framework, Symfony, CakePHP).
Good luck!
Comment: @halfer, thanks for making it pretty. It's been a long night.
Answer: Since you have a rank field in your database you'll have to retrieve it with a query:
$user = mysql_fetch_array(mysql_query("SELECT rank FROM members WHERE username='$username'"));

after that you can check it and then you have to create a if/switch to manage the various rank and the logic behind it:
if(!is_array($user) || $user['rank'] < 12){
     header('Location: homepage');
} else {
 //manage page that only ranked user can have

}

bare in mind this is an easy and also "bad" solution becouse it will do a query every page you will access and for each user but it will give you the idea, you could work for a bit more complex version by using a login page that will store in session the rank and just retrieve it in each page to decide if the user can view it or not:
if(!isset($_SESSION['user_rank'] || $_SESSION['user_rank']<12)
    header('Location : defaultpage.php');

Comment: Where you've put {
 //manage page that only ranked user can have

} Do I just leave that? and then continue to the ECHO <<<END Page content css and html would be here
Comment: you should avoid putting content outside the else branch to avoid output that would interfere with the header() function. all the include/html should be inside it. Example: if ($rank < $limit) {
        header("$baseurl/index.php?error=You+can+not+view+this+page.");
        exit();
        die();
    } else {  echo HTML}


Update all rows in the PhpMyAdmin

Question: I want to change in the PhpMyAdmin the text "pelecard" for all fields that contain this text. the table name is sales_flat_order_payment. How I can do this?

thank you
Answer: What is with SQL?
<code>UPDATE sales_flat_order_payment SET method="123"
</code>
Then you change all fields to a new value. Without a where clause you change all entries.
Answer: Can also be done directly in phpMyAdmin. Open the table, choose "Search" then "Find and replace".

Update all rows in the PhpMyAdmin


Compound Replace of Floating Point Number with Double Quotes

Question: I have a problem with JSON strings flowing back and forth between PHP and javascript Ajax calls.  The PHP routines are sending JSON encoded strings without quotes around the floating point numbers, i.e.
{"Route_1":[{"lat":-31.526107395574975,"lng":146.31591796875},{"lat":-31.51674215813217,"lng":145.5303955078125}]}}

But when the JSON string is received by the ajax routine, all the floating point numbers have double quotes around them as shown here:
{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}

So after a couple of days trying to get to the bottom of it, I have decided the best course of action is just to parse this to remove the double quotes.   I can identify the floating point numbers and using .replace and callback.  but the compound replace is not working as I would expect it to - that is it is just returning the same string.
Can anyone shed some light on this please?  btw this is not the same issue as asking how to parse a JSON string.

var str = '{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}'

var regex = /[-+]?[0-9]*\.?[0-9]+/g;

var t = str.replace(regex, function(x) {
  return x.replace(/"/g, "");
})

console.log(t);
Comment: Why would you use regex when you have a perfectly servicable JSON you can convert to an object and then manipulate?
Comment: Possible duplicate of [How to parse a JSONArray and convert in Javascript](http://stackoverflow.com/questions/39398091/how-to-parse-a-jsonarray-and-convert-in-javascript)
Comment: Although it actually seems that _isn't_ valid JSON. However, my point stands - you want to do stuff with JSON - if you had one that is valid, you shouldn't need to regex it.
Comment: All my transfers are in JSON.  On the server side the code '$jsonArray =  json_encode( $json );' transfers the correct file but once on the client side the quotes are introduced - it has just proved too time consuming to try to untangle it.
Comment: The `str` parameter you have does not hold correct JSON as it is also quoting each object in the array. However, the _values_ in object being quoted is a trivial thing to change _correctly_ when you properly convert the JSON into a JavaScript object, as the linked question shows. It turns your question from "how do I regex this" to "how do I convert a string into a number" which is far safer, far easier and far better defined. Using a regex is both unnecessary and brittle, which makes it the wrong approach. Regex a golden hammer is not.
Comment: I fully agree with you regarding the soundness of staying within a particular environment, but when that environment is introducing all sorts of artefacts (PHP backslashes ) and double quotes your ability to fathom some reasoning and workarounds is difficult and is possible just as bad as introducing post processing.
Answer: You would need to match " as well in the regex. Check below update.

var str = '{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}';

var regex = /\"[-+]?[0-9]*\.?[0-9]+\"/g;

var t = str.replace(regex, function(x) {
  return x.replace(/"/g, "");
})

console.log(t);
Comment: 1. I disagree that regex is the correct tool for the job here. 2. That's still not correct JSON.
Comment: I am sorry for the error in the JSON.  I will correct it above.  The syntax error crept in when I was testing the JSON strings being sent from the client.  I was using double quotes to see if that was causing the problem.  The correct JSON is now shown.  Thanks


Download button not working on Shiny (Error in writexl::write_xlsx:)

Question: Could you help me adjust my Download button of the code below? As you will notice, I am generating a table by datatable. I would like to download this generated table, but when I press to download, I see that the console gives the following error:
Warning: Error in writexl::write_xlsx: Argument x must be a data frame or list of data frames[No stack trace available]

How can I adjust this in my code?
Executable code below:
library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(DT)
library(writexl)

function.test<-function(){

  df1 <- structure(
    list(date1= c("2021-06-28","2021-06-28","2021-06-28"),
         date2 = c("2021-07-01","2021-07-02","2021-07-03"),
         Category = c("ABC","ABC","ABC"),
         Week= c("Wednesday","Wednesday","Wednesday"),
         DR1 = c(4,1,0),
         DR01 = c(4,1,4), DR02= c(4,2,3),DR03= c(9,5,0),
         DR04 = c(5,4,0),DR05 = c(5,4,0),DR06 = c(5,4,0),DR07 = c(5,4,0),DR08 = c(5,4,0)),
    class = "data.frame", row.names = c(NA, -3L))

  return(df1)
}

f1 <- function(df1, dmda, CategoryChosse) {

  x<-df1 %>% select(starts_with("DR0"))

  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))

  med<-PV %>%
    group_by(Category,Week) %>%
    summarize(across(ends_with("PV"), median))

  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d+$"), ~.x +
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())

  SPV<-data.frame(SPV)

  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)

  (dropnames <- paste0(mat1,"_",mat1, "_PV"))

  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))

  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }

  datas <-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    summarize(across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c("Days","Numbers")

  datas <- datas %>%
    group_by(Category) %>%
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(Days)+1) %>%
    ungroup

  m<-df1 %>%
    group_by(Category,Week) %>%
    summarize(across(starts_with("DR1"), mean))

  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1

  maxrange <-  range(min(0, datas$Numbers, na.rm = TRUE), na.rm = TRUE)
  maxrange[2] <- maxrange[2] - (maxrange[2] %%10) + 35

  max<-max(0, datas$Days, na.rm = TRUE)+1

  plot(Numbers ~ Days,  xlim= c(0,max),  ylim= c(0,maxrange[2]),
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))

  if (nrow(datas)<=2){
    abline(h=m,lwd=2)
    points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,m+ .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(m))
  }

  else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){
    yz <- unique(datas$Numbers)
    lines(c(0,datas$Days), c(yz, datas$Numbers), lwd = 2)
    points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,yz+ .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(yz))
  }

  else{
    mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
    new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
    new.data <- rbind(0, new.data)
    lines(new.data$Days,predict(mod,newdata = new.data),lwd=2)
    coef<-coef(mod)[2]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(coef(model)[2]))
  }

}

ui <- fluidPage(
  ui <- shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),

                          tabPanel("PAGE 1",
                                   fluidPage(
                                     fluidRow(
                                       column(4,
                                              wellPanel(
                                                uiOutput('daterange'),
                                                downloadButton("dl", "Download"),
                                              )),
                                       column(8,
                                              tabsetPanel(
                                                tabPanel("Table", dataTableOutput('table')

                                                ))
                                       ))))))

server <- function(input, output,session) {

  data <- reactive(function.test())

  output$daterange <- renderUI({
    tagList(dateRangeInput("daterange1", "Period you want to see:",
                           min   = min(data()$date2),
                           max   = max(data()$date2)),

                           tags$script(HTML('
                setTimeout(function(){
                  $("#daterange1 input")[0].value = "No date selected";
                  $("#daterange1 input")[1].value = "No date selected";
                }, 50);
            ')))
  })

  data_subset <- reactive({
    req(input$daterange1)
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    df1 <- subset(data(), as.Date(date2) %in% days)
    df2 <- df1 %>% select(date2,Category)
    All <- cbind(df2, coef = apply(df2, 1, function(x) {f1(data(),x[1],x[2])}))
    All<-tidyr::pivot_wider(All, names_from = Category, values_from = coef)
    All<-All %>% mutate(date2 = format(ymd(date2), "%d/%m/%Y"))%>%
      mutate(sum = rowSums(across(2:last_col()), na.rm = TRUE)) %>%
      mutate(across(everything(), ~ replace_na(as.character(.), '-')))

   All<-datatable(All, options = list(columnDefs = list(list(className = 'dt-center', targets = "_all")),
    paging =TRUE,searching = FALSE, pageLength =  10,dom = 'tip',scrollx=T),rownames = FALSE) %>%
      formatRound(c(2:3), digits=0)

   All

  })

  output$table <- renderDataTable({
    data_subset()
  })

  output$dl <- downloadHandler(
    filename = function() { "data.xlsx"},
    content = function(file) {
      showModal(modalDialog("Wait", footer=NULL))
      on.exit(removeModal())
      writexl::write_xlsx(data_subset(), path = file)
    }
  )

}

shinyApp(ui = ui, server = server)

Table generated:
Answer: Do a reactive conductor data_subset that returns a dataframe/tibble, and apply the datatable stuff in renderDataTable:
data_subset <- reactive({
  req(input$daterange1)
  req(input$daterange1[1] <= input$daterange1[2])
  days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
  df1 <- subset(data(), as.Date(date2) %in% days)
  df2 <- df1 %>% select(date2,Category)
  All <- cbind(df2, coef = apply(df2, 1, function(x) {f1(data(),x[1],x[2])}))
  All<-tidyr::pivot_wider(All, names_from = Category, values_from = coef)
  All %>% mutate(date2 = format(ymd(date2), "%d/%m/%Y"))%>%
    mutate(sum = rowSums(across(2:last_col()), na.rm = TRUE)) %>%
    mutate(across(everything(), ~ replace_na(as.character(.), '-')))
})

output$table <- renderDataTable({
  datatable(
    data_subset(),
    options = list(
      columnDefs = list(
        list(className = 'dt-center', targets = "_all")
      ),
      paging = TRUE,
      searching = FALSE,
      pageLength = 10,
      dom = 'tip',
      scrollx=TRUE
    ),
    rownames = FALSE
  ) %>%
    formatRound(c(2:3), digits=0)
})


Error redirecting to failure page

Question: I have a form that takes in a few fields.
Upon entering all fields, email will be sent to me with the details.
If any fields are missing, the form will redirect to fail.html file.
If I select at least one of the select values, I get redirected to the fail.html page.
However, the issue is that if I don't select any of the select multiple dropdown list, I get this error.
Warning: implode() [function.implode]: Invalid arguments passed in /home/mydomain/public_html/iComm/contact.php on line 6
Warning: Cannot modify header information - headers already sent by (output started at /home/mydomain/public_html/iComm/contact.php:6) in /home/mydomain/public_html/iComm/contact.php on line 19
This is the HTML.

            <form method="post" action="contact.php">
            <input type="text" name="fullName" placeholder="Full Name">
            <input type="email" name="email" placeholder="Email Address">
            <input type="text" name="number" placeholder="Phone">

                <select multiple="multiple" name="choices[]">
                  <option style="color:grey";" value="Fri 8AM">Fri 20 Mar 8PM</option>
                  <option style="color:grey";" value="Sat 8AM">Sat 21 Mar 8AM</option>
                  <option style="color:grey";" value="Sat 2PM">Sat 21 Mar 2PM</option>
                  <option style="color:grey";" value="Sat 8PM">Sat 21 Mar 8PM</option>
                  <option style="color:grey";" value="Sun 8AM">Sun 22 Mar 8AM</option>
                </select>

            <input type="submit" class="button" value="Sign Up">
            </form>

This is the PHP file.

    $fullName= $_POST['fullName'];
    $email=$_POST['email'];
    $tel=$_POST['number'];
    $choice = implode(',', $_POST['choices']);

    if(!empty($fullName) && !empty($email) && !empty($tel) && !empty($choice)){
        $to = 'firstname.lastname@example.com';
        $subject = '2015';
        $msg = "$fullName is keen to join. His/her email address is $email and number is $tel. He/She chose $choice.";

        mail($to, $subject, $msg, 'From: ' .$email);

        header("Location: success.html");
        }
    else{
        if(empty($fullName) || empty($email) || empty($tel) || empty($choice)){
            header("Location: fail.html");
        }
    }
?>

Comment: So please read the error message: `$_POST['choices']` is probably empty or not an array
Answer: Check that $_POST['choices'] isset and is array and not empty and if it is - implode.
Second error will disappear too.
Comment: thanks for your help, i tried Khushboo's answer earlier
Answer: Use isset()
if(isset($_POST['choices'])) {  // This will check if this variable is set or not.
    $choice = implode(',', $_POST['choices']);
}

Answer: Use isset on the 'choices' post variable before trying to use it. You are also trying to pass header info when you have already output text to the browser (with the error probably).
Comment: thanks for your help, i tried Khushboo's answer earlier

Error redirecting to failure page


Is there a way to force drush to enable a module and ignore dependencies?

Question: I'm getting exception 'Drupal\Core\Config\UnmetDependenciesException' with messageConfiguration objects (....) provided by cn_migrator have unmet dependenciesin .../core/lib/Drupal/Core/Config/UnmetDependenciesException.php:84 when trying to enable a custom migration module. I've checked the dependencies listed in the YAML files and can't see anything missing. I really need to push ahead, but can't find a way to force enabling this module.
Comment: Have you tried enabling each of the modules listed as dependencies separately; and then enabling the module in question?
Answer: No, you can't.
But, https://www.drupal.org/node/2655104 was committed today, and it allows you to see what exactly is missing. Try patching your site with that to see the problem.
Comment: Thanks - I've been watching that thread but unfortunately I'm running 8.1.8. I can try the patch anyway...
Comment: Th issue has been going on for a while. If the latest patch doesn't apply, try an older version.
Comment: Thanks - the patch failed on the Test files but the actual code changes applied fine to the 8.1.8 core/lib


Showing a function is injective in a disk

Question: Please help me prove that if $f(z)=\sum_{n=0}^\infty a_nz^n$ is analytic in $D_r=\{z:|z|<r\}$ and $r|a_1|>\sum_{n=2}^\infty n|a_n|r^n$, then $f$ is an injective function in $D_r$.
Answer: Suppose $f(z_1) = f(z_2)$, $|z_1|, |z_2| < r$, then
$$
0 = |f(z_1) - f(z_2)| = |\sum_{n = 1}^\infty a_n(z_1^n - z_2^n)| = |z_1 - z_2||\sum_{n = 1}^\infty a_n\sum_{k = 0}^{n - 1}z_1^kz_2^{n - 1 - k}| \\
\geq |z_1 - z_2|(|a_1| - \sum_{n = 2}^\infty |a_n|\sum_{k = 0}^{n - 1}|z_1|^k|z_2|^{n - 1 - k}) = |z_1 - z_2|(|a_1| - \sum_{n = 2}^\infty n|a_n|r^{n - 1}),
$$
since $|a_1| - \sum_{n = 2}^\infty n|a_n|r^{n - 1} > 0$, so we have $|z_1 - z_2| = 0$, i.e. $z_1 = z_2$. Hence $f$ is injective.


Passar estado entre componentes sem hierarquia

Question: Estou fazendo um app todo list, e gostaria que ao clicar no botão edit o conteúdo aparecesse no campo onde adiciono meu novo item.
Mas a ação do botão e o estado são componentes irmãos.
AddTodo  (como passo o estado da AddTodo para a Todo ?)
import React, { Component } from "react";

export default class AddTodo extends Component {
  state = {
    content: ""
  };
  handleChange = e => {
    this.setState({ content: e.target.value });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.addTodo(this.state);
    this.setState({ content: "" });
  };
  // Como passar o estado dessa função ?
  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          Add new todo
          <input
            type="text"
            onChange={this.handleChange}
            value={this.state.content}
          />
        </form>

    );
  }
}

Todo
import React from "react";
import "./style.css";

const Todos = ({ todos, deleteTodo }) => {
  const todoList = todos.length ? (
    todos.map(todo => {
      return (

           {
              deleteTodo(todo.id);
            }}
          >
            {todo.content}

          <button
          class="btn-small orange lighten-1 right"
           id="btnEdit"
           onClick={() => {editTodo(todo.content)}}
           >
            edit
          </button>

      );
    })
  ) : (

Nothing todo, yay

  );
  return
{todoList}
;
};
export default Todos;

App
import React, { Component } from "react";
import Todos from "./Todos";
import AddTodo from "./AddTodo";

export default class App extends Component {
  state = {
    todos: [
      { id: 1, content: "learning Redux" },
      { id: 2, content: "buy some milk" },
      { id: 3, content: "play Mario kart" }
    ]
  };

  deleteTodo = id => {
    const todos = this.state.todos.filter(todo => {
      return todo.id !== id;
    });
    this.setState({ todos });
  };
  addTodo = todo => {
    todo.id = Math.random();
    const todoss = [...this.state.todos, todo];
    this.setState({ todos: todoss });
  };

  render() {
    return (

Todo list

        <Todos todos={this.state.todos} deleteTodo={this.deleteTodo} />
        <AddTodo addTodo={this.addTodo} />

    );
  }
}

Comment: Não, a idéia é essa mesmo. Creio que tem como passar direto, mas usando Hooks, acho que o UseContext faz isso, passa direto pra qualquer componente sem levar em consideração era hierarquia. Mas como vc tá usando Class Components creio que só assim mesmo, de pai pra filho.
Comment: Você pode controlar o estado no pai e passar uma função de `criarTodo` para um filho e a `listaDeTodos` para o outro filho. Vale ler [Quando usar contexto?](https://pt-br.reactjs.org/docs/context.html#when-to-use-context) e [Antes de você usar contexto](https://pt-br.reactjs.org/docs/context.html#when-to-use-context).
Comment: Estude Redux ou Context do `Reactjs`
Comment: Você só consegue passar props de componentes pais pra componentes filhos, diretamente entre irmãos não é possível, nesse caso você teria que passar de um filho, para o pai e do pai para outro filho.
Comment: Verdade, estou colocando no state do App um array para receber o estado do filho, já que App é o pai, agora falta fazer uma função que passa esse estado para filho AddTodo, porque esse AddTodo é um capo de inserir, a ideia é por o texto aí mesmo.
Ficou confuso ?
Comment: Fiz um exemplo com `Context` mas, é com React Hooks
Answer: Essa é uma forma de programar um elo entre componentes onde os mesmo compartilham dos mesmo dados e quando o botão incrementa ou decrementa são clicados a ação se programa para mostrar a variável de estado count nos que estão com essa variável do Context, exemplo:

const GlobalContext = React.createContext();
function GlobalProvider({children}) {
  const [count, setCount] = React.useState(0);
  const handleIncrement = () => setCount(count + 1);
  const handleDecrement = () => setCount(count - 1);
  return (
    <GlobalContext.Provider value={{count, handleIncrement, handleDecrement}}>
      {children}
    </GlobalContext.Provider>
  )
}

function Score() {
  const { count, handleIncrement, handleDecrement  } = React.useContext(GlobalContext);
  return (

{count}

    <button onClick={handleIncrement}>Incremento</button>
    <button onClick={handleDecrement}>Decremento</button>

);
}

function Actions() {
  const { count } = React.useContext(GlobalContext);
  return (
{count}
);
}

function App() {
  return (
    <GlobalProvider>
      <Score />
      <Actions/>
    </GlobalProvider>
  )
}

ReactDOM.render(<App/>, document.getElementById('root'));

nesse código exemplo é criado um contexto com React.createContext();e logo na próxima linha uma função para facilitar a criação do seu Provider e por fim dentro do <App /> foi envolvido dois componentes que compartilharam funções e dados desse Provider.


Como criar eventos em C#?

Question: Tenho duas classes uma que tem uma lista e gostava de ter um evento que toda a vez que essa lista fosse alterada esse evento fosse chamado.
public class Exemplo
{
    List<string> lista = new List<string>();
    //Quando esta lista foi alterada
}

public class Exemplo1
{
    protected virtual void QuandoListaAlterada(EventArgs e)
    {
        MessageBox.Show("Lista Foi Alterada");
    }
}

Answer: Explicação
Existe um tipo de collection no C# que notifica as alterações realizadas na lista através de eventos, a ObservableCollection.
Com ela, você poderá atribuir um método no evento CollectionChanged para receber as notificações de alteração na lista e também utilizar o evento PropertyChanged para receber notificações de alterações nas propriedades.
Exemplo
using System;
using System.Collections.ObjectModel;

namespace ObservableCollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            list.CollectionChanged += List_CollectionChanged;

            list.Add("Teste 1");
            list.Add("Teste 2");
        }

        private static void List_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Console.WriteLine("A lista foi alterada.");
        }
    }
}

Veja funcionando no DotNetFiddle
Answer: Uma das formas é extender a classe List adicionando um evento, desta forma:
    using System;
    using System.Collections.Generic;

    namespace teste
    {
        class Program
        {

            class ListaComEventos<T> : List<T>
            {

                public event EventHandler OnAdicionar;

                public void Adicionar(T item)
                {
                    if (OnAdicionar != null)//verifica se evento foi especificado
                    {
                        OnAdicionar(this, null);
                    }
                    base.Add(item);
                }

            }

            static void Main(string[] args)
            {
                ListaComEventos<int> minhaLista = new ListaComEventos<int>();
                minhaLista.OnAdicionar += new EventHandler(EventoAdicionar);
                minhaLista.Adicionar(1);
                minhaLista.Adicionar(1);
                minhaLista.Adicionar(1);
                Console.ReadKey();
            }

            static void EventoAdicionar(object sender, EventArgs e)
            {
                Console.WriteLine("Um elemento foi adicionado");
            }
        }
    }

Aqui está o código rodando no .netFiddle
Comment: Mas e se essa lista nao estiver declarado no main ?
Comment: Isso foi só um exemplo. Você pode declarar onde voce quiser, desde que a referência seja válida.

Como criar eventos em C#?


Goodness of fit test: question about Anderson–Darling test and Cramér–von Mises criterion

Question: I'm reading web pages for goodness of fit tests, when I came to the Anderson–Darling test and the Cramér–von Mises criterion.
So far I got the point; it seems the Anderson–Darling test and the Cramér–von Mises criterion are similar, just based on a different weighting function $w$. Also there's a variant of the Cramér–von Mises criterion named the Watson test.
Basically I have two questions here

There are not many Google results about these two methods; are they still state-of-the-art? or replaced by some better approaches already?
It's a bit of a surprise, as according to this paper on power comparisons of Shapiro–Wilk, Kolmogorov–Smirnov, Lilliefors and Anderson-Darling tests, AD is performing quite well; always better than Lilliefors and KS, and very close to the SW test, which is specifically designed for the normal distribution.
What is the confidence interval for such tests?
For the AD, CM and Watson tests, I saw the test statistics variable defined on the wiki pages, but didn't find the confidence interval.
Things are just more straightforward for the KS test: on the wiki page, the confidence interval is defined by $K_\alpha$, which is defined from the cumulative distribution function of $K$.
Answer: There can be no single state-of-the-art for goodness of fit (for example no UMP test across general alternatives will exist, and really nothing even comes close -- even highly regarded omnibus tests have terrible power in some situations).
In general when selecting a test statistic you choose the kinds of deviation that it's most important to detect and use a test statistic that is good at that job. Some tests do very well at a wide variety of interesting alternatives, making them decent default choices, but that doesn't make them "state of the art".
The Anderson Darling is still very popular, and with good reason. The Cramer-von Mises test is much less used these days (to my surprise because it's usually better than the Kolmogorov-Smirnov, but simpler than the Anderson-Darling -- and often has better power than it on differences "in the middle" of the distribution)
All of these tests suffer from bias against some kinds of alternatives, and it's easy to find cases where the Anderson-Darling does much worse (terribly, really) than the other tests. (As I suggest, it's more 'horses for courses' than one test to rule them all). There's often little consideration given to this issue (what's best at picking up the deviations that matter the most to me?), unfortunately.
You may find some value in some of these posts:
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
2 Sample Kolmogorov-Smirnov vs. Anderson-Darling vs Cramer-von-Mises (about two-sample tests but many of the statements carry over
Motivation for Kolmogorov distance between distributions (more theoretical discussion but there are several important points about practical implications)

I don't think you'll be able to form a confidence interval for the cdf in the Cramer-von Mises and Anderson Darline statistics, because the criteria are based on all of the deviations rather than just the largest.
Comment: ... e.g. We can say that popular tests like the Shapiro-Wilk (while very popular in testing normality) have competitors with broadly better power (e.g. see Shapiro&Chen 1995)-- but not in every situation. There's no single best choice of test (and hence, no actual 'state of the art'). Certainly I agree that what is best (state of the art) depends on circumstances --- that's the point of my answer; the possible answers are myriad - something good in one situation may be very poor in another. It pays to know when tests perform well rather than ask for "what's best" as if it were a single thing.
Comment: @Carl you may want to check a dictionary (or wikipedia) on what *state of the art* is usually taken to mean -- your interpretation of the phrase is not how most people read the phrase. Dictionaries say things like this: "*the most recent stage in development, incorporating the newest ideas*" and "*the highest level of development at a given time*" and "*cutting edge, using the latest technology*". In this context -- testing goodness of fit -- the phrase implies "the best we can possibly do right now". I insist that's not something you can really say about any single test. ... ctd
Comment: I took "state of the art" to mean something that finds use that is not obsolescent. The existence of multiple goodness-of-fit definitions should signal to us that goodness-of-fit is not a single concept. Consider that "good" depends on "why" we are performing regression. Suppose we are fitting Model A to data B to obtain a best predictor of effect C. Then "good" is the best predictor of C not B. However, most often the question of how B and C differ is ignored.
Comment: True, your definition is more correct. However, there are many more methods than tests of methods, and the "state of the art" is largely fiction, i.e., the "art" has no "state" all it has are protagonists. Any response to such a nebulous posit is equivocal. I said 'yes' and you said 'no' and we both said the same thing.
Comment: BTW, the question was "state of the art" or "replaced" which I took to mean "obsolete, or not obsolete".  So there was a context for my answer which context was "Please assume that 'state of the art' and 'replace' are antonyms, and please choose one of those." You are correct that those are not antonyms, I was answering in context and you chose to beg the question. So, mine was the polite answer. And, I am going to vote for your answer, because I think it informative, if not overly polite.
Comment: A little late to respond, but in any case, to clarify -- to "[beg the question](https://en.wikipedia.org/wiki/Begging_the_question)" is to assume what is to be proved. What I did was *deny the premise*. I'll wear the accusation of being impolite.
Comment: Good grief. A state can have numerous elements as in *thermodynamic state* and so too can the *state of the art.* Each element of the state of the art could have a different date of first application and the criterion is whether it is in current use, or not how splendorous or novel it is. True, people reach for the hyperbolic when they use the phrase, but that is connotative not intrinsic.
Answer: The Anderson-Darling test is not available on all distributions but has power that is good and close to the power for the Shapiro-Wilk test except for small numbers of samples so that the two are equivalent at $n=400$ Razali NM, Wah YB. Power comparisons of Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests. Journal of Statistical Modeling and Analytics. 2011;2:21-33. However, the Shapiro-Wilk test is only for normal distribution testing. The Cramér–von Mises test and Pearson Chi-squared are general for all distribution fits to histograms and I think that Cramér–von Mises test has more power than Pearson Chi-squared. The Cramér–von Mises test is often more powerful cumulative density function goodness-of-fit test than the Kolmogorov-Smirnov test for a broad class of alternative hypotheses see 1. and can have power greater or less than t-testing.  Chi-squared has difficulty with low cell counts, so range restrictions are used for fitting tails.
**Question 1: ... are ... these two methods... still state-of-the-art? or replaced by some better approaches already? Question 2 What is the confidence interval for such tests? **
Answer: They are state of the art. However, sometimes we want confidence intervals not probabilities. When comparing these methods to each other we speak of power rather than confidence intervals. Sometimes goodness-of-fit is analyzed using AIC, BIC and other criteria as contrasted to probabilities of good fitting, and sometimes the goodness-of-fit criterion is irrelevant, for example, when goodness-of-fit is not the criterion for fitting. In the latter case, our regression target may be a physical quantity not related to fitting, e.g., see Tk-GV.
(1) See, e.g., Section 5 in Stephens (1974) or page 110 in D'Agostino and Stephens (1986). Observe this is only empirical evidence for certain scenarios. Stephens, M. A. 1974. "EDF Statistics for Goodness of Fit and Some Comparisons." Journal of the American Statistical Association 69 (347): 730–37. https://doi.org/10.2307/2286009. D'Agostino, R. B., and M. A. Stephens, eds. 1986. Goodness-of-Fit Techniques. Vol. 68. Statistics: Textbooks and Monographs. New York: Marcel Dekker. https://www.routledge.com/Goodness-of-Fit-Techniques/DAgostino/p/book/9780367580346.
Comment: NB The Anderson-Darling test is a weighted version of the Cramer-von Mises test; &, like it, suitable for any continuous distribution.
Comment: *he Cramér–von Mises test is a more powerful cumulative density function goodness-of-fit test than the Kolmogorov-Smirnov test* is incorrect. One is more powerful against some alternatives, the other against other alternatives.
Comment: @RichardHardy Agreed. However, the information concerning tests that only apply to specific distributions and those that are more general is not in question. Certain general rules also apply, for example, a nonparametric test may apply to more distribution types at the cost of some sensitivity for each of them. So, it is not as if looking at the algorithms themselves was a waste of time, in fact, the devil in the details includes not only the data, but the algorithms themselves.
Comment: I think this has improved your answer. Thank you for taking the time!
Comment: @RichardHardy Thanks for your input, Richard. Can you provide some guidance as to when which is better?
Comment: @Carl, this is a very broad question and I do not have a brief answer to it. I am aware of some related threads on this site and some textbook treatment; I provide links [here](https://stats.stackexchange.com/questions/619491). But there is more out there in the wild. Normally, if I want to find examples of which test does best when, I look at the test statistic and see what triggers it, then construct an example. Different test statistics get triggered by different things, so these examples should illustrate which test is more powerful when.
Comment: con't The argument that we need to test specific circumstances for test applicability may be too vague to provide good guidance. For example, non-normality for similar datasets may be variable, with some testing as normal and others, obtained identically, as non-normal. That leaves us with only vague indications of when to use what, and I would rather say something vague, as above, than say nothing because of fear of being incorrect. There are no right answers in statistics, just educated guesses.
Comment: *I would rather say something vague, as above, than say nothing because of fear of being incorrect*. In my view, you said something very concrete (the bit I cited above) rather than vague. Otherwise, I would not have been able to identify the mistake so easily. And I would take vague and correct instead of concrete and incorrect any day.
Comment: @RichardHardy OK, made some changes to text with more references. I have changed "more" to "often more" and put in three references in a chain to that effect. This now agrees with what you said, even though I have never seen it myself.
Comment: @RichardHardy Actually, thank-you for your patience and attention to detail. I vastly prefer your having contributed the time, effort and courtesy of formulating a cautionary note to a downvote, as the latter does nothing to improve the answer and the former can. Would that more contributors were like you.
Comment: @Carl, I appreciate your kind words very much!


Regarding uniform convergence on [a, infinity)

Question: Show that if $a > 0$, then the convergence of $(e^{-nx})$ is uniform on the interval $[a, \infty)$ but not uniform on the interval $[0,\infty)$.
Let $f_n(x) = e^{-nx}$ and $f(x) = 0$ for all $x \in \Bbb R$.
I know that $(e^{-nx})$ converges pointwise to $0$ for all $x \in \Bbb R$ (this was the first part of this question).
By following the example in my textbook, I did the following:
Let $n_k = k$ and let $x_k = \frac{1}{k}$, then:
$f_{nk}(x_k) = \frac{1}{e}$
It follows that:
$|f_{nk}(x_k) - f(x_k)| = |\frac{1}{e} - 0| = \frac{1}{e} < \epsilon$
This shows that the convergence is NOT uniform on $[0, \infty)$ since there is no n corresponding to $\epsilon = \frac{1}{e}$... right?
What I don't know how to do is this - I'm not sure how to show it IS uniform for $[a,\infty)$.  I tried this:
$ 0 ≤ x ≤ a$
$\frac{1}{e^{nx}} ≤ \frac{1}{e^{na}} ≤ \frac{2}{e^{nx}} ≤ \epsilon$
But I'm not sure if this is what I'm supposed to do or not.
Thanks in advance for any help.
Answer: Notice that the function
$$f_n\colon x\mapsto e^{-nx}$$
is decreasing on $[0,\infty)$ so
$$\sup_{x\in[a,+\infty)}|f_n(x)|=e^{-na}\xrightarrow{n\to\infty}0$$
hence we have uniform convergence on the interval $[a,\infty)$ for all $a>0$.
Remark 1: You have a mistake in your answer: we have a pointwise convergence of $(f_n)$ only on the interval $[0,\infty)$ to the function $f$ defined by
$$f(0)=1\quad;\quad f(x)=0,\;\forall x>0$$
Remark 2:
Since $f$ isn't continuous on $[0,\infty)$ and the functions $f_n$ are continuous then the convergence isn't uniform on $[0,\infty)$.


Calculating complex numbers

Question: What is $(1-i)^{1+i}$ ?
I did:
$(1-i)^{1+i} = \left(e^{ln(1-i)}\right)^{1+i} = e^{(1+i)\cdot ln(1-i)} = e^{(1+i)\cdot [ ln\sqrt{2} + i\cdot(-\pi/4) + 2ki\pi ]}$
$ = e^{(ln\sqrt{2} + i\cdot(-\pi/4) + 2ki\pi)} \cdot e^{i\cdot(ln\sqrt{2} - \pi/4 + 2ki\pi)}$
This is it?
Comment: Related : http://math.stackexchange.com/questions/189703/does-ii-and-i1-over-e-have-more-than-one-root-n-0-2-pi
Comment: That looks fine though it mentions nothing about the choice of a branch (apparently the main one) for the complex logarithm.
Answer: HINT :
$$1-i = \sqrt{2}e^{-i\pi/4}$$
Then the calculations depend under which form your want it but here's another hint for later :
$$\sqrt{2}^{1+i} = \sqrt{2}\cdot2^{i/2} = \sqrt{2}\cdot e^{i\log(2)/2}$$
Answer: When you work with logarithms in the complex plane you have to be very careful. The logarithm cannot be defined in a good way on the whole complex plane (even if you remove the $0$). You have to chose a branch of log, that means choosing a particular definition of logarithm. I would take the principal branch (i.e. the one with imaginary part lying in $(-\pi,\pi)$ and which is undefined on $\mathbb{R}_{\le 0}$) and do it as follows:
$$(1-i) = \sqrt{2}\ e^{-i\frac{\pi}{4}}$$
(you can see why this is true e.g. identifying $\mathbb{C}$ with $\mathbb{R}^2$ and drawing the position of $(1-i)$ as a "vector" in this space). Then you get:
$$(1-i)^{1+i}=\left(\sqrt{2}\ e^{-i\frac{\pi}{4}}\right)^{1+i} = 2^{\frac{1+i}{2}}e^{-i\frac{\pi}{4}(1+i)}$$
This gives you:
$$2^{\frac{1+i}{2}} = e^{\frac{i}{2}\ln(2)}\sqrt{2}$$
$$e^{-i\frac{\pi}{4}(1+i)} = e^{-i\frac{\pi}{4}}e^{\frac{\pi}{4}}$$
and thus:
$$(1-i)^{1+i}=e^{-i\frac{\pi}{4}}e^{\frac{\pi}{4}}e^{\frac{i}{2}\ln(2)}\sqrt{2}=$$
$$(1-i)e^{\frac{\pi}{4}}\left(\cos\left(\frac{\ln(2)}{2}\right)+i\sin\left(\frac{\ln(2)}{2}\right)\right)$$
For more details on branches of log, try to give a look at this page.
Comment: Well, you *had* to work with the complex logarithm anyway, didn't you?
Comment: @DonAntonio Not really, I reduced the problem to the logarithm of a real number. I believe you know that trying to keep the number of logarithms of ("strictly") complex numbers to a minimum tends to avoid the confusion coming from having to choose a branch of log (in particular if you are not used to working like that).
Comment: The very second  equality in your second line of mathematics (the one with $\;(1-i)^{1+i}\;$ not only uses the complex logarithm but it also does so assuming a very particular branch for it, apparently the main one. I understand the problems with the complex logarithm, yet someone trying to answer a question like the OP's **has** to deal with it sooner or later, so I think it's better to do it sooner and warn the student about some of the problems here than dodge it.
Comment: @DonAntonio Ok, you win :) How should I edit my answer to make the point crear(er)?
Comment: It's not, of course, a matter of winning-losing, but only to remark to the OP some problems/aspects that may arise in his question. If you want to add something to your question you could probably mention that, trying to avoid as much the problematic you mention in your first line (and perhaps explaining a little *why* you think that about working with the comp. log.), you' try this or that approach, etc. Remarking that what the OP did is fine can also help, imo.
Comment: @DonAntonio Better?
Comment: Indeed so, @Daniel +1
Comment: Thank you very much; I just didn't get why "$(1−i)=\sqrt{2}  e^{−i \pi/4}$" this is true
Comment: @K.L. You probably have seen (else you will see it shortly) that $e^{i\phi} = \cos(\phi)+i\sin(\phi)$. Apply this to $\sqrt{2}\ e^{i\pi/4}$.

Calculating complex numbers


How add javascrip file to a node? (module)

Question: I have create a module who add a new node named SquareOffs. I make that in my squareoffs.info file.
I would like to add to that node a javascript file, squareoffs.js, but I don't know to do that.
I have seen the drupal_add_js() documentation but I don't know understand how it works, how can I add the js file to this node??
Thank you very much for  your answers or your sugestions!!
Answer: You can add your js through drupal_add_js() function. You can control on which pages this js should be added by implementing different hook and calling drupal_add_js() function in those hooks:
1) Use drupal_add_js() in hook_init() if you want to add this js on all drupal pages.
function mymoduel_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js');
}

2) Use drupal_add_js() in hook_node_view() with content type condition check if you want to add this js on only specific content types.
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'my_content_type') {
    $node->content['#attached']['js'][] = array (
      'type' => 'file',
      'data' => drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    );
  }
}

3) Use drupal_add_js() in module's preprocess function if you want to add this js only on specific node
function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 'your node nid') {
    // Add js
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.awesome.js');
  }
}

You can implement this preprocess_page at theme level like mytheme_preprocess_page($variable) in theme's template.php file.
Comment: `hook_init()` is no longer the way for global JS - you can [use the info file instead](https://www.drupal.org/node/756722#adding-javascript). Also your third example I think should be done in the same way as your second.
Comment: @Andy you are right i just want to give the more possible ways.
Comment: Thank you very much for your help and your keen explanation! It work's perfectly, and I have better understand how drupal works!
Answer: Yes. drupal_add_js() is used to add js in your theme or custom module.
I assume that the node has been fetched under this custom module.
If you want to add in your module. Use this
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/squareoffs.js');

The js file can be added as inline and external too.
For more details Click Here
Once the js file has been included, it will be applied to all the nodes under this custom module.
OR
If you want to add a js for particular content type. You can add preprocessor function in my custom module:
function mymodule_preprocess_node(&$vars) {
    if($vars['type'] == 'Nodetype') {
        drupal_add_js('drupal_get_path('module', 'mymodule') . '/js/squareoffs.js');
    }
}

Comment: You should really use [`#attached`](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached) rather than `drupal_add_js()` if you want the JS to be added every time the node's displayed (because this plays well with caching).
Comment: @Andy would you provide an example how to use `#attached` in `template_preprocess_node`? I've try to rewrite my preprocess function using #attached, and it won't load attached files after the node is cached, although it's working for the first page call.
Comment: @ЕлинЙ. `template_preprocess_node()` is too late, because it's after you've already started rendering the render array. `hook_node_view()` or `hook_node_view_alter()` seem like sensible places to add any attached resources.
Comment: Thanks @Andy, I've also just figured out that and put them into `hook_node_view()`. It works great :)
Answer: If you are working on developing a website, I suggest you to use JS injector Module and you can insert you jQuery/JavaScript into your website theme. To insert a jQuery, navigate to Configuration -> development -> Js Injector -> Add.
You can add your JScode as :
(function ($) { // your jquery goes here... })(jQuery);

If you are working on developing a module, go through this link and add your javaScript.


Coupon Collector Problem solving for expected completion percentage

Question: I'm working on a variation of the coupon collector problem and trying to make a formulaic solution in Excel without using a user-defined function.
Basically, the gist of the problem is that at a variable number of attempts (t), and I already have a number of coupons collected (n) of the total coupons (x), I'm trying to solve for expected completion percentage (P.) The formula needs to be able to handle different values of t, n, and x,
In short:

I have t attempts to pull my coupons
I have n coupons already collected
There are x coupons in total
Knowing those variables, I'm solving for P - expected completion percentage

What is the formula to define expected completion percentage?
P = ?
EDIT: Basically, the coupon collector problem solution I have is this:
Normal coupon collector solution:
p = n$\sum\limits_{k=1}^n$ $\frac 1k$
EDIT2:
Simply phrased, I want x-n coupons. I have t tries to get those coupons. What is my expected completion percentage after those t tries?
Comment: You write the words "expected completion percentage" five times without ever saying what they mean. The formula you gave is the expected number of times you will have to draw a coupon in order to collect one of every kind, so it doesn't seem to be much use when you have a fixed number of drawings.
Comment: Sorry if I was confusion - "expected completion percentage" would be the 'expected number of coupons obtained, that I wanted' within those attempts. And I am quite aware my base formula isn't of much use, I included it to show my starting point. For example, if I pulled "3 out of 4" of the coupons I wanted in 274 trials, my 'expected completion percentage' would be 75%.
Answer: For each of the $x-n$ coupons you do not already have:

the probability of drawing it on the next attempt is $\frac{1}{n}$
the probability of not drawing it on the next attempt is $1 - \frac{1}{n}$
the probability of not drawing it on any of the next $t$ attempts is $\left(1 - \frac{1}{n}\right)^t$

So overall, since expectation is linear, after $t$ attempts

the total number you expect not to draw is $(x-n)\left(1 - \frac{1}{n}\right)^t$
the total number you expect to have (including the starting $n$) is $x-(x-n)\left(1 - \frac{1}{n}\right)^t$
the total proportion number you expect to have is $\dfrac{x-(x-n)\left(1 - \frac{1}{n}\right)^t}{x}$


How to select rows that have all values in a collection of IDs

Question: The title may not be very descriptive on what I need. I have a table with product_id and store_id columns. I need a way to get all Stores (store_id) that have a collection of product_ids (they need to have ALL products I want). Example:
+------------+----------+
| product_id | store_id |
+------------+----------+
|        10  |       1  |
|        20  |       1  |
|        10  |       2  |
|        20  |       2  |
|        30  |       1  |
|        30  |       3  |
|        20  |       3  |
+------------+----------+

I want to select all stores that have products 10, 20 and 30 (all of them).
In this example, only store 1 has all 3 products. The other two stores (2 and 3) only have two products, not all 3.
I want to build a query that will return ONLY the store_ids that have all products in stock.
I'm trying something like this, but this is logically not exactly what I need.
SELECT st.product_id, GROUP_CONCAT(DISTINCT st.store_id SEPARATOR ",")
AS store_ids
FROM stock_table AS st
WHERE st.product_id IN (10,20,30)
GROUP BY st.product_id

Answer: You can check if  the count of product_id is 3
SELECT st.product_id, GROUP_CONCAT(DISTINCT st.store_id SEPARATOR ",") AS store_ids store
FROM stock_table AS st
WHERE st.product_id IN (10,20,30)
GROUP BY store
having count(distinct st.product_id) = 3

this was the Original answer
SELECT st.product_id, GROUP_CONCAT(DISTINCT st.store_id SEPARATOR ",") store
AS store_ids
FROM stock_table AS st
WHERE st.product_id IN (10,20,30)

GROUP BY store
having count(distinct product_id) = 3

Comment: hello! many thanks for such quick answer... option 1 seems to do the trick! however I also tried option 2 (HAVING COUNT) and here I think I'm missing something... it doesn't seem to work... any clues?
Comment: btw, I think you accidentally deleted your original answer about using AND and not IN
Comment: i have update the answer  with the original answer  too but there is not an AND  .. anyway  check better you data sample  .. the query posted  should return product_id 1  .. or you data sample is different respected  the posted  one ..
Comment: no.. your code does not work I'm afraid.. HOWEVER, if I change the GROUP BY clause, and I use "store_id" instead of product_id as the group by, it seems to work. am I right?


Processamento de pagamentos para mais de uma API

Question: Estou desenvolvendo um site que busca reservas de passagens aéreas através da API do Decolar.com e busca hotéis pela API do Booking.com.
Minha dúvida é, tem como eu unificar o processo de pagamento? Por exemplo, o usuário paga uma única vez (valor total de hotel+voo) e é repassado para o processador de pagamentos dessas plataformas.
Answer: Você pode usar uma terceira API que recebe o pagamento dos seus clientes como PagSeguro ou Mercadopago. Assim você recebe o valor total, e faz os pagamentos no momento em que a API acusar a conclusão da transferência.


Dal Segno al Coda and repeats in Guitar Pro

Question: Why do D.S. al Coda and Dal Segno with separate al Coda, work differently in Guitar Pro when al Coda is at the end of repeat? D.S. al Coda skips the last repeat.

Here the performance is as thought. Repeats at bars 1-2, 3-4 and 5-8, then Dal Segno and repeats at bars 1-2, 3-4 and then to Coda at bar 9.

Here the performance differs. Repeats at bars 1-2, 3-4 and 5-8, then Dal Segno and repeats at bars 1-2 but not at bars 3-4. It jumps right after bar 4 to Coda at bar 9.
Comment: 1) I'm surprised it repeated at bar 2 after having done the D.S. I'm used to all repeats being overlooked when taking a D.S. (or is that only for D.C.?) 2) Your "segno" is at the beginning of the work, so it isn't needed. You can use D.C. 3) Are you creating this just as a way to get the playback to do certain things? If so, do whatever works. If the notated music matters, though, besides the unnecessary Segno, you'll want to use a Bb instead of A# in the first line (or actually change key signatures as you go from F to G to A).
Comment: To Andy, this is just practice to check how repeats, segnos, codas, da capos, fines work on Guitar Pro 7.5. Since Guitar Pro doesn't "teach" music, it has to be learned by practice. As I've learned about repeats they must be done first, before anything else. So, the difference between these 2 examples is something I'd like to know. For me, it's obvious that you always do a repeat before a da Coda, if it's written there. If the music theory is that you don't do a repeat when you are at Da Coda, then there is a bug with Guitar Pro. So, which is it?
Comment: I'm used both to absolutely no repeats done after D.C./D.S. and to "To Coda" instead of "Da Coda".
Comment: I have also never seen a standalone "Dal Segno" before. That looks pretty unorthodox to me.
Comment: To Dekkadeci, OK - if that is the music theory, then there's a bug with Guitar Pro software. It's confusing to use D.C., D.S. if the repeats should ignore when they exist there, though. And, in Guitar Pro, there's no a To Coda. It's only Da Coda - which should mean the same. And - the markings come from the software. And - while writing this comment - I tried both: D.C. al Coda and Da Capo with separate Da Coda. The performance is exactly same as it is with the examples above.
Answer: There are still several questions here (though related enough that it counts as one).

Is there a logical inconsistency in Guitar Pro's treatment of these repeats? Yes. If, after using the "Dal Segno" to go back to the beginning, it observed the repeat in m. 2, then it should also have observed the one in m. 4. If it didn't observe m. 4 it shouldn't have observed m. 2. This doesn't surprise me much; I haven't used Guitar Pro, but it seems to me to be rather under-featured as a notational tool. If you need to do a lot of writing I might turn to another piece of notation software.
Should you observe repeats after a Da Capo or Dal Segno? This is a little bit trickier. The overwhelming convention is, no, you should not. If a D.S. or D.C. sent you back to an earlier section of music, you should ignore repeats (which you would have observed the first time you encountered them). This source helps explain (note, wherever it talks about "first endings," the same is true for simple repeats), and the topic has been covered here as well (don't let the OP's initial confusion confuse you). So the "bug" in GuitarPro would appear to be that it observed the m. 2 repeat after the Dal Segno.
The plot thickens because occasionally composers or conductors ask for exceptions to this rule. Context also matters; in the Minuet-Trio movement of a Mozart symphony, the "skip the repeats" rule is even more ironclad—unless some director has a pet theory or bit of evidence suggesting that in this one case it isn't. If the composer intends repeats to be observed, they had better communicate it in writing.
Not asked, but a reasonable follow-up is: When writing music, how can I best make the repeats and sections clear to the performers? First of all, write out anything that's reasonably short without using any kind of directions. I understand that the example above is mocked up for demonstration purposes, but if the repeated material is only a few bars, it's better to simply write it twice than to make the reader jump backwards and forwards on the page. Even a simple D.C., D.S., Coda combination is deadly to sight-reading (and many worse mutations roam the wild). Performers are left hurriedly turning pages and scanning. In rehearsal, they make the impossible possible only by "decorating" the music with sticky notes, highlighters, and giant arrows (or perhaps colorful language).
If absolutely forced to use such directions (to navigate large sections), learn and follow standard conventions.
Comment: Thanks for your comment Andy. This clears a lot. Well, why I use the Guitar Pro? 1. It's a tons cheaper than for example Sibelius. 2. It has RSE (Realistic Sound Engine) for guitar band music and it makes an .mp3 file from the whole band's sheets. So, it's such easy to listen a song before look into the sheet. And 3. It's also a guitar tablature sheet, which is easier for those who do not understand notations. I've seen a lot of the sheets other people have done with GP and they are written almost without repeats and other directions, which means tens of pages to flip during rehearsals.
Comment: @KariHelander Good point, there is such a thing as too *little* use of space-saving directions too. By the way, It's not uncommon, no matter what the tool, to get the score ready for humans to read and then make other changes, not destined for print, to tweak the behavior of the audio that's generated. (For that, it might even be easiest to export the midi and work in a DAW.) Like, if it lets you, you might just replace the "Da Coda" with a bit of free text saying "to Coda," but reinstate the "Da" when bouncing the audio.


aligning horizontally using css

Question:

<!DOCTYPE html>

Floating box

Floating box

Guys, I have this and I want to align the text with the box horizontally, how can I do that?
Comment: Please use the search next time, this question has been asked many times before.
Comment: If you want to center align the floating-box then use  width:150px; margin:0 auto;
Answer:

<!DOCTYPE html>

Floating box

Floating box

Answer: If you want to align the "Floating Box" text inside that box.
.floating-box{
  text-align: center;
}

If you want to align the whole box horizontally relative to the body of the page.
.floating-box{
  display: block;
  margin: 10px auto;
}

Or you could do both as per the following snippet.

<!DOCTYPE html>

Floating box

Floating box

Comment: i want to align the outside text (h2) with thw whole box horizontally
Comment: I'm sorry, I'm confused. Could you provide a small illustration of what you're after? You want both items to be on the same line and aligned horizontally?

aligning horizontally using css


Escrever na planilha a partir da ultima linha sem sobescrever

Question: Estou tentando escrever em uma planilha de excel a partir da última linha escrita sem apagar o conteúdo que já existia, eu já consegui pegar qual a última linha e escrever a partir dela, porém quando eu escrevo apaga o que estava anteriormente. Usei uma IDE para gerar minhas telas e adaptei um exemplo que achei na internet para escrever na planilha, além disso usei a JEXCEL API do java.
Segue classes utilizadas:
Tela com a tabela:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
    initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jTextField1 = new javax.swing.JTextField();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3"
        }
    ));
    jScrollPane1.setViewportView(jTable1);

    jTextField1.setText("jTextField1");

    try {
        jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }

    jButton1.setText("Exportar");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(80, 80, 80)
                        .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addComponent(jFormattedTextField1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addContainerGap(19, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Excel e = new Excel();
    String aux = e.m(jTextField1.getText(), jTable1, jFormattedTextField1.getText());
    if (!aux.equals("")) {
        int i = JOptionPane.showConfirmDialog(null, "Deseja abrir o arquivo?", "", 0);
        if (i == 0) {
            File file = new File(aux);
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar abrir o arquivo.\n" + ex.getMessage(),
                        "Erro na Exportação", 2);
            }
        }
    }
}

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

Tela de selecionar local para salvar:
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class BuscaArquivo extends javax.swing.JDialog {

private String diretorio;//DECLARA VARIÁVEL QUE IRÁ RECEBER O DIRETÓRIO DO ARQUIVO SELECIONADO
private FileNameExtensionFilter fileFilter = null;

public String getDiretorio() {
    return diretorio;
}

public BuscaArquivo(java.awt.Frame parent, boolean modal, String nome, String[] tipo, String suge) {
    super(parent, modal);
    initComponents();
    jFileChooser1.setCurrentDirectory(new File("C://"));//DEFINE O DIRETÓRIO INICIAL QUE IRÁ ABRIR A TELA
    jFileChooser1.setSelectedFile(new File(suge));//SUGERE NOME PARA ARQUIVO
    if(tipo[0].equals(""))
        jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    else{
        fileFilter = new FileNameExtensionFilter(nome, tipo);
        //INSTANCIA OBJETO QUE FILTRA AS EXTENSÕES
        jFileChooser1.setFileFilter(fileFilter);//DEFINE FILTRO DE EXTENSÕES ACEITAS
    }
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jFileChooser1 = new javax.swing.JFileChooser();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jFileChooser1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jFileChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jFileChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//DEFINE QUE A TELA IRÁ PEGAR APENAS O DIRETÓRIO DOS ARQUIVOS
    try {//CLAUSULA TRY PARA TRATAMENTO DE EXEÇÃO
        if(fileFilter == null){
            if(!jFileChooser1.getSelectedFile().getAbsolutePath().substring(jFileChooser1.getSelectedFile().getAbsolutePath().length() - 1).equals("\\"))
                diretorio = jFileChooser1.getSelectedFile().getAbsolutePath() + "\\";
            else
                diretorio = jFileChooser1.getSelectedFile().getAbsolutePath();
        }
        else
            diretorio = jFileChooser1.getSelectedFile().getAbsolutePath();//INSERE NA VARIÁVEL 'diretorio' O DIRETÓRIO DO ARQUIVO SELECIONADO
        this.setVisible(false);
        this.dispose();//ENCERRA A TELA
    } catch (NullPointerException e) {
        this.setVisible(false);
        this.dispose();//ENCERRA A TELA
    }
}

// Variables declaration - do not modify
private javax.swing.JFileChooser jFileChooser1;
// End of variables declaration
}

Classe que escreve planilhas do excel:
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class Excel {

public String m(String t, JTable jt, String data) {
    try {
        String[] aux = new String[2];
        aux[0] = "XLS";
        aux[1] = "xls";
        data = data.replaceAll("/", "");
        BuscaArquivo ba = new BuscaArquivo(null, true, "XLS", aux, "TABELA - " + data);
        //TELA PARA ESCOLHER ONDE SERÁ SALVO O ARQUIVO
        ba.setVisible(true);
        String filename;
        if (ba.getDiretorio() != null) {//EXECUTA CASO ALGUM DIRETÓRIO TENHA SIDO SELECIONADO
            filename = ba.getDiretorio();
            if(!filename.contains(".xls"))
                filename = filename + ".xls";//COMPLETA CAMINHA CASO NÃO TENHA SIDO DIGITADO O .xls
            if(new File(filename).exists()){//SE O ARQUIVO JÁ EXISTIR
                Workbook workbookAux = Workbook.getWorkbook(new File(filename));
                Sheet sheet = workbookAux.getSheet(0);//PEGA A ULTIMA LINHA DA PLANILHA
                int linha = sheet.getRows();
                WorkbookSettings ws = new WorkbookSettings();
                ws.setLocale(new Locale("pt", "BR"));
                WritableWorkbook workbook
                        = Workbook.createWorkbook(new File(filename), ws);
                WritableSheet s = workbook.createSheet("Folha1", 0);
                writeDataSheet(s, t, jt, linha);
                workbook.write();
                workbook.close();
            } else{
                WorkbookSettings ws = new WorkbookSettings();
                ws.setLocale(new Locale("pt", "BR"));
                WritableWorkbook workbook
                        = Workbook.createWorkbook(new File(filename), ws);
                WritableSheet s = workbook.createSheet("Folha1", 0);
                writeDataSheet(s, t, jt, 0);
                workbook.write();
                workbook.close();
            }
            return filename;
        } else {
            return "";
        }
    } catch (IOException | WriteException | BiffException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Erro Ao Gravar", 0);
        return "";
    }
}

private static void writeDataSheet(WritableSheet s, String t, JTable jt, int linha)
        throws WriteException {

    /* Formata a fonte */
    WritableFont wf = new WritableFont(WritableFont.ARIAL,
            10, WritableFont.BOLD);//DEFINE COMO NEGRITO
    WritableCellFormat cf = new WritableCellFormat(wf);
    cf.setWrap(false);

    /* Cria um label e escreve um float numver em uma célula da folha*/
    Label l = new Label(0, linha, t, cf);
    s.addCell(l);

    cf = new WritableCellFormat(wf);
    cf.setBorder(Border.ALL, BorderLineStyle.THIN);//DEFINE BRODA

    for (int i = 1; i < jt.getColumnCount(); i++) {
        l = new Label(i - 1, linha + 1, jt.getColumnName(i), cf);
        s.addCell(l);
    }

    wf = new WritableFont(WritableFont.ARIAL,
            10, WritableFont.NO_BOLD);
    cf = new WritableCellFormat(wf);
    cf.setBorder(Border.ALL, BorderLineStyle.THIN);

    linha += 2;
    //TRECHO PARA ESCREVER TODA A TABELA NA PLANILHA
    for (int i = 0; i < jt.getRowCount(); i++, linha++) {
        for (int j = 1; j < jt.getColumnCount(); j++) {
            l = new Label(j - 1, linha, jt.getValueAt(i, j).toString(), cf);
            s.addCell(l);
        }
    }
}
}

Answer: Como eu já tinha pegado a planilha e colocado na variável sheet eu só reescrevi o que eu já tinha antes de começar a escrever a próxima parte.
Não sei se é a melhor forma de se fazer, mas foi como eu consegui.
Segue trecho de código adaptado em que eu pego a última linha:
            if(new File(filename).exists()){//SE O ARQUIVO JÁ EXISTIR
                Workbook workbookAux = Workbook.getWorkbook(new File(filename));
                Sheet sheet = workbookAux.getSheet(0);
                int linha = sheet.getRows();//PEGA A ULTIMA LINHA DA PLANILHA
                WorkbookSettings ws = new WorkbookSettings();
                ws.setLocale(new Locale("pt", "BR"));
                WritableWorkbook workbook
                        = Workbook.createWorkbook(new File(filename), ws);
                WritableSheet s = workbook.createSheet("Folha1",0);
                for(int i=0 ; i<linha ; i++){
                    for(int j=0 ; j<sheet.getColumns() ; j++){
                        if(!sheet.getCell(j, i).getContents().equals("")){//EXECUTA APENAS SE ACHAR ALGUM VALOR
                            Label l = new Label(j, i,
                                    sheet.getCell(j, i).getContents(), sheet.getCell(j, i).getCellFormat());
                            //PEGA TODA CONFIGURAÇÃO DA CÉLULA
                            s.addCell(l);
                        }
                    }
                }
                writeDataSheet(s, t, jt, linha);
                workbook.write();
                workbook.close();
            }


How to send JSON data created by Python to JavaScript?

Question: I am using Python cherrypy and Jinja to serve my web pages. I have two Python files: Main.py (handle web pages) and search.py (server-side functions).
I create a dynamic dropdown list (using JavaScript) based on a local JSON file called component.json(created by function componentSelectBar inside search.py).
I want to ask how can my JavaScript retrieve JSON data without physically storing the JSON data into my local website root's folder and still fulfil the function of dynamic dropdown list.
The componentSelectBar function inside search.py:
def componentSelectBar(self, brand, category):
    args = [brand, category]
    self.myCursor.callproc('findComponent', args)
    for result in self.myCursor.stored_results():
        component = result.fetchall()
    if (len(component) == 0):
        print "component not found"
        return "no"

    components = []
    for com in component:
        t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
        components.append(t)

    j = json.dumps(components)
    rowarraysFile = 'public/json/component.json'
    f = open(rowarraysFile, 'w')
    print >> f, j

    print "finish component bar"
    return "ok"

The selectBar.js:
    $.getJSON("static/json/component.json", function (result) {
        console.log("retrieve component list");
        console.log("where am i");
        $.each(result, function (i, word) {
            $("#component").append("<option>"+word+"</option>");
        });
    });

Comment: Basically, you need a handler to be marked with @cherrypy.tools.json_out decorator returning dict/list. Just change the URL in JS, and that's it.
Your question currently contains too many information, which doesn't look related to the problem. Please, consider reducing its size and providing only minimum amount of code to not confuse readers.
Answer:
store results from componentSelectBar into database
expose new api to get results from database and return json to browser

demo here:
@cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
    ...
    result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
    # here store result into a database, for example, brand_category_search_result
    ...

@cherrypy.expose
@cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
    # load json from that database, here is brand_category_search_result
    a_json = loadSearchResult(category, brand)

    return a_json

document on CherryPy, hope helps:
Encoding response
In your broswer, you need to GET /getSearchResult for json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
    console.log("retrieve component list");
    console.log("where am i");
    $.each(result, function (i, word) {
        $("#component").append("<option>"+word+"</option>");
    });
});

Answer: To use that json data directly into javascript you can use
var response = JSON.parse(component);
console.log(component); //prints

OR
You already created json file.If that file is in right format then you can read json data from that file using jQuery jQuery.getJSON() For more: http://api.jquery.com/jQuery.getJSON/
Comment: Yeah, you are correct. I can use the local JSON file, and it works fine. But now I want to improve the process, I mean I do not want to store the JSON file locally, and the JavaScript can still retrieve my JSON data from Python. Something like `return json.dumps(components)`, but I do not know how to implement it with JavaScript.
Answer: You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.
def componentSelectBar(self, brand, category):
    /* Your code goes here */
    j = json.dumps(components)
    // Code to add a persistent store here
    rowarraysFile = 'public/json/component.json'
    f = open(rowarraysFile, 'w')
    print >> f, j
    // Better to use append mode and append the contents to the file in python
    return j //Instead of string ok

@cherrypy.expose
def codeSearch(self):
    json_request = cherrypy.request.body.read()
    import json # This should go to the top of the file
    input_dict = json.loads(json_request)
    modelNumber = input_dict.get("modelNumber", "")
    category = input_dict.get("category", "")
    brand = input_dict.get("brand", "")
    /* Your code goes here */
    json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
    return json_response

Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the componentSelectBar function. That will help you keep the codeSearch function as plain as possible and help in a long run(read maintaining the code).
And I would suggest you to read PEP 8 and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.
EDIT: This is a sample javascript function that will make a post request and get the JSON response:
searchResponse: function(){
  $.ajax({
    url: 'http://localhost:8080/codeSearch', // Add your URL here
    data: {"brand" : "Levis", "category" : "pants"}
    async: False,
    success: function(search_response) {
      response_json = JSON.parse(search_response)
      alert(response_json)
      // Do what you have to do here;
      // In this specific case, you have to generate table or any structure based on the response received
    }
  })
}

Comment: Sorry I still do not know how to using this JSON data in JavaScript after I return the JSON data in _main.py_. Would you mind show me how to use the return JSON data in JavaScript to create the dynamic dropdown list?
Comment: Sure. I will update the answer with a sample JS function that will get the JSON data :)
Comment: Added a sample JS function. By this way, you will receive the JSON response. But then, you have to render it with JavaScript to display the output in required format.
Comment: If I return `json_response` in my `main.py`, I won't be able to load my web page, right? Instead, the JSON data will appear, which is not what I want.


$S^{1}\times (0, 1)$ admits a single smooth chart?

Question: I would like to know if this assertion is true and, in case it is, how to proceed. I already proved that $S^{1}\times [0,1]$ can't be covered by a single chart. But I get stuck in this case.
Edit: as my idea was wrong, I deleted it, so people that look for it won't be confused.
Thanks, for any help.
Answer: The map \begin{align}\phi:\Bbb R^2\setminus\{0\}&\to S^1\times(0,1)\\ x&\mapsto \left(\frac{x}{\lVert x\rVert},\frac1\pi\operatorname{arccot}(-\ln \lVert x\rVert)\right)\end{align}
is a diffeomorphism. Its inverse is $(\omega,t)\mapsto e^{-\cot(\pi t)}\omega$.


Rope / Ropemacs - Auto Import feature

Question: I'm using Rope and Ropemacs to transform my emacs as a IDE for Python. I have a problem with the rope-auto-import feature. I read in the doc that I must add modules that I want to autoimport like this:
(setq ropemacs-autoimport-modules '("os" "shutil"))

But I want to autoimport all modules installed on my computer. How can I specify this?
Answer: I miss the same feature but unfortunately it is not possible to tell rope/ropemacs to enable autoimport for all modules. You have to manually add the modules to the ropemacs-autoimport-modules variable.
See the last messages of this thread:
http://groups.google.com/group/rope-dev/browse_thread/thread/6d4778e7bedc096d

Rope / Ropemacs - Auto Import feature


What do the tiny yellow RC cars next to the javelin throwing field do?

Question: When they measure the distance of javelin throws during the European Athletics Championships in Amsterdam, there are small yellow remote controlled cars driving around.
Here is a screenshot of them.

What are the yellow cars used for?
Answer: They are collecting the javelins (and other projectiles) for athletes:

Over eight million TV viewers across Europe watched the remote control 1:5 scale model Volvo XC90 collect javelins, discuses and hammers for the athletes at the European Athletic Championships in Gothenburg last week.

emphasis added
Note that the article linked above is reporting on the 2006 Gothenburg event, so this practise has obviously stood a test of time!
Comment: I can add this [video from London 2012](https://www.youtube.com/watch?v=fzz-zKcmom0) where the mini car is working
Comment: While the shot put can use gravity-assist to roll the implements back the relatively short distance to the athletes (shot puts are generally won with distances on the close order of 21m at the pro level), the javelin/discus/hammer throws all travel much farther, necessitating such a tool.