Differential Equation Math Puzzle

Question: Dog race:
Edit 2:
I posted a possible answer below. However, I am unsure how the authors arrived at the solution.
Maybe someone can offer an explanation.
Four dogs are positioned at the corners of a square ($d= 1m$), chase each other in clockwise direction with the same constant speed . As their target is moving, they will follow a curved path, eventually colliding in the center of the square.

(a) Why is the total length of the path just $1 m$?
(b) Find and solve a differential equation for the radius $r(\theta)$ in polar coordinates.
This is a homework question! I just want hints, no solutions please.
The tough part is setting up an equation for the radius i.e for the motion of one of the dogs. I was thinking about an equation similar to that of an archimedean spiral.
$$r(\theta)=a+b\theta \space \space \space \text{or} \space \space \space r(\theta)=a\theta^{\frac{1}{n}}$$
However, I have no idea what values $a$ or $b$ should be. Any hints are appreciated.
Edit 1:
This is my second attempt at a solution:
If Dog 1 is positioned at $(r, \theta)$ $\implies$ Dog 2 is positioned at $(r, \theta+\frac{\pi}{2})$
Picture:

$$x_1=r \cos (\theta) \\ y_1= r \sin (\theta) \\ \\ \\ x_2=r \cos (\theta+\frac{\pi}{2})=-r \sin(\theta) \\y_2=r \sin (\theta+\frac{\pi}{2})=r \cos (\theta)$$
If these are the two position vectors then the vector joining the two points is my velocity vector.
$$\implies \frac{dy}{dx}=\frac{y_2-y_1}{x_2-x_1}=\frac{r \sin (\theta+\frac{\pi}{2})-r \sin (\theta)}{r \cos (\theta+\frac{\pi}{2})-r \cos (\theta)}=\frac{ \sin (\theta+\frac{\pi}{2})- \sin (\theta)}{ \cos (\theta+\frac{\pi}{2})- \cos (\theta)}=\frac{\cos(\theta)-\sin(\theta)}{-  \sin(\theta)-\cos(\theta)}$$
Am I on the right path? But How do I deduce $\dfrac{dr}{d\theta}$?
Comment: Your attempt tries to short-circuit the entire problem by giving a finished _parameterization_ of the curve. That's not what (b) asks you to do -- it says you must set up a _differential equation_ for the curve first and solve that. In other words, what you should do _first_ is come up with something that invoves $\frac{dr}{d\varphi}$ (where $\varphi$ is presumably the same as what you call $\theta$ in your attempt).
Comment: Also it looks like you're still trying to do too much too soon. The part about letting the dog continue blindfolded for half the distance doesn't seem to give you any progress -- it's as if you're _still_ trying to bypass the differential equation stage and find the shape of the _entire_ path, instead of just aiming for the differential equation. What you need to ask is: what is the dog's velocity vector **now**? Not where it will be at some point in the future -- reserve that for _after_ you have a differential equation and have solved that.
Comment: By the way, are the dogs assumed to be pointlike? Real dogs take up space that would be a significant fraction of the one-meter square arena, causing uncertainty in the precise direction each dog is moving in when it "chases" the next, and making them collide much before their centers (whatever that is) coincide.
Comment: @Henning Makholm Thanks for your answer. I will try doing that. But at the moment the only thing I can see is that $\frac{dr}{d\theta}$ must be negative since the radius is decreasing. I think we can assume that the dogs are pointlike. I will try to find some sort of differential equation and come back if i found/can't find anything.
Comment: x @SuH: You need to use the information that each dog is moving straight towards the next dog. If you draw a sketch of a typical moment during the race, you ought to see that this is the same as "the dog's trajectory must make a 45° angle with the radius", which you ought to be able to work into an expression for $\frac{dr}{d\varphi}$.
Comment: @HenningMakholm Thanks for the hint. I will draw some diagrams and try to extrapolate an expression. I am not sure if I understand the 45° angle part but I will try to figure it out. Can I ask you again later in case I don't get anywhere?
Comment: Try drawing a diagram that includes all the dogs, lines between each pair of neighboring dogs, and (straight) lines from each dog to the center.
Comment: x @SuH: Your diagram does not show the radius lines. Without having those lines in your diagram, you have no hope of seeing what the angle between the radius line and the (instantaneous) heading of the dog is!
Answer: For part (a), you don't have to parameterize anything, really, or set up any complicated differential equations.  All you have to do is show that, thinking of yourself as one of the dogs, the dog you're chasing is always running at right angles to your line of sight and therefore, since your speed is constant and directed straight at the target, you are getting closer at a constant rate -- in short, as far as the time to overtake it is concerned, the dog you're chasing may as well not be moving at all, which is to say you'll catch it in the time it takes to travel $1$ meter.
Comment: Thanks for your answer. I know you are right (because I have seen the answer) but I have a hard time getting my head around the fact that the total distance a dog has to chase is just 1 meter. It seems to me that the distance could be 1.01 meters or 1.3 meters etc..
Comment: @SuH, you are quite right that there are concepts here that can be hard to get your head around, but it's well worth making the attempt, because the same kind of reasoning can help in understanding a lot of other problems.
Answer: Here is a solution for (b):
Let
$$t\mapsto z(t)=r(t)e^{i\phi(t)}\qquad(t\geq0)$$ be the orbit of the dog starting at ${1\over2}(1+i)$. Then the orbit of the dog starting at ${1\over2}(-1+i)$ is simply $t\mapsto iz(t)$. It follows that at any moment the velocity vector $$\dot z=(\dot r+i r\dot\phi)e^{i\phi}$$ is parallel to $$iz-z=(-1+i)z=(-1+i)r e^{i\phi}\ .$$ This amounts to
$$\dot r+ir\dot\phi=\lambda(-r+ir)\tag{1}$$
for some $\lambda>0$ changing with time. Comparing the imaginary parts in $(1)$ we see that in fact $\lambda=\dot\phi>0$, so that from looking at the real parts we obtain $\dot r=-r\dot\phi$, or
$${dr\over d\phi}={\dot r\over\dot\phi}=-r\ .$$
It follows that the function $\phi\mapsto r(\phi)$ satisfies the differential equation
$$r'=-r\ ,$$
with the solutions $r(\phi)=r_0 e^{-(\phi-\phi_0)}$. This implies that we see four logarithmic spirals.
Comment: +1: It's been quite a while since I had anything to do with differential equations (and I didn't like it much), but reading your exposition was delightful. Thanks!
Comment: Thank you very much for your answer.
Answer: First off: I don't know how to do this problem the way they are asking. But I think I can do this problem my own way. Maybe this will be a hint enough for you to do it the original way.
Let's track the top dog (starts at $(0,1)$). Let its position at time $t$ be $(x(t),y(t))$. By symmetry, the dog it is chasing is at position
$$(u(t),v(t)) = (\frac{x(t) + y(t)}{\sqrt{2}},\frac{-x(t) + y(t)}{\sqrt{2}})$$ which is just the original position rotated by 45 degrees.
The speed of chase is a constant $s$ but the direction is from $(x(t),y(t))$ to $(u(t),v(t))$ so the velocity vector is
$$(\dot{x}(t),\dot{y}(t)) = s\frac{(u(t)-x(t),v(t)-y(t))}{|(u(t)-x(t),v(t)-y(t))|}$$
Can you change to polar coordinantes and take it from there?
Comment: Thanks for your answer. I think I have some sort of idea what to do now. I will post my post my answer if I get somewhere.
Answer: This answer is taken from Calculus 10th Edition by Larson and Edwards
Link to solution: Solution
This is how they derive the differential equation:
If a dog is located at $(r, \theta)$ in the first quadrant, then its neighbor is at $(r, \theta+ \frac{\pi}{2})$
$$(x_1,y_1)=(r \cos\theta, r \sin\theta)
\\(x_2,y_2)=(-r\sin\theta,r\cos\theta)$$
The slope joining these points is
$$\frac{r\cos\theta-r\sin\theta}{-r\sin\theta-r\cos\theta}=\frac{\sin\theta-\cos\theta}{\sin\theta+\cos\theta}=\text{slope of tangent line at} (r,\theta)$$
$$\color{}{\frac{dy}{dx}=\frac{\frac{dy}{dr}}{\frac{dx}{dr}}=\frac{\frac{dr}{d\theta}\sin\theta+r\cos\theta}{\frac{dr}{d\theta}\cos\theta-r\sin\theta}=\frac{\sin\theta-\cos\theta}{\sin\theta+\cos\theta}}$$
$$\color{blue}{\implies \frac{dr}{d\theta}=-r}$$
Comment: They're using chain rule to at first. i.e. $$ \frac{ dx}{d\theta} \frac{ dy}{dx} = \frac{ dy}{d\theta} $$  and computing the derivatives using $x(\theta) = r(\theta) \cos \theta$ and $y(\theta = r(\theta) \sin \theta$.
Comment: @Jeb I am sorry but I don't get it. Wouldn't I use the product rule to differentiatie $x(\theta)$ and $y(\theta)$?

$$\implies \frac{dx}{d\theta}=\frac{dr}{d\theta}\cos\theta -r\sin\theta \\ \frac{dy}{d\theta}=\frac{dr}{d\theta}\sin\theta +r\cos\theta$$

but how does that equal:

$$\frac{\sin\theta-\cos\theta}{sin\theta+\cos\theta}$$
Comment: because the ratio is $\frac{dy}{dx}$ which is the slope of the tangent line at $(r,\theta)$, and you've computed that already. Then you can simplify the expression to isolate $\frac{dr}{d\theta}$
Comment: @Jeb It's getting really late at my place so I will give it a rest for today. I will come back tomorrow and try to complete the problem. Thank you very much for your help.

Differential Equation Math Puzzle


and Ajax

Question: I am using Ajax on a CFC file. I can't get the result from the function that I am calling from Ajax. I set a debug message (Alert()), but can't see it. Any suggestion?
function getDelegateChartAcct(LocFund){
   alert("#Arguments.PIUniversalID#");
   alert($F("DelegateFund"));

  new Ajax.Request( "?method=displayDelegateChartAcct",
            {
              parameters : {
                            PIUniversalID: "#Arguments.PIUniversalID#",
                            PILocFund: $F("DelegateFund")
                            },
                            method : "post"
                             }
               );
     }

     <cffunction name="displayDelegateChartAcct" access="remote" output="true"
      returntype="void">
          <CFArgument name="PIUniversalID" type="string" required="true" />
          <CFArgument name="LocFund" required="true" type="String" />

      <CFSET var chartacctlist = runChartAcctDelegationQuery
                  (#Arguments.PIUniversalID#, #Arguments.LocFund#)>

        <CFContent type="text/x-javascript">
          alert("Hi");
          //      delegateChartAcctList();
          //      $("DelegateChartAcct").
           //     <CFOutput query="chartacctlist">
            //     $("DelegateChartAcct").insert( new Element(
                    "option", { value : "#JSStringFormat( chart_acct )#", selected :
            //        "selected" } ).update( "#JSStringFormat( chart_acct )#" ) );
            //                            </CFOutput>

            </cffunction>

Thanks,
Kefang
Comment: returntype="void" specifically tells your cfc to return nothing.
Answer: You are not returning anything from the CFC (and you can't run JavaScript inside the function you are calling remotely, either).
You have 2 ways you can handle this:

Load the form (or element) you want by making a remote call to a .cfm file that builds the form (or element) you want. You can use $("{place form will be displayed}").load("{url to .cfm page}) and jQuery will make an HTTP request adn load the result in the DOM element that matches the selector.
Change your CFC to return the query and populate the select box on the client side using JavsScript. (This is what I would do)

Your code would look like this:
<cffunction name="displayDelegateChartAcct" access="remote" output="true" returntype="query">
      <cfargument name="PIUniversalID" type="string" required="true" />
      <cafrgument name="LocFund" required="true" type="String" />

  <cfset var chartacctlist = runChartAcctDelegationQuery (#Arguments.PIUniversalID#, #Arguments.LocFund#)>
    <cfreturn chartacctlist />
</cfcomponent>

You could then use the following to load that data (looks like Prototype based on the syntax):
new Ajax.Request( "?method=displayDelegateChartAcct&returnFormat=json",
    {
        parameters : {
            PIUniversalID: "#Arguments.PIUniversalID#",
            PILocFund: $F("DelegateFund")
        },
        method : "post",
        onSuccess: function(response) {
                // code in here will populate select
        }
     }
 );

The 'returnFormat=json' tells ColdFusion to return the results as JSON.
You would just need a JS handler to take that data and use it to populate the SELECT box.

and Ajax


Integration among Shiny Flexdashboard and shinyAmBarCharts

Question: I'm trying to insert a shinyAmBarCharts chart within a flexdashboard with Shiny runtime. The final goal would be to use the modifiable chart as an input to other charts/models.
So far I've been unsuccessful, because the amBarChart does not render in the dashboard. This is a sample code:
---
title: "shinyAmBarCharts"
output:
  flexdashboard::flex_dashboard:
  orientation: columns
  vertical_layout: fill
 runtime: shiny
---

 ```{r setup, include=FALSE}

 library(flexdashboard)
 library(shiny)
 library(shinyAmBarCharts)
 library(tidyr)

set.seed(666)
df0 <- data.frame(
species = rep(c("sorgho","poacee","banana","triticum"), each = 3),
condition = rep(c("normal", "stress", "Nitrogen"), 4),
 value = rpois(12, 10)
 )
df1 <- spread(df0, condition, value)

output[["data"]] <- renderPrint({
input[["mygroupedbarchart"]]
 })

 output[["change"]] <- renderPrint({ input[["mygroupedbarchart_change"]] })

```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

 ```{r}
 fluidPage(

       amBarChart(
         "mygroupedbarchart", data = df1, height = "400px",
         category = "species", value = c("normal", "stress", "Nitrogen"),
         valueNames = c("Normal", "Stress", "Nitrogen"),
         minValue = 0, maxValue = 20,
         draggable = c(FALSE, FALSE, TRUE),
         theme = "dark", backgroundColor = "#30303d",
         columnStyle = list(fill = c("darkmagenta", "darkred", "gold"),
                            stroke = "#cccccc",
                            cornerRadius = 4),
         chartTitle = list(text = "Grouped bar chart",
                           fontSize = 23,
                           color = "firebrick"),
         xAxis = list(title = list(text = "Species",
                                   fontSize = 21,
                                   color = "silver"),
                      labels = list(color = "whitesmoke",
                                    fontSize = 17)),
         yAxis = list(title = list(text = "Value",
                                   fontSize = 21,
                                   color = "silver"),
                      labels = list(color = "whitesmoke",
                                    fontSize = 14)),
         columnWidth = 90,
         caption = list(text = "[font-style:italic]shinyAmBarCharts[/]",
                        color = "yellow"),
         gridLines = list(color = "whitesmoke",
                          opacity = 0.4,
                          width = 1),
         tooltip = list(text = "[bold;font-style:italic]{name}: {valueY}[/]",
                        labelColor = "#101010",
                        backgroundColor = "cyan",
                        backgroundOpacity = 0.7)
       )
       )
```

 Column {data-width=350}
  -----------------------------------------------------------------------

 ### Chart B

 ```{r}

        verbatimTextOutput("data")

  ```

 ### Chart C

 ```{r}
       verbatimTextOutput("change")

 ```

that I have basically copied from these places:

https://github.com/stla/shinyAmBarCharts
Draggable interactive bar chart Rshiny.

I' ve tried the inline shiny-app solution from the flexdashboard web page (https://rmarkdown.rstudio.com/flexdashboard/shiny.html#inline_applications), but in this case I do not know how to re-use the changes made to the chart as an input to other part of the flexdashboard.
Any help would be much appreciated.
Answer: I started to do a new package, rAmCharts4, which allow to generate HTML widgets displaying some charts produced by version 4 of the amcharts JavaScript library. Currently only two types of chart are available: the vertical bar chart and the horizontal bar chart. More types of chart will be available in the future. The charts can be displayed in Shiny, and the integration in Flexdashboard works:

---
title: "rAmCharts4"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(rAmCharts4)
library(tidyr)

set.seed(666)
df0 <- data.frame(
  species = rep(c("sorgho","poacee","banana","triticum"), each = 3),
  condition = rep(c("normal", "stress", "Nitrogen"), 4),
  value = rpois(12, 10)
)
df1 <- spread(df0, condition, value)

output[["mygroupedbarchart"]] <- renderAmChart4({
  amBarChart(
    height = "400px",
    data = df1,
    category = "species", values = c("normal", "stress", "Nitrogen"),
    valueNames = list(normal = "Normal", stress = "Stress", Nitrogen = "Nitrogen"),
    minValue = 0, maxValue = 20,
    draggable = list(normal = TRUE, stress = FALSE, Nitrogen = TRUE),
    theme = "dark", backgroundColor = "#30303d",
    columnStyle = list(
      fill = list(
        normal = "darkmagenta", stress = "darkred", Nitrogen = "gold"
      ),
      stroke = "#cccccc",
      cornerRadius = 4),
    chartTitle = list(text = "Grouped bar chart",
                      fontSize = 23,
                      color = "firebrick"),
    xAxis = list(title = list(text = "Species",
                              fontSize = 21,
                              color = "silver"),
                 labels = list(color = "whitesmoke",
                               fontSize = 17)),
    yAxis = list(title = list(text = "Value",
                              fontSize = 21,
                              color = "silver"),
                 labels = list(color = "whitesmoke",
                               fontSize = 14)),
    columnWidth = 90,
    caption = list(text = "[font-style:italic]rAmCharts4[/]",
                   color = "yellow"),
    gridLines = list(color = "whitesmoke",
                     opacity = 0.4,
                     width = 1),
    tooltip = amTooltip(
      text = "[bold font-style:italic]{name}: {valueY}[/]",
      textColor = "#101010",
      backgroundColor = "cyan",
      backgroundOpacity = 0.7
    )
  )
})

output[["data"]] <- renderPrint({
  input[["mygroupedbarchart"]]
})

output[["change"]] <- renderPrint({
  input[["mygroupedbarchart_change"]]
})
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
fluidPage(

  amChart4Output("mygroupedbarchart", width = "100%", height = "100%")

)
```

Column {data-width=350}
-----------------------------------------------------------------------

### Chart B

```{r}
verbatimTextOutput("data")
```

### Chart C

```{r}
verbatimTextOutput("change")
```

Installation: devtools::install_github("stla/rAmCharts4")

Update
The above code is not valid anymore. Please see the package documentation. There are now five available types of chart.


Using imageWithContentsOfFile: to load textures in spritekit

Question: So, I noticed this recommendation in one of the discussions here.
It says that in order to release memory once you done with the textures, a possible solution will be the next:

create UIImages with +imageWithContentsOfFile:
create SKTextures from the resulting UIImage objects by calling SKTexture/+textureWithImage:(UIImage*).

I have memory issues that comes from the high res backgrounds and few embedded scroll views, so I tried the above implementation - and it works in terms of memory.
The problem is that it looks like when doing so, imageWithContentsOfFile: in retina devices,  scales the @2x image by 2, so I need to explicit scale it again by 0.5.
How can I ensure the right scaling when calling this method?
Here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:@"sc_01_bg" ofType:@"png"];
UIImage *img = [UIImage imageWithContentsOfFile:path];
SKSpriteNode *backgroundSprite = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImage: img]];

Answer: Actually, there is only upvote on that answer, and that upvote is mine. I can't remember now why I have upvoted that answer, because I've never experienced such problem.
If you still want to use the approach stated in that answer, you should use [UIImage imageNamed:@"imageName"] instead of [UIImage imageWithContentsOfFile:path]. Probably, UIKit doesn't automatically handle retina/non-retina images with imageWithContentsOfFile: method.
But basically you don't need that. Check LearnCocos2D's answer for that question.
PS: To free up a memory that have been used by SKScene just call
[self.skView removeFromSuperview];
self.skView = nil;

Comment: The problem is "imageNamed:" cached the texture. I am not sure it is a good idea to work with few skviews, at list from what I read.
Comment: What do you mean by saying "I am not sure it is a good idea to work with few skviews"?


Parse xml in Python 3.x

Question: I have some xml code I wish to parse. I wish to use ElementTree and not BeautifulSoup as I am having some issues with the latter the way it handles the xml.
I wish to extract the text from the following:

Abstract/AbstractText
ArticleId when IdType="pmc"
PublicationType with 'UI' value to be retrieved first before retrieving the corresponding text

Which functions of ElementTree do I use to do the work?
I have been trying to use .attrib, attrib.get(), .iter, .attrib[key] to get the text but I have not been successful in accessing the actual text.
<PubmedArticleSet>
   <PubmedArticle>
       <PMID Version="1">10890875</PMID>
       <Journal>
           <ISSN IssnType="Print">0143-005X</ISSN>
            <Title>Journal of epidemiology and community health</Title>
       </Journal>
       <ArticleTitle>Sources of influence on medical practice.
       </ArticleTitle>
       <Abstract>
          <AbstractText Label="OBJECTIVES" NlmCategory="OBJECTIVE">
             To explore the opinion of general practitioners on the
             importance and legitimacy of sources of influence on
             medical practice.
          </AbstractText>
          <AbstractText Label="METHODS" NlmCategory="METHODS">
             General practitioners (n=723) assigned to Primary Care
             Teams (PCTs) in two Spanish regions were randomly selected
             to participate in this study.
          </AbstractText>
          <AbstractText Label="RESULTS" NlmCategory="RESULTS">
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues.
          </AbstractText>
          <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting. </AbstractText>
        </Abstract>
        <Language>eng</Language>
        <PublicationTypeList>
           <PublicationType UI="D016428">Journal Article
           </PublicationType>
           <PublicationType UI="D013485">Research Support, Non-U.S.Gov't </PublicationType>
        </PublicationTypeList>
    <PubmedData>
         <PublicationStatus>ppublish</PublicationStatus>
         <ArticleIdList>
            <ArticleId IdType="pubmed">10890875</ArticleId>
            <ArticleId IdType="pmc">PMC1731730</ArticleId>
         </ArticleIdList>
     </PubmedData>
   </PubmedArticle>
</PubmedArticleSet>

What I am hoping to get as a result is:
       generating every "label" of AbstractText
       getting the text for that "label"
Comment: Can you please add an example of your desired output?
Answer: Try the following code with Css Selector.
from bs4 import BeautifulSoup

html='''<PubmedArticleSet>
   <PubmedArticle>
       <PMID Version="1">10890875</PMID>
       <Journal>
           <ISSN IssnType="Print">0143-005X</ISSN>
            <Title>Journal of epidemiology and community health</Title>
       </Journal>
       <ArticleTitle>Sources of influence on medical practice.
       </ArticleTitle>
       <Abstract>
          <AbstractText Label="OBJECTIVES" NlmCategory="OBJECTIVE">
             To explore the opinion of general practitioners on the
             importance and legitimacy of sources of influence on
             medical practice.
          </AbstractText>
          <AbstractText Label="METHODS" NlmCategory="METHODS">
             General practitioners (n=723) assigned to Primary Care
             Teams (PCTs) in two Spanish regions were randomly selected
             to participate in this study.
          </AbstractText>
          <AbstractText Label="RESULTS" NlmCategory="RESULTS">
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues.
          </AbstractText>
          <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting. </AbstractText>
        </Abstract>
        <Language>eng</Language>
        <PublicationTypeList>
           <PublicationType UI="D016428">Journal Article
           </PublicationType>
           <PublicationType UI="D013485">Research Support, Non-U.S.Gov't </PublicationType>
        </PublicationTypeList>
    <PubmedData>
         <PublicationStatus>ppublish</PublicationStatus>
         <ArticleIdList>
            <ArticleId IdType="pubmed">10890875</ArticleId>
            <ArticleId IdType="pmc">PMC1731730</ArticleId>
         </ArticleIdList>
     </PubmedData>
   </PubmedArticle>
</PubmedArticleSet>'''

soup = BeautifulSoup(html, 'lxml')

maintag=soup.select_one('Abstract')
for childtag in maintag.select('AbstractText'):
    print(childtag.text.strip())

print(soup.select_one('ArticleId[IdType="pmc"]').text)

Output:
To explore the opinion of general practitioners on the
             importance and legitimacy of sources of influence on
             medical practice.
General practitioners (n=723) assigned to Primary Care
             Teams (PCTs) in two Spanish regions were randomly selected
             to participate in this study.
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues.
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting.
PMC1731730

Answer: In general, I have had great use of the .find()-method for looking through XML-files that have been parsed with ElementTree. And then for whatever you find, you can use the element.text, element.attrib and element.tag to get text, a dictionary of attributes and the element name respectively.
Combine that with list comprehension, and it sounds like that's what you're looking for.
As an example, let's say you have the xml-file saved as 'publications.xml':
import xml.etree.ElementTree as ET

filename = 'publications.xml'
content = ET.parse(filename)
root = content.getroot()

abstracts = [a.text for a in root.find('PubmedArticle/Abstract')]

will give you a list of the text in the 4 abstracts.
Accessing all the ID's can be done in a similar way, adding the check for the correct IdType. By the method mentioned above, you can similarly get the list of all elements with name 'ArticleId' and then access the IdType using
element.attrib['IdType']

for each element in the given list.
For the last request, I'm not entirely sure what you mean by retrieving UI-value first. If you just want to make sure that you retrieve both values, you can loop through all the elements in
root.find('PubmedArticle/PublicationTypeList')

and save both element.attrib['UI'] and element.text

Parse xml in Python 3.x


If $A+B+C=\pi$, prove: $\cos(B+2C)+\cos(C+2A)+\cos(A+2B)=1-4\cos\frac {B-C}{2}\;\cos\frac {C-A}{2}\;\cos\frac {A-B}{2}$

Question:
If $A+B+C=\pi$, prove that:
  $$\cos(B+2C)+\cos(C+2A)+\cos(A+2B)=1-4\cos\frac {B-C}{2}\;\cos\frac {C-A}{2}\;\cos\frac {A-B}{2}$$

My Attempt:
Here, $A+B+C=\pi$
Now,
$$\begin{align}
LHS &=\cos(B+2C)+\cos(C+2A)+\cos(A+2B) \\
&=\cos(B+C+C)+\cos(C+A+A)+\cos(A+B+B) \\
&=\cos(\pi-(A-C))+\cos(\pi-(B-A))+\cos(\pi-(C-B)) \\
&=-\cos(A-C)-\cos(B-A)-\cos(C-B)
\end{align}$$
Please help to continue from here.
Comment: Certainly try: $\cos (A-C)=2\cos^2\frac{A-C}{2}-1$.
Comment: Maybe try drawing a picture of a triangle with angles $A,B,C$ and seeing if you can gain some intuition from that?
Answer: Let $C-A=2x,B-C=2y,A-B=2z\implies2(x+y+z)=0$
$$F=\cos2x+\cos2y+\cos2z=2\cos(x+y)\cos(x-y)+2\cos^2z-1$$
Now as $\cos(x+y)=\cos(-z)=\cos z,$
$$F=2\cos z\cos(x-y)+2\cos z\cdot\cos(x+y)-1$$
$$=2\cos z\{\cos(x+y)+\cos(x-y)\}-1=2\cos z\{2\cos x\cos y\}-1=?$$
Comment: How is $cos(x+y)=cosz$?
Comment: @user354073,  $$x+y=-z\implies\cos(x+y)=\cos(-z)=?$$
Comment: And how is LHS=RHS? I could not get that. Please clarify.
Comment: @user354073, Replace the values of $x,y,z$
Comment: With that, I got:
$$4cos\frac {C-A}{2}.cos\frac {B-C}{2}.cos\frac {A-B}{2} -1$$?
Comment: @user354073, LHS $$=-\cos(A-C)-\cos(B-C)-\cos(C-B)$$  Use $\cos(-u)=+\cos u$
Answer: For the RHS, you can use a known formula for the product of three cosines (see eg. here):
$\cos x \; \cos y \; \cos z = \frac{1}{4} \Big(\cos (x+y-z) + \cos (y+z-x) + \cos (z+x-y) + \cos (x+y+z)\Big)$
Considering your RHS, you set $x = \frac{B-C}{2}$,  $y = \frac{C-A}{2}$,  $z = \frac{A-B}{2}$,    and plug it into the formula. Then, for example,
$x+y-z = B-A$, likewise the other arguments.
This gives immediately the form you arrived at,
$-\cos(A-C)-\cos(B-A)-\cos(C-B)$.
Comment: Andreas,  I.could not understand. Could you please elaborate?
Comment: I added more steps in the answer.


Grid Skeleton Responsiva com Wordpress

Question: Seguinte estou construindo um website que precisa mostrar os posts com o wordpress, porém estou usando o framework de grid Skeleton, ele funciona da seguinte forma:

E assim vái....
Mas eu estou tendo o seguinte :

E o Problema:
Wordpress tem o seguinte esquema de dar display nos posts:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php endwhile?>

<?php else: ?>

<?php endif; ?>

Como adapto o sistema de grid para a cada 4 posts dar um
 no inicio e um
 no final, para ficar responsivo?
Situação atual:

Teste Bananinha

Teste Bananinha

Teste Bananinha

Teste Bananinha

Teste Bananinha

Teste Bananinha

Teste Bananinha

Teste Bananinha

Answer: Existem várias maneiras de solucionar essa questão. Abaixo tem algumas das formas que já usei.
1. CSS:
Em vez de usar o framework nessa situação poderá usar o puro CSS. Seria algo mais ou menos assim:
HTML(gerado pelo WordPress):

CSS:
.posts {
    width: 1280px;
}

.posts .three {
    width: 25%;
}

Porém seria necessárias mais algumas linhas de código para corrigir possíveis desajustes no layout.
2. PHP:
Você pode também usar uma função para incluir o código necessário no loop, essa era a maneira que eu fazia no início. Fiz uma função exemplo, basta colocá-la no funcions.php e chamá-la na página que quiser:
Função:
function add_row( $current, $end = false, $columns = 4 ) {
    $row = ( $current % $columns ) === 0 ? true : false;

    if( $row && ! $end ) {
        echo '
';
    }
    if( $row && $end) {
        echo '
';
    }
}

Exemplo de uso:
if ( have_posts() ):
    $count = 1;
    while ( have_posts() ):
        add_row($count); // Imprimi a tag de abertura
        the_post();
        add_row($count, true); // Imprimi a tag de fechamento
        $count++;
    endwhile;
endif;

Com essa modificação o loop vai gerar o HTML que você espera.
3. Jeet:
Ou você pode usar o Jeet que é um sistema de grids, ele torna a criação de grids css bem mais fácil e rápida.
Mas para isso você também terá de usar um task runner como Grunt ou Gulp e um pré-processador CSS como Less ou Sass ou Stylus. Interessante que dando uma olhada na documentação do Skeleton vi que eles dão suporte a Less e Sass, você pode ver isso aqui. Usando essas ferramentas combinadas* você teria um código assim:
HTML:
Séria o mesmo do primeiro exemplo.
Sass:
@import 'jeet/index';

.container {
  .three {
    col(3/12)
  }
}

*A combinação que eu gosto, devido a curva de aprendizado é Gulp + Sass + Jeet.
Comment: Estou utilizando o sistema básico com o html mais o css (gerado pelo WordPress), e está funcionando perfeitamente, obrigado!

Grid Skeleton Responsiva com Wordpress


Does $(p\implies q)\implies\neg( q\implies p)$?

Question: $p\implies q$ does not necessarily indicate that $q\implies p$, which is why there exists a double-sided implication: $\iff$.
$p\iff q$ is the same as saying $(p\implies q)\land(q\implies p)$. However, sometimes when I am illustrating my working out, I use the one-sided $\implies$ symbol even when using the $\iff$ symbol would also work. My question is: does $p\implies q$ directly say that $q\implies p$ is false? Even if it does not, is it better practice to try and always use $\iff$ when it works both ways?
Comment: No. Check it with truth table.
Comment: Writing $p\implies q$ doesn't imply that the converse is false. It's often useful to notice when your logical steps are reversible (i.e. when things are equivalences instead of just implications) but it's not required. Sometimes one direction is a lot easier than the other.
Comment: Is it possible that your posted question has a typo?  Is it possible that you intended $~(p \implies q) \implies ( ~[\neg q] \implies [\neg p] ~) ~?$
Comment: "does p⟹q directly say that q⟹p is false?"  Of course not.  " is it better practice to try and always use ⟺ when it works both ways?"  It's better practice to not say things that aren't important.  If whether $q\implies p$ is completely irrelevant, why talk about it? Penguins eat fish is always true but I usually don't include it in my mathematical proofs.
Answer: By definition: $(p\Longrightarrow q)\equiv(q\lor\lnot p)$ and $\lnot(q\Longrightarrow p)\equiv(q\land\lnot p)$. Clearly if $q$ holds and $p$ holds or if $\lnot q$ and $\lnot p$ hold, your implication fails.
Edit: The notation $p\Longleftrightarrow q$ is just a short form for $(p\Longrightarrow q)\land(q\Longrightarrow p)$. When using only a one-sided arrow, one doesn't say anything about the converse direction. It can be used when one doesn't really care about the converse direction.


How companies calculate and ensure an uptime guarantee?

Question: It is simple to calculate the expected uptime based on past data.
But a "guarantee" is totally another concept.
How do companies manage that?
Comment: This is a question about contracts, not technology.  There are usually penalties listed with any guarantee.  If there isn't, you've got nothing but 'their word'.  It's handled with a Service Level Agreement.
Comment: @yoonix Okay....I thought they have some kind of sophisticated statistical model....
Answer: They lie through their teeth and/or have good lawyers write them service level agreements that effectively prevent customers from seeking damages when something does break?
Of course you should start out with a well-designed and resilient architecture, but occasionally things will blow up in your face when you poke them, and as you note you can't really predict the future based on your historical track record.


Can workstations from completely separate domain access a WSUS server?

Question: I have the situation where there are many workstations in Domain A and a WSUS server in Domain A.  The situation is that I want a few computers from Domain B to be able to pull updates from Domain A's WSUS server.
Please assume that there is no link between the two domains (trust relationships) except for a open port(s) in a firewall for communication
Answer: Per Wikipedia
"WSUS does not require the use of Active Directory; client configuration can also be applied by local group policy or by modifying the Windows registry."
This should be possible by setting up a GPO for domain B, pointing to update server  on domain A.
Here is a dated, but still relevant article. My understanding, and it's been awhile since I supported a production AD domain, is that it merely replaces the Windows Update Server, as well as providing statistics.
Answer: You could do registry editing to have the computers access Domain A's WSUS.
http://technet.microsoft.com/en-us/library/cc708449%28v=ws.10%29.aspx


normalize floating point

Question: i am doing floating point addition using MARS.
  SameExponent:
  add $s6,$s4,$s5

after I aligned the exponents, I added up the significands,but how do I detect if the sum is still normalized or not in order to shift the signicicand to the left or right? Thank you
Comment: Is this the MARS MIPS simulator? If so you might want to tag it with mips as well.
Answer: If the significands are integers in the range -A ... +A, then the result of adding them together is in the range -2A ... +2A. To normalize the result you need to shift left or right to get the most-significant 1 bit back to the normalized position, keeping track of how much you shifted so you can adjust the exponent accordingly.
The maximum required right shift is one position; the left shift can be more if your arguments may be positive or negative. The simple way to do it is a while-style loop, shifting left by one until the MSB is where you want.
Algorithm for finding the smallest power of two that's greater or equal to a given value has some alternate possibilities if you want something faster (nothing for MIPS though).

normalize floating point


Pass in array of components as inputs Angular 12

Question: I'm creating a window like component in Angular. On the top right of the component it can have set of buttons that do different things (like opening a modal, deleting something etc). See the image below for reference:

Now, we're using this type of layout in a lot of places within the application but with different set of buttons for the top right section. Now, in react doing this is pretty straightforward, I can simply pass any number of instanciated components as props to this component and display them.
What is the ideal way to do something like this in Angular?
Answer: A solution to this could be to pass the buttons into a display component.
you can pass the buttons in using Content projection.
ng-content is a good example of this but could require you to have the buttons in the layout, for each view you are on, in order to pass them in.
Another solution would be to have all the buttons already exist inside the component and then only display the ones you need based on a input parameter.
You can also look into dynamic components which should allow you to switch out the components when needed.
Comment: Generally for the use cases I have experienced, that method is the simplest. Reusability of each button also plays a part.
Comment: Thanks, I was also looking into content projection. I'm already using `ng-content` to display some html/angular template code inside the window area.


want a simple program illustrating the use of concurrent lisp using threads

Question:
I am just getting curious  about lisp programming and wanted to
know how to use concurrent lisp by making threads.
-I also wanted to be clear with the pcall() function in lisp.
Comment: Can you be more specific about which lisp and libraries you are using, and what is unclear to you?
Comment: @samuel-edwin-ward am using the sbcl lisp on fedora 19.I was reading the threading part in the sbcl manual,and just wanted a simple program that would illustrate the use of threading in it.Also i noticed the ex in which pcall  was used to automatically perform the operation concurrently.Ex (pcall (+(* a b) (*c d))
Comment: This is almost certainly off topic (too broad, not enough detail, etc.), but you may find [Eager-Future2 Library :Parallel Programming in Lisp](http://stackoverflow.com/q/27798351/1281433) helpful, at least in terms of links to follow.
Comment: Ok that definately helped me.Thank You Joshua Taylor
Answer: the comments to your question give you the right key to solve the problem. I hope this is still helpful.
If you want to use concurrency with common lisp, One of the ways is Eager Future2 http://common-lisp.net/project/eager-future/, but you can choose other models here http://www.cliki.net/concurrency.
Eager Future is based, like the name suggested, in Futures
"Eager Future2 is a Common Lisp library that provides composable
concurrency primitives that unify parallel and lazy evaluation, are
integrated with CL's condition system, and have automatic resource
management.
The basic unit of concurrency in Eager Future2 is the future, which is
a data type that acts as a proxy for the values of a no-argument
function (thunk) that is computed concurrently."
Let's see how works pcall, from documentation of Eager Furture2 we find:
"
function pcall (thunk &optional (future-type default-future-type)) => future
Given a function of no arguments, returns an object (called a
future) that can later be used to retrieve the values computed by the
function.
future-type (by default the value of default-future-type) can either
be :eager, :speculative, or :lazy. See the documentation of
default-future-type for an explanation of the different future
types.
The function is called in an unspecified dynamic environment."
sample lisp code
<code>;; use quicklisp to add Eager-Future2 to your common lisp
;; implementation in my case I use GVIM, SLIMV and SBCL
(quicklisp:quickload "EAGER-FUTURE2")

(defparameter *future* (eager-future2:pcall #'compute))

*future*

;; Returns non nil if the future values have been computed, nil otherwise
(eager-future2:ready-to-yield? *future*)

;;Returns the computed values, see delayed future, computes the value in current thread,
;;and speculative future computes the future in a current thread if not is evalatuated
;;in another thread.
(eager-future2:yield *future*)

;; function for the long computation, from http://www.cliki.net/fibonacci
(defun fib (n)
  "Tail-recursive computation of the nth element of the Fibonacci sequence"
  (check-type n (integer 0 *))
  (labels ((fib-aux (n f1 f2)
             (if (zerop n)
               f1 (fib-aux (1- n) f2 (+ f1 f2)))))
    (fib-aux n 0 1)))

;; function with no arguments for pcall that computes fibonacci 10000th number
(defun compute ()
  (fib 10000))
</code>
Use in REPL
<code>SBCL 1.2.4-1.fc21  Port: 4005  Pid: 1188
; SWANK 2014-10-10
CL-USER> (quicklisp:quickload "EAGER-FUTURE2")
To load "eager-future2":
  Load 1 ASDF system:
    alexandria
  Install 3 Quicklisp releases:
    bordeaux-threads eager-future2 trivial-garbage
; Fetching #<URL "http://beta.quicklisp.org/archive/trivial-garbage/2013-03-12/trivial-garbage-20130312-git.tgz">
; 8.00KB
==================================================
8,197 bytes in 0.01 seconds (1143.55KB/sec)
; Fetching #<URL "http://beta.quicklisp.org/archive/bordeaux-threads/2013-06-15/bordeaux-threads-0.8.3.tgz">
; 18.31KB
==================================================
18,754 bytes in 0.06 seconds (327.04KB/sec)
; Fetching #<URL "http://beta.quicklisp.org/archive/eager-future2/2011-03-20/eager-future2-0.2.tgz">
; 17.34KB
==================================================
17,758 bytes in 0.07 seconds (262.75KB/sec)
; Loading "eager-future2"
[package bordeaux-threads]........................
[package trivial-garbage].........................
[package eager-future2]..
("EAGER-FUTURE2")
CL-USER> (defun fib (n)
  "Tail-recursive computation of the nth element of the Fibonacci sequence"
  (check-type n (integer 0 *))
  (labels ((fib-aux (n f1 f2)  ...))))
FIB
CL-USER> (fib 1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
CL-USER> (fib 10000)
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875
CL-USER> (defun compute ()
  (fib 10000))
COMPUTE
CL-USER> (defparameter *future* (eager-future2:pcall #'compute))
*FUTURE*
CL-USER> *future*
#<EAGER-FUTURE2:FUTURE {1004F20383}>
CL-USER> (eager-future2:ready-to-yield? *future*)
T
CL-USER> (eager-future2:yield *future*)
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875
CL-USER>
</code>
I hope that this will be usefull


With the Elimination of God Class "Mage::" can we say Magento is now Atheist

Question: I was reading some articles about Magento 2.0 and came across one from Amasty Blog. It is a very informative article. There i saw a point which states God class "Mage::" is eliminated
As soon as i read it a question popped up my mind, So now who will control the whole flow, Who can we pray for giving us the power of inheritance?
I am asking this question over here as we have many Angels of Magento over here who can provide pretty good information about it.
Please make the answer informative and funny too in this festive season.
Answer: We will bow down to the all mighty Dependency Injection.
Here is preview: http://inchoo.net/magento-2/basics-dependency-injection-usage-magento-2/
Here is the full "holly book": http://devdocs.magento.com/
Comment: Thank you angel for spreading the message of GOD


Web based file search in the lan?

Question: I would like to search files in my lan easily. (over 500k files on SMB shares, it would take ages with other ways)
I mean, i just need to do a quick search on file names, i don't care content indexing at all, as most of my files are in a proprietary format, and the file name is explicative enough. But, date range filters are a must for me.
I just need a quick search like voidtools' everything can do, but in a network way
The files are on a WHS box (lol, Videos and Music share names are not appropriate for a company, but a license for that win2003-based os is cheaper than an xp home one!)
I tried:

Lansearch pro: it is not good for me, as i need a quick index
Network Search Engine: it would be perfect, but does not offer a date range filter
Microsoft Search Server 2008 Express, but it is horrible! First, does NOT index filenames, and then, my Core2Duo is not powerful enough to run it smoothly.
Google Desktop with a proxy on localhost to make it run on the lan, but i don't like the hacked result.
The preinstalled Windows Search 4.0 but it sucks totally in choosing the relevance of data - uninstalled
Docco... what's that?

I am considering to try:

Ibm omnifind
DocFetcher (can it work as a client? did not investigated yet)
Strigi (it looks like that it can work as a client, right?)

Any ideas/suggestions?
Comment: docfetcher and strigi are not good because they dont offer date filter
Comment: ibm omnifind seems very good, but it's not ok, because seems there is no way to make it index other extensions, and does not offer date filter too...
Comment: Did you ever settle on something? I am looking for something similar. Does Solr work? that seems to be the most common suggestion. I tried elasticsearch but didn't know how to add a network path as an index to it.
Comment: No, i didn't found a solution for this...
Answer: try solr, it also has a date filter when you configure it.
here is a php client to solr and here is a tutorial from developer works for setting this up.
when it does not fullfill all your needs, you can also extend it.
Comment: i forgot to reply: i don't like solr. I like something like google desktop...
Answer: The google search appliance might be just what you are looking for.
Comment: it would be great, but we are too small for such a solution
Answer: I have a simple Windows search utility that will search network shares as easily as the local drive and fits your description. You can download it from here. It's freeware, so comes with no warranty.
Answer: I had a similar problem in my company.
Lot of files/directories on a Windows network share.
Biggest: ~50 million files in 25 million directories.
I wrote a little tool which does the directory enumerations in parallel.
There's a pretty nice speedup on network shares using this method.
Source code:
https://github.com/blaubart69/find_win32

right now it's running on Windows only (.NET framework)
command line
simple date filter (newer/older)
regex on filename

Web based file search in the lan?


CakePHP i18n/i10n Routing

Question: Update:
I'm using a shared CakePHP lib across several apps (with all of them living in subdomains).  They're not all nested the same; so, for example, on the filesystem I might have:
/foo
  .htaccess
  /1.0 (app)
  /1.1 (app)
  /1.2 (app)
  ...
/bar
  .htaccess
  /1.0 (app)
  /1.1 (app)
  /1.2 (app)
  ...

Where the .htaccess in each just defines which app is the default that requests are routed to within that subfolder, while all of them are still available by a direct url (eg /foo/1.0/...).
It seems that if I'm using the direct URL (eg not the .htaccess-rewritten one) it recognizes the routes appropriately, but if the URL is rewritten by .htaccess, it doesn't; it will invoke AppError::error404() with the ouput at the end of the question.  This doesn't seem right to me... if anyone has any insight, that would be awesome.

Hey guys,
I'm using CakePHP 1.3 and having a routing issue.  The gist of the concept is this:

I want to use 'en_us' style i18n/i10n, not simply 'en'
I'm not using built-in i18n because of requirements to have some languages display pages with localized views (views/:i18n/...) and others to common views with calls to __()

So, I have routes set up like so:
$sI18nFormat = '/[a-z]{2}_[a-z]{2}/';
Router::connect('/:i18n/:controller/:action',
    array('controller' => ':controller', 'action' => ':action', 'i18n' => ':i18n'),
    array('i18n' => $sI18nFormat));
Router::connect('/:i18n/:controller',
    array('controller' => ':controller', 'action' => 'index', 'i18n' => ':i18n'),
    array('i18n' => $sI18nFormat));
Router::connect('/:controller/:action',
    array('controller' => ':controller', 'action' => ':action', 'i18n' => 'en_us'),
    array('i18n' => $sI18nFormat));
Router::connect('/:controller',
    array('controller' => ':controller', 'action' => 'index', 'i18n' => 'en_us'),
    array('i18n' => $sI18nFormat));

where obviously the routes are mirrored except that one has a dynamic i18n parameter passed, and the other has a static one.
The problem comes with using certain values for :i18n - for example, en_us is okay, but fr_fr seems to have Cake looking for FrController (not FrFrController) - seemingly because it's trying to work some magic with a built-in i18n fr prefix.
As an example, here's what AppError::error404 is given:
Array
(
    [className] => FrController
    [webroot] => /path/to/webroot
    [url] => _fr
    [base] => /path/to/webroot
)

Is it possible to a) make Cake stop this so my routes work as expected, or b) tell Cake what format I want my i18n/i10n in so it doesn't try to do it its own way?
Any thoughts would be appreciated.
Comment: BTW, it's "i18n" (eye-18-en) and *"l10n" (ell-10-en)*. :)
Comment: haha, too true... long day. ;)
Answer: You should not (need to) delimit the Regex, and there should also be no need to populate the default parameter. Try this:
$sI18nFormat = '[a-z]{2}_[a-z]{2}';
Router::connect('/:i18n/:controller/:action', array(), array('i18n' => $sI18nFormat));

It's probably also failing because the URL does not match the full defined route. I.e., /fr_fr/foo will not match the above route, since it contains no :action. Try adding shorter variants as well:
Router::connect('/:i18n/:controller', array('action' => 'index'), array('i18n' => $sI18nFormat));
Router::connect('/:i18n', array('controller' => 'foo', 'action' => 'index'), array('i18n' => $sI18nFormat));

Comment: It was definitely a bit too verbose... happily removed the unnecessary bits.  Question though - I thought that only the parameter itself was matched against the regex, not the entire URI?  If I have a defined route `/:i18n/:controller` that points to `:action => index`, why would that not match `/fr_fr/foo` (for example)?
Comment: Scratch that - after I resolved an .htaccess issue everything is working as expected.  Thank you!
Answer: Have you looked at p28n? http://bakery.cakephp.org/articles/p0windah/2007/09/12/p28n-the-top-to-bottom-persistent-internationalization-tutorial
I found that it made the whole thing much less of a handful.
Comment: I did look into that before and I was a bit turned off by the need for an (effectively) redirect controller to switch languages.  I want language to be controlled by the URI, not by the session... and it seems that p28n ~= stock i18n in that regard... unless I'm missing something crucial.  Clue me in if I am!

CakePHP i18n/i10n Routing


Como verificar se tag HTML tem determinado atributo com JS?

Question: Neste código:

Como você pode ver, não tem atributo src. Como posso saber se determinada tag tem um src ou não usando JavaScript?
Answer: Você pode verificar utilizando o método hasAttribute(), veja abaixo:
document.getElementById('SizeImage1').hasAttribute('src');

Vai te retornar true ou false.
Mais informações aqui: W3Schools - hasAttribute.
Comment: Consegui resolver problema usando hasAttribute(), https://jsfiddle.net/rsf6mn9n/
Comment: @MatheusMiranda então se a resposta do Douglas lhe resolveu o problema marque-a como correta por favor. Não somos um fórum, somos um Q&A, por favor faça o tour: http://pt.stackoverflow.com/tour para entender como o site funciona
Comment: Obrigado @GuilhermeNascimento, eu vi documento como funciona o site.
Answer: Outra forma é obtendo o valor de src, então verificar se está vazio ou não:

var src1 = document.getElementById("SizeImage1").src
  , src2 = document.getElementById("SizeImage2").src;

// verifica se está null, '', undefined, 0
if (!src1)
 console.log("Primeiro está vazio");

if (!src2)
console.log("Segundo está vazio");

Comment: Oi Lucas Costa, esse também funciona, obrigado pela resposta.


Quebra de linha em dados vindo de uma lista

Question: Tenho um dialog que mostra na tela os dados recebidos de uma lista:

    <h:outputText value="#{zonaBean.getVendedoresPorZona(zona.id)}"/>

Quando esse dialog é exibido, todas as informações aparecem na mesma linha, e eu queria que fosse um dado em cada linha.
Alguém sabe como faço isso?
Comment: Acredito que a String que vc quer mostrar já tenha as quebras de linha. Nesse caso use um `` ao invés do outputText.
Comment: Já tentou usar o `dataList`? http://www.primefaces.org/showcase/ui/data/dataList.xhtml
Answer: Imagino que esteja exibindo tudo na mesma linha porque o "
" é executada somente uma vez e depois de exibir o outputText.
Tenta colocar o retorno dessa lista dentro de um forEach.
Exemplo:

    <c:forEach  items="#{zonaBean.getVendedoresPorZona(zona.id)}" var="row"
       <h:outputText value="row"/>

    </c:forEach>

Answer: Como você não especificou o que vai fazer com a lista (creio que seja somente para exibição, mas a mesma lógica se aplica a outras estruturas - checkboxes, por exemplo), existem várias soluções possíveis (considerando que getVendedoresPorZona retorna uma lista de String). Nos exemplos, estou usando o outputText da sua pergunta para fins didáticos:
Por Repeat (permite uma maior flexibidade, não ficando restrito a um output específico):

    <ui:repeat value="#{zonaBean.getVendedoresPorZona(zona.id)}" var="v">
        <h:outputText value="#{v}"/>

    </ui:repeat>

Por Repeat do Primefaces:

        <h:outputText value="#{v}"/>

Por DataList do Primefaces:

        <h:outputText value="#{v}"/>

Por DataTable do Primefaces (útil quando tem um objeto com vários atributos):

            <h:outputText value="#{v}"/>

Por ForEach (exemplificado anteriormente pelo @arthur-vidal):

    <c:forEach var="v" items="${zonaBean.getVendedoresPorZona(zona.id)}">
        <h:outputText value="#{v}"/>

    </c:forEach>


Evaluate $\int_0^1x\log\left(1+x^2\right)\left[\log\left(\frac{1-x}{1+x}\right)\right]^3\operatorname{d}\!x$

Question: Prove that
 $$\int_0^1x\log\left(1+x^2\right)\left[\log\left(\frac{1-x}{1+x}\right)\right]^3\operatorname{d}\!x$$
 $$I=\frac{105}{8}\zeta(3)-\frac{7\pi^2}{4}\ln2-6\pi{G}+3\pi^2-\frac{3}{8}\pi^3-\frac{7}{64}\pi^4$$
where $G$ is the Catalan's constant.
Additional reponse at FDP
You are almost at the end.
 $\mathbf{I}\mathbf{\,continue}$
 Using integration by parts, we have:
 $C=3\displaystyle\int_0^1\dfrac{\log^2x\log(1+x^2)}{x}dx-3\displaystyle\int_0^1\dfrac{\log^2x\log(1+x^2)}{1+x}dx-\displaystyle\int_0^1\dfrac{log^3x}{1+x}dx-\displaystyle\int_0^1\dfrac{log^3x}{1+x^2}dx+\displaystyle\int_0^1\dfrac{x\log^3x}{1+x^2}dx$
$D=\displaystyle\dfrac{3}{2}\int_0^1\dfrac{\log^2x\log(1+x^2)}{x}dx-\displaystyle\dfrac{3}{2}\int_0^1\dfrac{\log^2x\log(1+x^2)}{1+x}dx-\displaystyle\dfrac{3}{2}\int_0^1\dfrac{\log^2x\log(1+x^2)}{(1+x)^2}dx-\displaystyle\dfrac{1}{2}\int_0^1\dfrac{log^3x}{(1+x)^2}dx+\displaystyle\dfrac{1}{2}\int_0^1\dfrac{log^3x}{1+x^2}dx$
$2D-C=\displaystyle\int_0^1\dfrac{(1-x)\log^3x\log(1+x^2)}{(1+x)^3}dx=-3\displaystyle\int_0^1\dfrac{log^2x\log(1+x^2)}{(1+x)^2}dx+\displaystyle\int_0^1\dfrac{log^3x}{1+x}dx-\displaystyle\int_0^1\dfrac{xlog^3x}{1+x^2}dx$.
}
But,$\displaystyle\int_0^1\dfrac{log^3x}{1+x}dx=-\dfrac{7\pi^4}{120}$; and$ \displaystyle\int_0^1\dfrac{xlog^3x}{1+x^2}dx.=-\dfrac{7\pi^4}{1920}$
Remains to be assessed:  $ \displaystyle\int_0^1\dfrac{log^2x\log(1+x^2)}{(1+x)^2}dx$, to be continued .
 Also,  $\displaystyle\int_0^1\dfrac{\log^2x\log(1+x^2)}{(1+x)^2}dx=2\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{x}dx-2\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{(1+x)}dx-\displaystyle\int_0^1\dfrac{log^2x}{1+x}dx+\displaystyle\int_0^1\dfrac{log^2x}{1+x^2}dx+\displaystyle\int_0^1\dfrac{x\log^2x}{1+x^2}dx$
These integrals are know
$\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{x}dx=-\dfrac{3}{16}\zeta(3)$;
$\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{(1+x)}dx=-\dfrac{\pi(G)}{2}-\dfrac{\pi^2}{16}ln2+\dfrac{3}{2}\zeta(3)$
Also,  $\displaystyle\int_0^1\dfrac{\log^2x\log(1+x^2)}{(1+x)^2}dx=2\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{x}dx-2\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{(1+x)}dx-\displaystyle\int_0^1\dfrac{log^2x}{1+x}dx+\displaystyle\int_0^1\dfrac{log^2x}{1+x^2}dx+\displaystyle\int_0^1\dfrac{x\log^2x}{1+x^2}dx$
These integrals are know
$\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{x}dx=-\dfrac{3}{16}\zeta(3)$;
$\displaystyle\int_0^1\dfrac{\log\,x\log(1+x^2)}{(1+x)}dx=-\dfrac{\pi}{2}{G}-\dfrac{\pi^2}{16}ln2+\dfrac{3}{2}\zeta(3);\displaystyle\int_0^1\dfrac{log^2x}{1+x}dx=\dfrac{3}{2}\zeta(3); \displaystyle\int_0^1\dfrac{log^2x}{1+x^2}dx=\dfrac{\pi^3}{16}$
Finally,$\displaystyle\int_0^1\dfrac{log^2x\log(1+x^2)}{(1+x)^2}dx=\dfrac{75}{16}\zeta(3)+{\pi}G+\dfrac{\pi^2}{8}ln2+\dfrac{\pi^3}{16}$
And 2D-C=$\dfrac{297}{16}\zeta(3)-3{\pi}G-\dfrac{3}{8}{\pi^2}ln2-\dfrac{3}{16}{\pi^3}-\dfrac{7}{128}{\pi^4}$
We obtain also the result.
Comment: My approach would be to rewrite log((1-x)/(1+x)) as log(1-x)-log(1+x) and then expand the cube. This will at least break the integral up into smaller chunks.
Answer: I don't have a complete answer.
Let $\displaystyle I=\int_0^1 x\log(1+x^2)\Big[\log\Big(\dfrac{1-x}{1-x}\Big)\Big]^3dx$
First perform the change of variable $y=\dfrac{1-x}{1+x}$.
$\displaystyle I=\int_0^1 \dfrac{2(1-x)}{(1+x)^3}\log\Big(\dfrac{2(1+x^2)}{(1+x)^2}\Big)\log^3xdx$
Notice:
$\dfrac{1-x}{(1+x)^3}=\dfrac{2}{(1+x)^2}-\dfrac{1}{(1+x)^3}$
Therefore:
$I=4\log 2\times B-2\log 2\times A+4D-2C-8F+4E$
Where:
$A=\displaystyle \int_0^1\dfrac{\log^3x}{(1+x)^2}dx$
$B=\displaystyle \int_0^1\dfrac{\log^3x}{(1+x)^3}dx$
$C=\displaystyle \int_0^1 \dfrac{\log(1+x^2)\log^3x}{(1+x)^2}dx$
$D=\displaystyle \int_0^1 \dfrac{\log(1+x^2)\log^3x}{(1+x)^3}dx$
$E=\displaystyle \int_0^1 \dfrac{\log(1+x)\log^3x}{(1+x)^2}dx$
$F=\displaystyle \int_0^1 \dfrac{\log(1+x)\log^3x}{(1+x)^3}dx$
One can continue like this, using integration by parts:
$C=\displaystyle\int_0^1 \dfrac{3\log^2x\log(1+x^2)}{x}dx-\int_0^1 \dfrac{3\log^2x\log(1+x^2)}{1+x}dx+\int_0^1 \dfrac{x\log^3 x}{1+x}dx-\int_0^1 \dfrac{x^2\log^3 x}{1+x^2}dx+\int_0^1 \dfrac{x\log^3 x}{1+x^2}dx$
Let's compute $A$:
$\displaystyle A=\int_0^1 \Big[\sum_{n=0}^{+\infty}(n+1)(-1)^nx^n\Big]\log^3 x dx$
$\displaystyle A=-6\sum_{n=0}^{+\infty} \dfrac{(-1)^n}{(n+1)^3}$
$A=-6\times (1-2^{1-3})\zeta(3)=-\dfrac{9}{2}\zeta(3)$
Let's compute $B$:
$\displaystyle B=\dfrac{1}{2}\int_0^1 \Big[(-1)^n(n+2)(n+1)x^n\Big]\log^3 x dx$
$\displaystyle B=-3\sum_{n=0}^{+\infty} \dfrac {(-1)^n}{(n+1)^2}-3\sum_{n=0}^{+\infty} \dfrac {(-1)^n}{(n+1)^3}$
$B=-3\times(1-2^{1-2})\zeta(2)-3\times(1-2^{1-3})\zeta(3)=-\dfrac{3}{2}\zeta(2)-\dfrac{9}{4}\zeta(3)$
$B=-\dfrac{\pi^2}{4}-\dfrac{9}{4}\zeta(3)$
Let's continue.
(it's a bad idea to try to compute $E$ by the way. happily, we're lucky, we don't have to do this)
$\displaystyle E=3\int_0^1 \dfrac{\log^2(x)\log(1+x)}{x}dx-3\int_0^1 \dfrac{\log^2(x)\log(1+x)}{1+x}dx+A$
Let $E_1:=\displaystyle \int_0^1 \dfrac{\log^2(x)\log(1+x)}{x}dx$
Let $\displaystyle E_2:=\int_0^1 \dfrac{\log^2(x)\log(1+x)}{1+x}dx$
(believe me, you don't want to compute $E_2$)
Using integration by parts and partial fraction decomposition:
$\displaystyle -8F=12E_2-12E_1+24\int_0^1 \dfrac{\log x\log(1+x)}{x}dx-24\int_0^1 \dfrac{\log x\log(1+x)}{1+x}dx+12\times\int_0^1\dfrac{\log^2x}{(1+x)^2}dx-4B$
Let $\displaystyle F_1=\int_0^1 \dfrac{\log x\log(1+x)}{x}dx$
$\displaystyle F_1=\int_0^1 \Big[\sum_{n=0}^{+\infty}(-1)^n\dfrac{x^{n+1}}{n+1}\Big]\dfrac{\log x}{x}dx$
$F_1=\displaystyle -\sum_{n=0}^{+\infty}\dfrac{(-1)^n}{(n+1)^3}=-(1-2^{1-3})\zeta(3)=-\dfrac{3}{4}\zeta(3)$
Let $\displaystyle F_2=\int_0^1 \dfrac{\log x\log(1+x)}{1+x}dx=-\dfrac{1}{8}\zeta(3)$
(based upon the computation of $K$ in: Other challenging logarithmic integral $\int_0^1 \frac{\log^2(x)\log(1-x)\log(1+x)}{x}dx$ )
Another way to compute $F_2$ knowing that:
$Li_2\Big(\dfrac{1}{2}\Big)=\dfrac{1}{12}\Big(\pi^2-6(\log 2)^2\Big)$
$Li_3\Big(\dfrac{1}{2}\Big)=\dfrac{1}{24}\Big(4(\log 2)^3-2\pi^2\log 2+21\zeta(3)\Big)$
Performing the change of variable $y=\log(1+x)$:
$\displaystyle F_2=\int_0^{\log 2} x\log(e^x-1)dx=\int_0^{\log 2} x^2dx+\int_0^{\log 2} x\log(1-e^{-x})dx$
$\displaystyle F_2=\dfrac{(\log 2)^3}{3}-\sum_{n=1}^{+\infty}\Big(\int_0^{\log 2}\dfrac{xe^{-nx}}{n}dx\Big)$
$\displaystyle F_2=\dfrac{(\log 2)^3}{3}-\sum_{n=1}^{+\infty}\dfrac{1}{n^3}+\log 2\sum_{n=1}^{+\infty}\dfrac{2^{-n}}{n^2}+\sum_{n=1}^{+\infty}\dfrac{2^{-n}}{n^3}$
$\displaystyle F_2=\dfrac{(\log 2)^3}{3}-\zeta(3)+\log 2 Li_2\Big(\dfrac{1}{2}\Big)+Li_3\Big(\dfrac{1}{2}\Big)=-\dfrac{1}{8}\zeta(3)$
Let $\displaystyle F_3=\int_0^1\dfrac{\log^2x}{(1+x)^2}dx$
$\displaystyle F_3=\int_0^1 \Big[\sum_{n=0}^{+\infty}(n+1)(-1)^nx^n\Big]\log^2 x dx$
$\displaystyle F_3=2\sum_{n=0}^{+\infty} \dfrac{(-1)^n}{(n+1)^2}$
$F_3=2\times (1-2^{1-2})\zeta(2)=\zeta(2)=\dfrac{\pi^2}{6}$
Therefore:
$-8F+4E=24F_1-24F_2+12F_3-4B+4A=-24\zeta(3)+3\pi^2$
The harder part remains to do !
Comment: @Narasimham It's [Riemann zeta function](http://en.wikipedia.org/wiki/Riemann_zeta_function)
Comment: What is denoted by function  $\zeta(x)$?
Comment: @FDP, wonderful solution. There is a typo in the second line.


Show that the set of products need not be an ideal

Question: Let $R$ be a commutative ring, and $I$, $J$ be two ideals in $R$.
Show, by giving an explicit example, that the set of products $\{xy\ |\ x\in I, y\in J\}\subset R$ need not be an ideal.
The definition of "ideal" we're using is:

An ideal is a subset $I$ of a commutative ring $R$ that satisfies the following properties:
1) $0\in I$.
2) If $x\in I$ and $y\in I$, then $x+y\in I$.
3) If $x\in I$ and $a\in R$, then $ax\in R$.

The set of products will contain $0$, so property 2 or 3 has to fail. I can't come up with an example. Any suggestions?
Comment: @AlexVong: $\mathbb Z$ is a principal ideal domain ...
Comment: I think $\mathbb{Z}$ already contains an example. Can you guess it? Hint: use the `closed under addition` property
Comment: @HenningMakholm Yes I was wrong. $\{ax \mid x \in \mathbb{Z}\}$ and $\{bx \mid x \in \mathbb{Z}\}$ gives you $\{abx \mid x \in \mathbb{Z}\}$, which is an ideal.
Answer: Consider $k[x,y,z,t]$ where $k$ is a field, $I$ is the ideal generated by $x,y$ and $J$ is the ideal generated by $z,t$. $xz,yt\in IJ$ but $xz+yt$ is not in $I.J$.
Comment: If you just have x and y, and I=(x) and J=(y) you can do the same, no?
Comment: @MarianoSuárez-Álvarez: Not with principal ideals (in a commutative ring with unity); there you always have $(a)(b)=(ab)$.
Comment: Why xz + yt isn't in I.J ? Thanks in advance
Answer:
Let $R,I,J$ be given by
\begin{align*}
R&=\mathbb{Z}[s,t]\\[3pt]
I&=(s,t)\\[3pt]
J&=(s,t)\\[3pt]
\end{align*}
Then, letting $A = \{xy\ |\ x\in I, y\in J\}$, we have
\begin{align*}
&s^2 \in A\\[3pt]
&t^2 \in A\\[3pt]
&s^2 + t^2 \notin A \\[3pt]
\end{align*}
hence $A$ is not an ideal of $R$.


404 Not found - Apache CentOS

Question: I am running CentOS 5.11 with apache/2.2.3(named) server.
I am able to view my site homepage, so I can confirm php is running correct.
However when trying to naviate to one if the pages like domain.com/wp_post1001(wordpress, mysql driven) I see the following message.
Not Found
The requested URL /wp_post1001 was not found on this server.
Apache/2.2.3 (CentOS) Server at domain.com Port 80
I see the following rows in my log file
nano /var/log/httpd/domain.com-error
<code>[Mon Dec 22 16:24:11 2014] [error]  File does not exist:  /home/FTP/domain.com/www/wp_post1001
[Mon Dec 22 16:24:14 2014] [error]  File does not exist:  /home/FTP/domain.com/www/wp_post12
[Mon Dec 22 16:25:24 2014] [error]  File does not exist:  /home/FTP/domain.com/www/wp_post402
[Mon Dec 22 16:25:34 2014] [error]  File does not exist:  /home/FTP/domain.com/www/wp_post22
</code>
I have made sure my .htaccess file exists.
I have added RewriteEngine on in /etc/httpd/conf/httpd.conf at the highest level global block, and also within my domains  block.
Fixed this by changing AllowOverride None to All
<code>    <Directory />
            AllowOverride All
    </Directory>
</code>
Comment: You can mark your own response below as the answer, given that you found it (this is [encouraged](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/)). However, if you'd searched you may have found [other relevant responses](http://serverfault.com/questions/497050/apache-allowoverride-options-directive)
Answer: AllowOverride is set to None by default, Must be changed to All
<code>        <Directory />
                AllowOverride All
        </Directory>
</code>

404 Not found - Apache CentOS


Need to query "order date" larger than "filled date" any suggestions?

Question: I have a query with over 500,000 rows of data in the output. I need to filter the criteria down so that I am comparing column "order date" to column "filled date". I want to find all orders with a filled date sooner than an order date (yes, that sounds backwards). Is there an easy way to query this in design view? I am not very good with SQL.
Comment: What database are you using? What designer are you using?
Answer: You want the SQL to look something like this:
SELECT *
FROM yourtable
WHERE filled_date < order_date

How to do it in the designer depends on which designer you are using.
Comment: @Andrew Bullock: Yes it's backwards - I *think* that's what she wanted.
Comment: your logic is backwards, however i suspect a badly worded question.
Comment: Thank you for your help. Yes, the logic is backwards intentionally. Thanks again!
Answer: try
select *
from [orders]
where [filled date] > [order date]

obviously use your field and table names


Finding $y(x)$ using a minimization problem.

Question: I am going to post a problem that I've tried to solve and I feel like I've been banging my head against the wall. Any kind of hint or advice are more than welcome.
The Problem:
Consider a 3 meter power cable, attached between two poles to a distance of $2$ meters. Find $y(x)$,a function that measures the height of the cable at each x position between $0$ and $2$. For that, consider:
$$\begin{array}{ll} \text{minimize} & \displaystyle\int_{0}^2 y(x)\sqrt{1 + y'(x)^2} dx\\ \text{subject to} & \displaystyle\int_0^2 \sqrt{1 + y'(x)^2} dx = 3\\ & y(0) = 0, \quad y(2) = 0\end{array}$$
The objective function represents the potential energy to be minimized and  the constraint is the force in wich the power cable lenght is fixed. For that use the appropriate discretization of the problem and use the resolution of the KKT method through Newton method for non-linear systems. Your solution must consider a globalization strategy for the Newton method.
What I've tried:
I've tried a different approach, using the exterior penalty method,  with the sub-problems solved by the newton method. what I've got was that
$$y(x) = a \cosh(x +a)$$
but this is wrong, I know that the exact solution of the problem is
$$y(x) = a \cosh \left( \frac{x + b}{a} \right) + c$$
It's worth reminding that $a, b, c$ are just constants.
Comment: This is a classic. Must have been solved already on Math SE. Have you tried searching for "catenary"?
Comment: Maybe this helps: Let $F'(x)=\sqrt{1 + y'(x)^2}, $ then $\int_{0}^2 y(x)\sqrt{1 + y'(x)^2} \;dx=y(2)(F(2)-F(0))+(y(2)-y(0))F(0)-\int_0^2 F(x)y'(x) dx=-\int_0^2 F(x)y'(x) dx$.
Comment: @Divide1918, thank u. I was not seeing that transformation, im goingo to try again. What do you think about this problem? how would you try to solve it?
Comment: @RodrigodeAzevedo oh my god
Comment: @Occhima Too many catenaries on Math SE? :-D
Comment: @RodrigodeAzevedo i had no idea about this, i thought it was just a random optimization problem. I believe that, like me, you're a portuguese speaker, right?
Comment: @Occhima It is *the* optimization problem ;-) Yes, I am in the Lusosphere. "Catenary", or, in Portuguese, "cadeia".
Comment: @RodrigodeAzevedo that helped a lot, Muito Obrigado!!
Answer: With the  help of Lagrange multiplier $\lambda$ the minimization problem can be posed as
Determine the stationary points for $(y,\lambda)$ in
$$
\int_0^2 y\sqrt{1+y' ^2} dx + \lambda \left(\int_0^2\sqrt{1+y'^2}dx -3\right)
$$
Now considering
$$
L = y\sqrt{1+y' ^2}+\lambda\left(\sqrt{1+y'^2}-\frac 32\right)
$$
the variation gives us the Euler-Lagrange conditions
$$
\cases{
y''(y+\lambda)-y'^2-1=0\\
\int_0^2\sqrt{1+y'^2}dx -3 = 0
}
$$
This ODE has as primitive function
$$
y(x,c_1,c_2,\lambda) = \frac{1}{2} \left(e^{-e^{c_1}(c_2+ x)-2
   c_1}+e^{e^{c_1}(c_2 + x)}-2 \lambda \right)
$$
From this point, the problem is solved numerically by a minimization process:
calling $r_1(c_1,c_2,\lambda) = y(0)$ and $r_2(c_1,c_2,\lambda) = y(2)$  we need to solve
$$
\min_{c_1,c_2,\lambda}\left(r_1^2+r_2^2+\left(\int_0^2\sqrt{1+y'^2}dx -3\right)^2\right)
$$
Follows a MATHEMATICA V 11 script which accomplishes that.
<code>Clear[lambda, c1, c2, y, x]
L = y[x] Sqrt[1 + y'[x]^2] + lambda (Sqrt[1 + y'[x]^2] - 3/2)
eq1 = D[L, y[x]] - D[D[L, y'[x]], x] // FullSimplify // Numerator
soly = DSolve[eq1 == 0, y, x][[1]] /. {C[1] -> c1, C[2] -> c2}
yx = y[x] /. soly;
r1 = yx /. {x -> 0}
r2 = yx /. {x -> 2}
int = Integrate[Evaluate[Sqrt[1 + y'[x]^2] /. soly], {x, 0, 2}]
solc1c2 = NMinimize[{r1^2 + r2^2 + (int - 3)^2, lambda > 1}, {c1, c2, lambda}]
yx0 = y[x] /. soly /. solc1c2[[2]]
Plot[yx0, {x, 0, 2}]
</code>
Comment: I don't know how to thank you
Comment: I'll try to implement this code in python


Enviar emails com HTML/CSS embutido CakePhp

Question: Boa tarde!
Estou tentando fazer uma coisa "simples", preciso enviar um email estilizado, não quero enviar apenas texto, preciso inserir tags html e css.
Antes de trabalhar com cakePHP eu usava o PHPmailler, no qual eu conseguia enviar emails com HTML e CSS in line.
Estou trabalhando em um projeto que utiliza o framework cakePHP.
Na documentação, me parece que ele tem a possibiliade de enviar emails com o css embutido, da mesma forma que eu fazia, mas todos os emails enviados vão com as tags HTML printadas como se fossem textos simples.
$email = new CakeEmail('smtp');
$email->template('contato');
$email->emailFormat('html');
$email->to('****************');
$email->subject('Contato - Fale Conosco');
$email->viewVars(array('contato' => $this->request->data));
$email->send();

Esse é o código que estou utiliando para enviar os emails e a view é:

Contato Recebido

Data: <?php echo date("d/m/Y"); ?>

Nome: <?php echo $contato['Contato']['nome']?>

Telefone: <?php echo $contato['Contato']['telefone']?>

E-mail: <?php echo $contato['Contato']['email']?>

Assunto: <?php echo $contato['Contato']['assunto']?>

Mensagem: <?php echo $contato['Contato']['mensagem']?>

Porém, quando eu deixo o parâmetro "$email->emailFormat('html');" as mensagens enviadas chegam em branco, quando eu removo esse parâmetro deixando o default(text) as mensagem chegam com o html na tela como se fosse texto simples e se eu colocar o parâmetro como "both" não chega nada.
Comment: 1º o CSS que deseja aplicar pode estar `inline` ou quer uma folha de estilo mesmo? 2º Obrigatoriamente o Email tem de passar pelo servidor?
Comment: @RicardoHenrique

O css está inline(na verdade ainda não está nem inline, queria resolver essas tags html que estão expostas no email,)  e o email não precisa passar pelo servidor.
Comment: trabalhei com algo assim, Julgo ter uma solução então aguarde que irei postar.
Comment: @RicardoHenrique Ok, estou no aguardo.
Answer: 1º Utilizei o MandrilJS que é um serviço que me envia 12 Mil emails de forma gratuita pra você (isso não é spam). funciona como meio de campo para não precisar de um servidor.
Link para acesso (é necessário criar uma conta): MandrilJS
2º Crie um formulário comum e (coloque como method POST só pra não encher a URL mas nada será enviado para um servidor) no botão de envio faça-o desta forma:
<button onClick="sendMail();return false;">Enviar</button>

3º Crie um Javascript com uma função de mesmo nome que a do botão que irá recuperar os campos preenchidos pelo usuário do formulário:
function sendMail(){
    var nome = document.getElementById("nome").value;
    var email = document.getElementById("email").value;
    var assunto = document.getElementById("assunto").value;
    var desc = document.getElementById("desc").value;
    var body = 'Nome: '+nome+'
'+
               'Email: '+email+'
'+
               'Assunto: '+assunto+'
'+
               'Descição: '+desc;

    $.ajax({
        type:"POST",
        url:"https://mandrillapp.com/api/1.0/messages/send.json",
        data:{
                'key':'sua chave aqui',
                'message':{
                    'from_email':'email que irá enviar',
                    'to':[
                        {
                            'email':'email remetente',
                            'name':'Seu Nome (ou nick)',
                            'type':'to'
                        }
                    ],
                    'subject':'Assunto',
                    'html':body
                }
            }
    });
}

OBS1: Não é necessário inserir suas senhas de email em local algum, você deverá somente se cadastrar no MandrilJS (sem inserir senha de seus emails) e gerar uma chave, chave esta que será inserida no json no local especifico (ela é gerado nas configurações).
OBS2: É necessário jQuery.
OBS3: Pode inserir o CSS nas tags
OBS4: Ambos os Emails tem de ser validos o Destinatário por rasões obvias ele irá receber os emails, o Remente por que o MandriJS envia semanalmente as estatísticas de envios e leituras dos email.
Comment: Comente aqui qualquer duvida no processo de criação de sua conta.
Comment: Obrigado pela resposta Ricardo, é uma solução.
Mas eu preciso que seja enviado do back-end, de preferencia de forma nativa com o cake.
Nesse caso que postei é de um simples formulário de contato, mas existem outros trechos que enviam email no back-end...
Ainda estou pesquisando por possíveis soluções, talvez eu utilize sua reposta para elaborar um curl e enviar o email!

Obrigado pela resposta!
Comment: OK, espero que encontre uma solução, se encontrar poste Aqui.
Answer: Boa noite,
Consegui encontrar uma solução para o meu problema.
Primeira coisa que tive que fazer foi remover as tags de abertura do HTML, mas não tenho certeza se foi isso que resolveu.
Segunda coisa que reparei, na minha pasta /app/Views/Emails/html, eu não tinha o template "contato", por esse motivo meus emails html iam sempre vazios e os emails do tipo text não.
Creio que foram as únicas modificações que fiz.
Obrigado pela ajuda!


Probability of picking exactly one correct from a pool of 6 incorrect and 4 correct

Question: So as the question says. You have 6 incorrect objects and 4 correct ones. What are the odds that, when picking 3 of them at random, you end up with exactly one of them being correct.
This seems to be quite trivial but I'm having issues since my solution differs from the provided one. Also, I've written a program that simulates it and it seems to be leaning towards my solution.
Anyways, the way I did it is just by multiplying $\dfrac{4}{10}\dfrac{6}{9}\dfrac{5}{8}$ with the result being $\dfrac{1}{6}$. The reasoning is that you first have a 4 in 10 chance of picking the correct one and then you need to pick the incorrect one 2 times with 6 in 9 and 5 in 8 chances. I thought that maybe the fact that the order doesn't matter is making my calculation off but since you can write the product as a big fraction and commute everything, that can't be the problem.
The provided solution is $\dfrac{\binom{4}{1}\binom{6}{2}}{\binom{10}{3}}$. I can see how that would work as well so I can't really say what the problem might be with their solution.
Anyways, I wrote a program that picks 3 numbers out of [0,0,0,0,0,0,1,1,1,1] at random. It does it 100000 times and the number of times it got exactly one 1 is around 18800. That's obviously much closer to my $\dfrac{1}{6}$ than their $\dfrac{1}{2}$. Is their solution wrong? If so, why?
Edit:
Now that I think about it, my solution should be the incorrect one since it answers the question of what the odds are that I FIRST pick a correct one and then 2 incorrect ones, but why would the simulation lean towards my solution then?
Comment: You calculate the probability that you *first* pick a correct one and then two wrong ones. There are $3$ possible orders here: CWW, WCW and WWC. Note that $3\times\frac{1}{6}=\frac{1}{2}$
Comment: Your first proposed solution is not right, though it can be made right by multiplying by $3$, the number of orders in which you can get $1$ correct, $2$ incorrect. As to the simulation, presumably the simulation follows the wrong analysis, the program counts the cases where you get good, then bad, then bad.
Comment: Yes, three identical numbers, which you then should add.
Comment: Your code for shuffle is wrong. "arr.Add(array[rand.Next(i, array.Count - 1)]);" picks up a random element in an array containing 6 zeros and 4 ones. You might end up creating a new list that is shuffled but not having exactly 4 1's and 6 0's.
Comment: I've noticed that (see my edit) but it still doesn't explain the simulation.
Comment: @drhab Yeah but the order does not matter here:
WWC yields $6/10\times 5/9\times 4/8$. No matter the order you still have decreasing denomitators $10\to 9 \to 8$ and the same goes for the numerator $6\to5$ and another one that is 4. The only thing you forgot is to count the number of such sequences, i.e. 3.
Comment: In any case, this is the code for the simulation if anyone wants to try and find the error. https://gist.github.com/7550678
Comment: Interestingly enough, when I remove the shuffle, it starts leaning toward 1/2. I'll leave it to someone smarter than me to find out why. In any case, consider the question answered.
Comment: You're absolutely right. At first I was using arrays and I had working code but when switching to lists I must have changed swapped the variable name for the parameter name.
Comment: Also aside, the shuffle should not matter because every look at the list is random; it doesn't matter where the 1's or 0's are located. [code](https://gist.github.com/sudarsanvsr/7551366).
Answer: I just tried running the simulation and it works (out of $100000$, I got the number of trials in which only 1 correct object picked up as $49982$, fairly converging to $\frac{1}{2}$).
Code: (Octave)

sum = 0; res = 0; a=[0,0,0,0,0,0,1,1,1,1]; for i =
  1:100000; [junk,index] = sort(rand(1,10)); pick =
  index(1); sum = sum+a(pick); b=[]; tempcount = 1; for
  j = 1:length(a); if(j == pick) continue else
  b(tempcount) = a(j); end tempcount = tempcount + 1;
  end [junk,index] = sort(rand(1,9)); pick = index(1); sum =
  sum+b(pick); c = []; tempcount = 1; for j =
  1:length(b); if(j == pick) continue else c(tempcount)
  = b(j); end tempcount = tempcount + 1; end [junk,index] = sort(rand(1,8)); pick = index(1); sum =
  sum+c(pick); if(sum == 1); res = res + 1; end sum =
  0; end


Is ASP.NET 3.5 training track independent from ASP.NET 2?

Question: I am a newbie to the ASP.NET world and I want to take the straight way for fast learning and to start producing some applications.
I want to take ASP.NET certification and training but I found that there are a lot of new features in ASP.NET 3.5 and many new features and concepts also was introduced in ASP.NET 2.
I want to take the track for ASP.NET 3.5 but can't know if it depend on the previous track for ASP.NET 2 or not?
What is the track name?
Remember I know nothing in ASP.NET, but want to start with the true track from the very beginning.
Answer: ASP.Net 3.5 is basically v2.0 with some extensions. If you look inside %WINDIR%/Microsoft.Net/Framework/ you'll see v2.0 and v3.5 but note that v3.5 lacks things like a CONFIG folder. This is because the v2.0 CLR is used by v3.5.
IMO you should study 2.0 to get all the fundamentals right first and then look at the extensions like LINQ, ASP.Net AJAX etc. once you have a good understanding of the basics.


P-values shows something different than AIC or delta AIC. What to do?

Question: I applied an glmer model on data derived from several raster (image) files. Together, my dataset had several hundred thousand rows.
My model was something like this:
glmer(subject_0_1 ~ var1 + (1 | Year), data = datsc,
      family = binomial(link = "logit"))

I had three highly correlated variables, so I 'v used three models:
glmer(subject_0_1 ~ var2 + (1 | Year), data = datsc,
      family = binomial(link = "logit"))

glmer(subject_0_1 ~ var3 + (1 | Year), data = datsc,
      family = binomial(link = "logit"))

Each model told me, that my explanatory variables is statistically significant in  relation to subject_0_1.
At the end, I compared my models with AIC, the one with the var3 had the lowest AIC value. But when I calculated the deltaAIC, it showed that the first two models are far from valid - their values were more than deltaAIC > 100.
So, variables var1 and var2 are important from the viewpoint of p-values, but deltaAIC shows that they are meaningless?
Comment: Why should $p$-values and AIC give the same result? They are based on different (though related) principles and are answering different questions. Perhaps [this](https://stats.stackexchange.com/questions/198799/aic-versus-likelihood-ratio-test-in-model-variable-selection) brief thread could be helpful?
Answer: Yes!
AIC is based on the log-likelihood and penalize according the number of parameters. So, AIC aim to find the model that maximize the likelihood of the model and the data (simplifying).
P-values, in this case, are related to this variable effect and their errors.
A variable can have a significant effect, but do not necessarily it is the best predictor in the likelihood point of view.
And remember, AIC is to compare models, suppose you do not have var3 and only have var1 and var2, if you compare the models, the AIC will rank the models with var1 and var2 and you will pick the best(s) model(s) only with one of these variables.
Hence, you are comparing very different things.
In this case, you pick the model with deltaAIC<2 or 4 (see Burnham et al. 2010). Since in you case it is only one model, you can assume that the variable which best describes your data is var3 and put var1 and var2 out according AIC.
If your best model have a non-significant variable, probably the null model is the best to describe your data, so, you can assume that your variables are not parsimonious to explain your data. (It is not your case)
I also suggest to use AICc, which is indicated to small sample sizes, if you have a big sample, the AICc will converge to AIC, thus, AICc is a safety value.
Best
Comment: Regarding your first paragraph and the aim of AIC, I am not sure I find it clear. You could say, though, that AIC aims at finding a model that will have the highest likelihood on a new observation drawn from the same population. The paragraph starting with *If your best model* is also a little confusing to me. Also, could you give a full reference for Burnham et al. 2011?
Comment: Sorry for this confusion. Yes, the highest likelihood with your population and due the parameter penalizations it aims to have the highest likelihood with unobserved data too. https://www.researchgate.net/publication/299822584_AIC_model_selection_and_multimodel_inference_in_behavioral_ecology_some_background_observations_and_comparisons


Problema com formatação de data MYSQL

Question: Estou fazendo um sistema de gerenciamento de hotel usando Javascript, NodeJS, Express e MYSQL.
Eu preciso que o meu formato de data seja do tipo DIA/MÊS/ANO, desta forma:
DATE_FORMAT(dt_entrada, '%d/%m/%Y')
DATE_FORMAT(dt_saida, '%d/%m/%Y')

Meu código SQL está deste jeito
SELECT id_reserva, quarto.num_quarto, nome, DATE_FORMAT(dt_entrada,
'%d/%m/%Y'), DATE_FORMAT(dt_saida, '%d/%m/%Y') from reserva, quarto, cliente
WHERE reserva.id_cliente = cliente.id_cliente and reserva.num_quarto =
quarto.num_quarto

Porém, quando faço um console.log(rows), ele me aparece isto.

O nome da propriedade do meu banco de dados acaba mudando para DATE_FORMAT...
Sendo que ele é dt_entrada e dt_saida.
Answer: Tenta adicionar um alias,
ex:
DATE_FORMAT(dt_entrada,
'%d/%m/%Y') as dt_entrada

Problema com formatação de data MYSQL


Underscore.js filter not returning all results

Question: I am trying to build an filtering function that works similar to the way an auto-complete field would work. I am using Underscore.js to filter an array of names. Here is a JSFiddle that demonstrates the problem:
http://jsfiddle.net/PWcVM/
And for those who would rather not jump to JSFiddle, here is the example in plain text.
HTML:

Type the name 'Craig' into the text field

<input class="query" type="text" />

There are 4 Craig's in the data array. The results below should output those 4 Craigs. For some reason, it only outputs two.

Results:

<textarea class="results" style="width: 300px; height: 300px;"></textarea>

JavaScript:
var data = ["Aaron Abram", "Abbie Hanson", "Abraham Vázquez", "Ace Marrero", "Adam D. Chaitin", "Adam Duzey", "Adam Reichental", "Adam Scott", "Adam Smythe", "Addison McCaleb", "Ahmad Childress", "Aidas Petrulis", "Aldo Nievas", "Alex Alexapolsky", "Alexander R. Lampone", "Alexandra Elizabeth London", "Alexandra Jacobs", "Alexis Jones", "Allan Louis", "Allie Tintle", "Alyssa Wada", "Amanda Armstrong", "Amanda Olmstead", "Amber Fox", "Amber Graves", "Amy Berkin-Chavez", "Amy Buggy", "Amy Rush", "Amy Schlumberger", "Andi Dzilums", "Andre Savage", "Andrew Fryer", "Andrew Rivetty", "Angel Chavez", "Angel Lewis", "Angela Truong", "Anthony Wentzel", "Anya Estrov", "Aram Homampour", "Ariana Blumenfeld-James", "Armo Movsessian", "Ashley DeMeza", "Ashley Froschauer", "Athena Asklipiadis", "Athena Stamos", "Audryn Swigert", "Augie Sanchez", "Avi Horn", "Bali Ciri Yoman", "Bali Distinction Norman", "Barnaby Hitzig", "Betty Tran Chillino", "Bill McGovern", "Blues Bob", "Bob Cribbs", "Bob West", "Bobby DiGiacomo", "Borivoj Ivanovic", "Brad Horwitz", "Brad Ormand", "Bradley F. Cole", "Brandon Jordan", "Brandon Kosoko", "Brent Nelson", "Brett Vadset", "Brian Kubat", "Bridget Betts", "Brock Winberg", "Bryan C Dickson", "Caleb Bacon", "Carlos Carreras", "Carlos Castro", "Carlos Chávez", "Caryn Saxena", "Celina Chavanette", "Ceren Güven", "Chad Buechler", "Charles Winemiller", "Charlie Diaz", "Cheri Kingsley", "Chloe Sherman-Pepe", "Chris Hackett", "Chris Han", "Chris Laughter", "Chris Mabli", "Chris McGarry", "Chris Scott", "Chris Ueland", "Christelle Penalosa", "Christine Is Lovely", "Clark McCutchen", "Colleen Steckloff Mayo", "Cory J Thomas", "Craig Adams", "Craig Duro", "Craig Fredrics", "Craig Phelps", "Curt Bonnem", "Dalilah Rain", "Damien Nemire-Pepe"];

_.each(data, function (name) {
    $('textarea.results').val($('textarea.results').val() + name + "\n");
});

$('input.query').bind('input', function (event) {
    var pattern = new RegExp($(event.currentTarget).val(), 'gim'),
        filteredResults = _.filter(data, function (name) {
            return pattern.test(name)
        });

    $('textarea.results').val('');

    _.each(filteredResults, function (name) {
        $('textarea.results').val($('textarea.results').val() + name + "\n");
    });
});

I get some results back, just not ALL of the results that should be coming back.
Any idea what I am doing wrong?
Answer: If you could get rid of the global flag from RegExp this should work.
var pattern = new RegExp($(event.currentTarget).val(), 'im');

Comment: @AdamDuro See [this related question](http://stackoverflow.com/questions/15610251/why-pattern-testname-opposite-results-on-consecutive-calls) : using the `g` modifier turns the RegExp object into an iterator. There is no reason to use this modifier when using the `test` function.
Comment: Indeed...I need a why before I can accept this answer. It does indeed fix it, but a little more background will make this answer complete.