Enabling Spring Repositories cvc-complex-type.2.4.c:The matching wildcard is strict,but no declaration can be found for element jpa:repositories

Question: The following applicationContext.xml, which does not give any warning, is causing an evil exception. Reading old threads did not help.
The main part of the exception is
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element jpa:repositories.
This is the applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<context:property-placeholder location="classpath*:spring/*.properties" />
<context:component-scan base-package="com.lh.clte" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${database.driverClassName}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.username}" />
    <property name="password" value="${database.password}" />
    <property name="initialSize" value="3" />
    <property name="maxActive" value="10" />
</bean>

<tx:annotation-driven mode="proxy"
    transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
    id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
</bean>

<jpa:repositories base-package="com.lh.clte.repository" />
</beans>

SEVERE: Exception sending context initialized event to listener instance of class     org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 39 in XML document from class path resource [spring/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 39; columnNumber: 64; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'jpa:repositories'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Caused by: org.xml.sax.SAXParseException; lineNumber: 39; columnNumber: 64; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'jpa:repositories'.
at     com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:458)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3237)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1917)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(XMLSchemaValidator.java:766)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:355)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2770)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:428)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 22 more

Jun 27, 2014 6:42:35 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Jun 27, 2014 6:42:35 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/CLTERestServer] startup failed due to previous errors
Jun 27, 2014 6:42:35 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Jun 27, 2014 6:42:35 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:921)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:579)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:115)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4980)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5626)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Adding http://www.springframework.org/schema/context/spring-context.xsd to the schema location causes the following warning to appear:
  Referenced bean 'jpaMapppingContext' not found    applicationContext.xml

Answer: Try Adding following to xsi:schemaLocation
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd

Comment: Thanks, that works! Now I got the warning I have already mentioned "Referenced bean 'jpaMapppingContext' not found". Is there a way to fix it?
Comment: Do you have a bean defined with id  "jpaMapppingContext"
Comment: I don't, but what type of bean is it?
Comment: I did not used JPA before, but what i think is that Spring is looking for a bean to set when you define JPA Respository . May be you are missing some annotation
Comment: Not sure what you mean by "missing some annotation". I am defining such kind of beans in the XML files, as they are configuration beans. Repositories are working even though that warning exists.


Comparing two time series statistically?

Question: This question has been asked before with very good (but incomplete) answers. This and this are the two best answers that I found. But following is my doubt:
Top answers from both (by IrishStat) the links suggest to fit a common model to both the time series and then globally. I understand that if the same series was split in two parts, chow test can be used comparing the estimated models of the two splits with the estimated global model.
However, if the two time series are different (say urban and rural inflation), and the comparison is to be done for the same time window, IrishStat suggests  "..( putting the second series behind the first ) . Make sure that your software recognizes the beginning of the scond series.."
Question: how to do this? Do we need to add a dummy (LS outlier type?). If so, would it not disturb the estimate of the global model. In fact there should be no global model in the strict sense. Joining two time series assumes a  dependence structure between last point of first series and first point of second series, where there may not be any.
Comment: *How* do you want to compare these series, for what purpose, and what assumptions can you make concerning any common properties they might have?
Comment: The question is pretty straight forward. You have two series. You want to check whether they are statistically same or not, i.e. same data generation process. This is akin to mean comparison for two IID samples using t-test. The same question was very well articulated [here](https://stats.stackexchange.com/questions/19103/how-to-statistically-compare-two-time-series).
Answer: I used AUTOBOX and took 21 values representing three distinct subjects ( 7 values each)  and specified an ar(1) model here

The idea is that the last point of first series and first point of second series should be restricted from affecting the model coefficients.
I directed that there were 3 groups here
The results shown here detail how the 1st , 8th and 15th residual were restricted to 0.0

with final model here reflecting a pooled estimate  and here
to test the hypothesis of a common parameter across the 3 groups , simply estimate each group separately and sum the 3 error sum of squares and perform an F test. The CHOW test can be used comparing the estimated models of the two splits with the estimated global model.
Comment: perhap we can hash this out on SKYPE as we are having a communications problem with one-sided material. Please SKYPE me or call my land line so I can help. You seem to want a parameter by parameter test , rather than a comprehensive test , a portmanteau  test , which is easily conducted as there could be many parameters in the model not just one..
Comment: Thanks for answering. What's the rationale behind restricting the residuals to be zero at break points? And wouldn't doing so immediately calculate the coefficients? For example, $x_t=\alpha x_{t-1}+e_t$. If we know that for a given value of $x_t$, $e_t$ is zero, then $\alpha=\frac{x_t}{x_{t-1}}$?
Comment: the model used was an ar(1) . there is no forecast possible for period 1 .
Comment: I meant, using this at, say, 8th residual. Since the three series are put together, the last point of series 1 is $x_7$ and the first point of series 2 is $x_8$. If by construction, we are forcing $e_8=0$, then shouldn't $\alpha=x_8/x_7$ (assuming no constant, in this example)?
Comment: a is the "best" coefficient for the model y(i)=a*y(i-1)+e(i) for  i=1,21 and where e(1),e(8) and e(15) are constrained to be  0.0 and y(0)=0.0
Comment: I have already upvoted but want to understand how it is correct. So you said that $\alpha$ is the best estimate with such restrictions on residuals. Two doubts: (1) How to get this best $\alpha$? (2) If we just fit a common ARIMA specification model  separately on both the series. Then also we can compare the estimated coefficients, isn't it? What is the need of having a global model at all and do this joining of time series?


MVC4 Compare attribute and nested object properties

Question: Getting a model error when using MVC4 Compare attribute against a nested property.
Error is as follows Could not find a property named PASSWORD.
What is the correct way to use Compare for Nested Property comparison?
User.cs
public partial class User
{
    public User()
    {
        this.Mobilizations = new HashSet<Mobilization>();
    }

    [Required(ErrorMessage="Password is required")]
    [DataType(DataType.Password)]
    public string PASSWORD { get; set; }
}

UserViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using CompareAttribute = System.Web.Mvc.CompareAttribute;

 public class userViewModel
{
    public User User { get; set; }

    [DataType(DataType.Password)]
    [Required(ErrorMessage = "CONFIRM PASSWORD is required")]
    [Display(Name="CONFIRM PASSWORD")]
    [CompareAttribute("PASSWORD",ErrorMessage="Password didnot match")]
    public string ComparePassword { get; set; }

    public IEnumerable<Designation> DesignationList { get; set; }
    public SelectList MenuList { get; set; }

    [Required(ErrorMessage="Select some menu items")]
    public string[] MenuIds { get; set; }
}

Controller
 [HttpPost]
    public ActionResult Create(userViewModel model)
    {

        if (ModelState.IsValid) //<= **Getting Model error here**
        {
            _db.Entry(model.User).State = EntityState.Modified;
            _db.SaveChanges();
        }
        return RedirectToAction("Create");
    }

The View is as follows

        @Html.LabelFor(model => model.User.PASSWORD, new { @class = "col-sm-2 control-label " })

            @Html.EditorFor(model => model.User.PASSWORD, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.User.PASSWORD)

        @Html.LabelFor(model => model.ComparePassword, new { @class = "col-sm-2 control-label " })

            @Html.EditorFor(model => model.ComparePassword, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ComparePassword)

How can i solve this issue?
Comment: Shouldn't User.Password be in inverted commas
Answer: Try like this:
[CompareAttribute("User.Password", ErrorMessage="Password didnot match")]
public string ComparePassword { get; set; }

Or, remove the User property from your ViewModel and add
public string Password {get; set;}

[CompareAttribute("Password", ErrorMessage="Password didnot match")]
public string CinfirmPassword {get; set;}

Later you can populate your User object.
And here you can find a workaround.


apache virtual host to work with django

Question: My project is under: /home/projects/testing and I'm adding this to the buttom of my /etc/httpd/conf/httpd.conf file on Centos machine, but that is not working,
<Location "/testing/">
    SetHandler python-program
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE testing.settings
    PythonOption django.root /testing
    PythonDebug On
    PythonPath "['/home/projects/'] + sys.path"
</Location>

but when requesting http://localhost/testing/jobs for example, I get:

Mod_python error: "PythonHandler django.core.handlers.modpython"

Traceback (most recent call last):

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch
    result = object(req)

.............

 File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/conf/__init__.py", line 75, in __init__
    raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)

ImportError: Could not import settings 'testing.settings' (Is it on sys.path? Does it have syntax errors?): No module named testing.settings
Answer: You want both, the projects folder and the testing folder in your PythonPath, because  your project uses paths without the "testing" in it:
PythonPath "['/home/projects/', '/home/projects/testing/'] + sys.path"

Comment: If `/home/projects/testing/__init__.py` doesn't exist, then importing `testing.settings` will fail.  I'd suggest making your python path as @reko_t suggested, but then use:  `SetEnv DJANGO_SETTINGS_MODULE settings`.  This should work weather `__init__.py` exists or not.
Comment: updated the PythonPath as instructed, and made the settings directly on settings file inside the project. Still no luck.
Comment: @reko_t: the traceback says "import error", "no module named testing.settings". Assuming that the files `/home/projects/testing/__init__.py` and `/home/projects/testing/settings.py` exist, the `/home/projects` on the path should suffice. This is why I'd say it was more likely that mod_python can't read the files, rather than can't find them.
Answer: The path looks okay to me, I've just double checked that items in sys.path work with trailing slashes.
I'd suggest that this is a file permissions issue:

Does the user apache is running under have access to the project files?
Is selinux preventing access?
Comment: made the folder with permission 777, I'm using Centos as well, there is no selinux AFAIK. Still no luck.
Comment: I've not had any exposure to Centos, but the existence of this document, http://www.centos.org/docs/5/html/5.1/Deployment_Guide/rhlcommon-chapter-0017.html would lead me to believe that Centos doesn't intrinsically lack selinux.

apache virtual host to work with django


Limit of $f(x, y)$ at $(0, 0)$

Question: I need to show
$$\lim_{(x, y) \rightarrow (0,0)} \frac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}} = 0
$$
Not really sure how to go about this without using the epsilon delta definition, which I would prefer not to. Any sort of help is appreciated.
Edit: I do have the inequality:
$$\frac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}} \le \frac{xy(x^2+y^2)}{(x^2+y^2)^{3/2}} = \frac{xy}{(x^2+y^2)} $$
Comment: Check the final line I think you made a typo
Answer: Let $(x,y) \not =(0,0)$.
$0\le |\dfrac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}}| \le \dfrac{|xy||x^2+y^2|}{(x^2+y^2)^{3/2}} $
$\le \dfrac{(x^2+y^2)^2}{(x^2+y^2)^{3/2}}= (x^2+y^2)^{1/2}.$
Used:
1)$|x^2-y^2| \le |x^2+y^2|;$
2)$x^2+y^2 \ge |xy|$.
Answer: Use polar coordinates: by letting $x=r\cos(\theta)$ and $y=r\sin(\theta)$, we have that
$$\frac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}}= \frac{r^4\sin(2\theta)\cos(2\theta)}{2r^3}=\frac{r\sin(4\theta)}{4}.$$
Therefore
$$\left|\frac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}}\right|\leq \frac{r}{4}$$
and the right-hand side goes to $0$ as $r\to 0$.
P.S. Your equality is too "weak" for the job: by taking $y=x$ the right-hand side is $\frac{1}{2}$.
Comment: Thanks, are using polar coordinates quite a common approach to solving such limits? Haven't encountered their use before
Comment: Yes, it is. You can find more examples in this site. For example: https://math.stackexchange.com/questions/3297618/calculating-lim-x-y-to0-0-fracx2yx2y4
Answer: Let $y=tx$. Then
$$\frac{xy(x^2-y^2)}{(x^2+y^2)^{3/2}}=\frac{x^2tx^2(1-t^2)}{x^3(1+t^2)^{3/2}}=x\frac{t(1-t^2)}{(1+t^2)^{3/2}}.$$
As the fraction remains bounded for all values of $t$, the limit is $0$.
Comment: I think this is not true, because the existsence and equality of the limits along all of the lines through the origin won't imply the existence of the original limit. (See, for example, my old question: https://math.stackexchange.com/questions/2741516/is-there-an-mathbbr2-to-mathbbr-function-with-the-following-limit-pr )
Comment: @Botond: I never spoke about a limit along all lines in the sense of constant $t$. $(x,y)$ and $(x,t)$ are equivalent 2D representations, as $t$ spans all of $\mathbb R$. Feel free to retract your downvote.
Comment: I see. I thought that you fixed $t$. But I did not downvote your answer, so I can't retract it, just give you an upvote :) (I prefer to not upvote and ask for clarification over downvote, especially in the case of smarter people's answers)
Comment: @Botond: sorry for suspecting you :-)

Limit of $f(x, y)$ at $(0, 0)$


Front page has a shortened form of my articles

Question: In my Main Page Content block, I'm getting a list of recent articles with a "Read more" link.
What do I do if I want the whole article to appear on the front page?
Answer: I'm going to make a couple of assumptions that you are using Drupal 8, and that the front page is using the default Frontpage view. In this case, you can edit the view by logging in as an administrator and editing the view page under Structure - Views - Frontpage (or go to the path admin/structure/views/view/frontpage/edit/page_1). In the first column of this page there is a section called FORMAT. Under the FORMAT section there is a Format and Show row. My guess is Show is set to show content using the teaser view mode. You can change this to show the full content by clicking on "Teaser" and selecting "Full content". After you save the view then you should see the full content of the article on the front page.


what are the valid values for Timezone in icinga-web?

Question: the documentation rightly points out that I can change the timezone in /etc/icinga/web/conf.d/translation.xml, but what are the valid values for timezone?
GMT (Greenwich Mean Time) is the default, EST (Eastern Standard Time) seems to work, but what I really want is EDT (Eastern Daylight Time), which is EST, but with daylight savings time awareness.
Answer: The original problem sources from the underlaying agavi framework in combination with php not exposing the system timezone by default anymore (details: http://trac.agavi.org/ticket/1008)
etc/conf.d/translation.xml was added to Icinga Web for those people not being capable of modifying their php.ini - once you set the correct timezone (i.e 'Europe/Berlin') agavi and Icinga Web will be satisfied again. http://php.net/manual/en/timezones.php
Other than that, you may still play around with translation.xml and set values like 'GMT+6' or similar, but i would rather suggest fixing your php.ini anyways.


Align font baseline inside DIV or display content "outside" canvas

Question: I have a little design issue, which I cannot seem to get my head around.
Maybe I can find some creative minds here who can point me into a direction - I believe I have a creativity blockade right now :(
Please have a look at the following example, before I explain. That makes things easier:
http://jsfiddle.net/DV9SE/3/
<canvas id="mycanvas" width="100" height="20"></canvas>

ASDqpjy

#mycanvas {
  position:absolute;
  left:20px;
  top:20px;
  border:1px solid #999999;
}
#mydiv {
  position:absolute;
  height:20px;
  width:100px;
  left:20px;
  top:50px;
  border:1px solid #999999;
  font-family:arial;
  font-size:14px;
  line-height:2.2;
}

var canvas = $('#mycanvas')[0];
var ctx = canvas.getContext('2d');

ctx.font = '14px arial';
ctx.fillText('ASDqpjy', 0, canvas.height);

As you can see, it is very easy to put the baseline of a text at the very bottom of a canvas element. Which is precisely what I need for a project. The baseline must be at the bottom of an element (which I can later render movable through JQuery).
The problem though: the text is cut off, as, evidently, the lower parts would be outside of the canvas and can thus not be rendered.
An alternative - or so I thought - was to put everything in a DIV, which makes rendering parts of the text possible, that is outside of the actual border/margin. The problem here though: I have to adjust the baseline by using css line-height. That is not an issue when it comes to one or two fonts. But since the project will allow for a font-selection with tens of fonts, it would be a complete nut-job to create a pixel-precise line-height rule for every single font.
Does anybody have an Idea how to work around this problem? How to possibly move the baseline of fonts consistently to the bottom of a DIV element, or a creative solution, how to display parts in a canvas, that are actually "outside" of it? ;)
Thanks a ton SO!
Answer: You can use display:table-cell and vertical-align:bottom. Like here:
http://jsfiddle.net/DV9SE/1/
Comment: Thanks a lot for your answer Tim. Your solution is not exactly what I was looking for though. You see, in your example, the font baseline is not precisely on the bottom margin of the div. The bottom of the "bounding box" is. But I need the baseline to be, like in the canvas.
Comment: It looks like you can replicate that by setting the `line-height` to be half of the `font-size`. Is this more like it? http://jsfiddle.net/DV9SE/2/
Comment: Almost, but not exactly it either, I've tried this too. If you use a font-size of 60 or above and set the line-height to 30+ accordingly, you will notice that it is not exactly putting the font baseline to the lower div margin. Also, this solution did not work when I used more "unusual" fonts like calligraphic ones for example.
Comment: Maybe I should explain that the baseline position is so imperative in this project, because its exact coordinates are later sent to a php script which creates a PDF with POST-sent data. Thus the position is very important to be precise.


sklearn.gaussian_process fit() not working with array sizes greater than 100

Question: I am generating a random.uniform(low=0.0, high=100.0, size=(150,150)) array.
I input this into a function that generates the X, x, and y.
However, if the random test matrix is greater than 100, I get the error below.
I have tried playing around with theta values.
Has anyone had this problem?  Is this a bug?
I am using python2.6 and scikit-learn-0.10. Should I try python3?
Any suggestions or comments are welcome.
Thank you.
gp.fit( XKrn, yKrn )
  File "/usr/lib/python2.6/scikit_learn-0.10_git-py2.6-linux-x86_64.egg/sklearn/gaussian_process/gaussian_process.py", line 258, in fit
    raise ValueError("X and y must have the same number of rows.")
ValueError: X and y must have the same number of rows.

Answer: ValueError: X and y must have the same number of rows. means that in your case XKrn.shape[0] should be equal to yKrn.shape[0]. You probably have an error in the code generating the dataset.
Here is a working example:
In [1]: from sklearn.gaussian_process import GaussianProcess

In [2]: import numpy as np

In [3]: X, y = np.random.randn(150, 10), np.random.randn(150)

In [4]: GaussianProcess().fit(X, y)
Out[4]:
GaussianProcess(beta0=None,
        corr=<function squared_exponential at 0x10d42aaa0>, normalize=True,
        nugget=array(2.220446049250313e-15), optimizer='fmin_cobyla',
        random_start=1,
        random_state=<mtrand.RandomState object at 0x10b4c8360>,
        regr=<function constant at 0x10d42a488>, storage_mode='full',
        theta0=array([[ 0.1]]), thetaL=None, thetaU=None, verbose=False)

Python 3 is not supported yet and the latest released version of scikit-learn is 0.12.1 at this time.
Answer: My original post was deleted. Thanks, Flexo.
I had the same problem, and number of rows I was passing in was the same in my X and y.
In my case, the problem was in fact that I was passing in a number of features to fit against in my output. Gaussian processes fit to a single output feature.
The "number of rows" error was misleading, and stemmed from the fact that I wasn't using the package correctly. To fit multiple output features like this, you'll need a GP for each feature.


Get information from a node that has just been saved to update a different node

Question: I have 2 different content types "factory" and "measurement" that are related with an entity reference field. I am using a computed field to store the latest measurement as a field of the factory content type. The problem is that in order for the computed field to be "re-computed", the factory node that the measurement refers to, needs to be updated.
My first thought was to batch update all the factory nodes in predefined intervals. This has a very important downside: the factory information (and specifically the latest measurement that I'm interested in) will not be updated until the batch update is executed.
My next thought was that I could use a hook whenever a new measurement is created and update the corresponding (=the one that the entity reference points to) factory. The problem is that hook_node_insert will not give me the information that I want (i.e. the entity reference field that points to the factory) since in the hook's description it states clearly that:

You should not rely on data in the database at this time as it is not
  updated yet.

Is there any other way to execute a piece of code whenever a new node of specific type (i.e. measurement) is saved/created and have the node's fields available in my code? How do Rules do it?
P.S: I thought about using Rules but it seems like an overkill for such a simple thing to install a pretty heavy module.
Answer: In hook_node_insert($node) you cannot reliably read saved node's data from database, but you can read data from $node object provided to that hook.


How to save the URL of anonymous user on a webform?

Question: Using Webform 7.x-3.18, I'd like to save the referring URL of an anonymous visitor on a webform. I added some code to MYTHEME__preprocess_page() in template.php to save the info as a cookie:
user_cookie_save(array('webform_referrer' => $_SERVER['HTTP_REFERER']));
On my webform I added a hidden component, with a default value of %cookie[Drupal_visitor_webform_referrer].
I'm testing with safari/chrome/ff on a Mac and on Windows. I can get this to work on my local testserver, but only about 10% of the time on the production server, and never from Windows to the production server. The production server has hardware load balancing. I'm suspecting this is a caching issue. I've also read that server vars may not be available as webform default values for anon users (http://drupal.org/node/296453#comment-2397674) - is this the issue? Why then would it be working for anon users coming to my local server?
I can't think of another way to integrate this easily into webform as a hidden field. Perhaps I have to write some kind of custom hander to save the referrer?
Comment: That won't work, because the value is recorded when the webform is submitted. And when it is submitted, the referring page is contact-us, so we would never see the real referring page. That's why I'm capturing the original referrer in a cookie. But thanks for the suggestion.
Comment: Have you tried  %server[HTTP_REFERER] as default value for your webform's hidden field?
Answer: So you can achieve this using form alter,
create a text field namely 'refer_url' for saving referring url, then using following snippet in your module you can save the referring url. You can hide this field in display using css or form alter.
<code>function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_27') {
    $form['submitted']['refer_url']['#default_value'] = $_SERVER['HTTP_REFERER'];
    }
}
</code>
Comment: Same problem - when the page is first loaded, the default value is correctly set. I set a breakpoint in my form_alter. When the form is submitted, I reach it again, and this time the referrer is set to the webform, not the site I was coming from. That's why I tried using a cookie to save the value and stash it.
Comment: Are you tried this with textfield, i got it working perfectly. However it is the same case as you said for the hiddenfield. Try with textfield and just hide it using css in frontend


Alinhamento de Inputs text em HTML/CSS

Question: Como faço para alinhar esses dois input?
Já estou tentando há mais de 2 dias e não consigo fazer eles se alinharem corretamente.
Comment: Nickolas, se alinhar em relação a que? Poderia colocar aqui o código que você já fez, mesmo estando errado poderemos corrigir.
Answer: Para este caso existe algumas soluções.
O que posso te aconselhar a fazer, é colocar o label e o input em divs diferentes e controlar o tamanho deles através destas divs.
Desta forma, todos os label terão o mesmo tamanho, forçando o alinhamento dos inputs. Neste caso será importante alinhar os label a direita.

body {
    position: fixed;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    margin: 0px;
    padding: 0px;
}

#container {
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    width: 360px;
    height: 120px;
    margin: auto;
    box-shadow: 0px 0px 10px black;
    padding: 20px;
    box-sizing: border-box;
}

.row {
  clear: both;
}

.column-3 {
    width: 25%;
}

.column-9 {
    width: 75%;
}

.label {
    padding-top: 7px;
    text-align: right;
}

.label:after {
    content: ':';
    padding-right: 5px;
}

.column {
    float: left;
    height: 41px;
}

.input input {
    width: 100%;
    height: 34px;
    padding-left: 5px;
    box-sizing: border-box;
}

            Logon

            <input type="text" id="txtLogon" />

            Senha

            <input type="password" id="txtPassword" />

Em todo caso, é interessante que atualize a sua pergunta com o que você já fez, assim fica mais facil complementar o seu código.
por fim, aconselho a leitura do seguinte artigo (no exemplo acima eu utilizei o alinhamento a direita):
Label Placement on Forms
Answer: Tudo depende da tua markup atual, mas recorrendo apenas a CSS, sem introdução de novos elementos na markup para além dos requeridos, conseguimos resolver a questão:

form,
label {
  display: block;
  padding: 10px;
}
form {
  width: 270px;
  margin: 10px;
  background-color: rgba(0, 0, 0, 0.5);
}
label {
  color: #FFF;
  text-align: right;
}
input {
  display: inline-block;
  padding-left: 10px;
}
<form>

    Login:
    <input type="text" value="" id="username" name="username" />

    Senha:
    <input type="text" value="" id="username" name="username" />

</form>

Alinhamento de Inputs text em HTML/CSS


How to alter/hide the label of the input element in form (create/edit)?

Question: We can theme the label of any field in tpl or even simply by changing the manage display option but wondering how to do the same in form (while creating or editing a content) ?
I'm looking for the proper way to alter/hide the label especially with field collection fields when the content is created or edited.
Answer: You can do this with hook_form_alter() or hook_form_FORM_ID_alter() in your custom module or also in your theme's template.php file.
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form_id
  if ($form_id == 'YOUR_FORM_ID') {
    // To hide the label
    $form['your_form_element']['#title_display'] = 'invisible';
    // To alter the label
    $form['your_form_element']['#title'] = t('Your new title');
  }
}

If you use hook_form_FORM_ID_alter() instead, you don't need to check the form_id.
You can find more information on the Form API Reference for the #title and #title_display attributes, and also all the other form elements and their attributes.
In case of Field Collection, it can be a bit complicated. Below is an example code:
function YOURMODULE_form_YOUR_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $your_field_collection = element_children($form['your_field_collection'][LANGUAGE_NONE];
  foreach ($your_field_collection as $key => $value) {
    if (is_numeric($value)) {
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title'] = t('Your new title');
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title_display'] = 'invisible';
    }
  }
}

Explanation of the above code:
First I assigned the field collection itself to a variable, to make it a bit readable. I used LANGUAGE_NONE for simplicity but a better practice would be to use $form['your_field_collection']['#language'], admittedly it makes the whole code more complicated to read.
Second, I used a foreach, since most of the time we use a field collection if we want to have multiple values of some collection of fields. So the foreach loop would take care of all instances of the field collection.
Third hack, is a dirty trick I learned from someone on Drupal.org, maybe there would be a better approach, but it just works so I didn't dig into. I check if the $value is numeric, to exclude all other meta attributes and loop only through the elements.
Then, finally, in each element I alter the field in the field collection.
Comment: Thanks. But in case of field collection, its not having any of those attributes attached with
Comment: It surely does, but the field collection is a little bit complicated depending on how you configure the field collection field. If you use the 'Embedded' widget, you should be able to find the fields in your form array.
Comment: its embedded widget only, but still nothing happening. I'm not trying to do anything with field collection but with field collection fields is whre I want to change the label
Answer: This will help you.
/**
 * Implements hook_field_widget_form_alter().
 */
function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#entity_type']) && $element['#entity_type'] == 'field_collection_item' && $element['#bundle'] == 'YOUR FIELD COLLECTION') {
    $element['value']['#title_display'] = 'invisible';
  }
}

Comment: Using `invisible` will still render the label but it will be hidden. You can use `hidden` to prevent label from rendering.
Answer: The field_display_label module solves this by adding a separate display label.
This way, the original field label appears exclusively on the create/edit form, while the display label (if set) appears exclusively on the view page.
So by setting the original field label to nothing, you can remove the label in the create/edit form only.
Answer: Using hook_form_FORM_ID_alter() trying to act on the node edit form, this worked for me:
function MYMODULE_form_NODE_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_MY_FIELD']['und']['#title_display'] = 'invisible';
}

(Substitute your values for values in ALL CAPS.)


Correct fingering for soprano recorder

Question: In the following diagram, is the fingering for Si 2 incorrect?  Someone said it is not the real fingering, but an alternative with the wrong tuning.
He also said that the Baroque fingering for high Do# is wrong.
What do you guys say?
Comment: Given that there's a Si1, it's possible that they're *all* alternatives of each other. For everyone else's sake, I think the OP's "Do#3" is labelled "DO# bar" in the diagram, though correct me if I'm wrong.
Answer: The fingerings listed as "Si2" is a correct one. It's an alternate fingering for use with the Do right above it.
Regarding the high Do#, that's a particularly nasty note on the instrument, and is considered borderline unplayable. The fingering I know is 1-3|4-6 with the end of the instrument blocked (either with your pinky finger, or with your leg, depending on the size of the instrument). But notes this high are so finicky that ideal fingerings can differ between different models. The listed ones may work.
Comment: Another fingering for the high C# (Do#3) that works on some instruments is ---|45, but only slurring upward from Si2.

Correct fingering for soprano recorder


Docker copy files to and mount same folder

Question: I am working on 'tomcat:7.0.75-jre8-alpine' base image and want to deploy my web application alongwith its configurations file. Below is what I am doing in Dockerfile:
<code>......
COPY <my-app-configurations> /org/app/data
COPY <my-app-configurations> /org/app/conf
......
CMD ["catalina.sh", "run"]
</code>
And I am using below command to create a container from above image:
<code>$ docker run -p 8080:8080 -v "/c/Users/jaffy/app:/org/app" myapp-image
</code>
'/c/Users/jaffy/app' folder is initially empty and I want to get all contents of '/org/app' in it and remains in-sync.
Initially, all configurations are copied in '/org/app' folder but when '/c/Users/jaffy/app' is mounted, '/org/app' gets cleaned/emptied.
How can I solve this issue that host machine folder remains empty initially but afterwards it reflects the exact state of container's '/org/app' folder and its sub-directories.
Thanks a lot in advance.
Comment: I don't think it is possible to mount something at build time. Is this a special usecase? You can put your app and conf files in a folder you use as build context.
Answer: There is no way to keep the container's folder content when you mount/share a volume over that folder, because the command is replacing the folder not merging it.
If you don't need to replace all the files in the folder you could just mount the file that need to be changed like:

$ docker run -p 8080:8080 -v "/c/Users/jaffy/app/web.xml:/org/app/web.xml" my-app-image


Trocar cor da div ao passar o mouse por cima

Question: Boa tarde,
O código abaixo gera um quadrado vermelho toda vez que clico no botão "Criar quadrado vermelho". Mas agora preciso trocar a cor desse quadrado toda vez que passo o mouse por cima dele, tentei fazer isso com o código abaixo, mas não consegui.
Alguém poderia me ajudar?

        Criar quadrado vermelho

Answer: Caso queira mudar sempre para a mesma cor (azul, por exemplo), eu sugeria fazê-lo com css, ou seja, definir uma classe para os quadrados que são adicionados e depois definir o css para quando passa por cima.
No onclick do btnElement, adicione divNova.classList.add('square);. Depois defina a seguinte regra em css:
.square:hover {
   background-color: blue;
}

Update
Usando apenas js:

var btnElement = document.querySelector('button.botao');

function getRandomColor() {
    var letters = "0123456789ABCDEF";
    var color = "#";
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
var newColor = getRandomColor(); // #E943F0

btnElement.onclick = function () {
    // cria um novo elemento div
    var divNova = document.createElement("div");
    divNova.style.width = '100px';
    divNova.style.height = '100px';
    divNova.style.backgroundColor = '#f00';
    divNova.onmouseover = function() {
      divNova.style.backgroundColor = getRandomColor();
    }

    // adiciona o novo elemento criado e seu conteúdo ao DOM
    var divAtual = document.querySelector('app');
    document.body.insertBefore(divNova, divAtual);
}
<button class="botao">Add Square</button>
Comment: Então, mas no caso eu preciso trocar para uma cor aleatória, gerada pela função getRandomColor(). Como eu poderia fazer isso?
Comment: Neste caso terá que registar a ação `ommouseover` antes de adicionar o elemento à DOM. Atualizei a resposta, por favor verifique.


Uploadifive: Show error/result from uploadifive.php at each queue element

Question: I'm using uploadifive (non-flash version of uploadify), for uploading with jquery and php
I'm looking for ways to treat what is being returned (echo'ed) from uploadifive.php, same way as errors/results are shown by jquery on each file queue element
 'onUploadComplete (or maybe onProgress)' : function(file, data) {
 // show the php result/error at the queue element
 }

As it is now, it says "Completed" for the file no matter what php returns
I'm thinking, I should fiddle around with the uploadifive.js file.. but where excactly and how?
Answer: I have just had the same problem and found that "file.xhr.responseText" will output the content echoed by the backend script.
Good Luck!
Comment: Yes, I discovered that too by investigating the script ;) Thanks
Comment: How exactly is this the correct solution? I'm encountering the same problem but I don't know how to fix it.
Comment: This is solution with "file.xhr.responseText" and this definitively save my day - Thanks!  http://www.uploadify.com/forum/#/discussion/9139/custom-errors-dont-register-says-completed-instead-/p1
Answer: You can access the data echoed in the script in the data variable…
Then you can handle it as you want :
For instance, if everything is ok I don't echo anything, but if something wrong happens (file too big, bad format …) I echo the message in my php script and then
'onUploadComplete': function (file, data) {
                    $('#uplodifive_errors').append('
File "' + file['name'] + '" : ' + data + '
');
                },

I show it in a error div.


How to upload multiple images as multiple nodes?

Question: I built a social network website that is like Instagram (users can follow each other, upload images and ...) but it focuses on some event. People send us tens of thousands of images every year and we present them on their profile in the website.
Every thing is fine with this website. The only problem is for users who send many images (usually more than 50), It is difficult for them to click on Create New Content link for every image and save that image and create new content again. To solve this problem I allow the images content type to have unlimited number of image field and used Multipleupload Imagefield Widget to allow users to select multiple files at once.
But every content must have exactly one image, so if a user selects multiple images for a content, we need to have a mechanism to separate every image as a distinct content, we can also share the Title of the content among all of them.
The only solution I found so far is to build a module that check for the number of images and create new content for each one on node save hook. I would like to know is there any other solution? any module or strategy to handle this requirement?
Thanks.

UPDATE
as @Gokul N K recommended I installed Bulk File Nodes Module, I also installed Plupload module. After selecting the Image field in Bulk Photo Node Settings vertical tab, This is what I see in node/add/image

and I can't add any image, By clicking on next button this page is reloaded.
Answer: Check out Bulk File Nodes Module

Bulk File Nodes allows a user to upload or import many files at once,
  and have many individual nodes created, one for each file . Where this
  module significantly differentiates from other modules like Bulk Media
  Upload is that after uploading/importing the file(s), the user is
  given the opportunity to edit all of the fields for each node in a
  single form.
Another form to the right acts as a bulk settings form where each
  field that has a value is applied to each node's corresponding field,
  except where the user has overridden the bulk settings form by
  specifying a value in the field of an individual node.
Comment: I found the problem, I had to copy `plupload` in to `/libraries` folder
Comment: Your solution is promising but I encountered a problem. I updated my question, Please check it out.


How do I a wmic path query result which is converted to a "Boolean", into a variable?

Question: From the other Stack Overflow article, I found a very useful piece of code. With my modifications, it returns "true" or "false" if a specific USB device is plugged in.
Is it possible to get this "true" or "false" into a batch variable?
I want to run a batch file who installs a driver automatically if the USB device is plugged in
I already tried the for /F command with a lot of different configurations but
I always get the error:

2>&1 was unexpected at this time.

Here is the query that is actually working:
wmic path Win32_PnPEntity where "Manufacturer like 'Lenovo' AND Caption like 'Thinkpad USB 3.0 Ethernet Adapter'" get Manufacturer 2>&1 > nul | find /V "" > nul && (echo False) || (echo True)

And this is just one variation of for /f comments I tried...
for /f "tokens=2 delims=2>&1" %%a in ('wmic path Win32_PnPEntity where "Caption like 'Thinkpad USB LAN'" get Caption 2>&1 > nul | find /V "" > nul && (echo False) || (echo True)') do set TEST= %%a

Comment: If you want to use `Like`, then where are your wildcards?
Answer: Special characters like >, &, ), etc. must be either escaped or quoted when used within the IN('cmd') clause of FOR /F.
It is important to know that the IN clause command is executed via CMD /C, which has special quote handling behavior described by the help. In your case, the simplest option is to add enclosing double quotes just inside the single quotes as follows:
for /f %%A in ('"wmic path Win32_PnPEntity where "Manufacturer like 'Lenovo' AND Caption like 'Thinkpad USB 3.0 Ethernet Adapter'" get Manufacturer 2>&1 > nul | find /V "" > nul && (echo False) || (echo True)"') do @echo %%A

The implicit CMD /C will remove the outer most quotes after the IN() clause has been safely parsed. Your WHERE clause is also quoted, so in the first parsing pass, it is not quoted. This is OK because your WHERE clause does not have any special characters. If it did, then you would have to do some escaping somewhere.

Add the extra quotes as I have them, and then escape any special characters in your quoted WHERE clause.
Or use the original form without the extra quotes and escape any special characters that are not quoted (all characters not in the WHERE clause in your case).
Comment: @Compo - Yes, the use of `LIKE` without wildcards is odd, and possibly suspect. But it is not relevant to the central question.
Comment: This really helps me a lot! Thank you so much for this detailed explanation!


Mixing general WPF styles with ResourceDictionary

Question: I came from web development and WinForms to WPF and maybe I didn't get the concept yet.
I'm able to define general styles for my Application in the app.xaml. For example I defined the style for all my ribbon controls in this file.
Then I tried Microsoft Blend and came across ResourceDictionary, which is somekind of Resource File .resx I knew from WinForms.
But as I see it's not possible to mix these two concepts. For example following xaml code will not work because ResourceDictionary have to be the only child.
<Application x:Class="Wpf.MyApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
             StartupUri="MyMainWindow.xaml">
    <Application.Resources>

        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/RibbonStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <BitmapImage x:Key="IconDokumentNeu" >Images/NewDocument_32x32.png</BitmapImage>
      <SolidColorBrush x:Key="LightGrayBrushKey">WhiteSmoke</SolidColorBrush>
    </ResourceDictionary>

    </Application.Resources>
</Application>

It seems I didn't really get the concept. Maybe you can help me, why this is not possible and how I can use general styles next to ResourceDictionary.
Answer: You already have resources defined "next to" the dictionary, one image and one brush.
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

        </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>
</Application.Resources>

Comment: I know, but how I got it from MSDN descriptions, styles in a ResourceDictionary must have a key. But I want to define general styles without a key so they would be enabled as default.
Comment: @René: So the problem is that you get an error if you add a style with the same TargetType as a style in the merged dictionary?
Comment: Nope. I just didn't know that Resource Dictionary takes styles with just a TargetType without a key. Until now...
Answer: Just include the {x:type} style in the resource dictionary
  <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>

           </ResourceDictionary.MergedDictionaries>

     </ResourceDictionary>


Monte Carlo / Gambler's Fallacy in fair coin toss: why bet on Tails after 26 consecutive Heads

Question: given a fair coin that tossed Heads 26 consecutive times, we need to decide whether gamble on Tails and provide a logical statistical explanation.
Since this is a fair coin and the probability of each event is 1/2:

after 26 consecutive Heads, the probability of Tails remains equal to the probability of Heads (1/2).
the probability of every sequence appearing is equally very low 7.45e^-9: HHHHHHHHHHHHHHHHHHHHHHHHH has the exact same probability as HHHHHHHHHHHHHHHHHHHHHHHHT which has the exact same probability as HTHTHTHTHTHTHTHTHTHTHTHTHT

Nevertheless, my biased human intuition tells me to bet on tails. What is the correct theoretical foundation? ..or is this just a common misconception of chance?
Appendix:

simulating 10,000 tosses I observed maximum of 12 consecutive Heads

Thank you
Comment: Since the tosses are independent, what happened in the 26 previous tosses does not impact the probability of a tail in the next toss.
Comment: If anything betting on tails is the only answer that you cannot really justify. Betting on heads through an evidence of bias argument, or betting on no impact through a gamblers fallacy argument are the only real two bets you can justify.
Comment: So what is the rational argument to change my biased human intuition that tells me to bet on tails simply because "after 26 consecutive Heads, the coin must toss Tails very soon"?
Comment: The rational attitude is to question the fairness assumption. (Even though [coin tossing is always fair!](https://www.npr.org/transcripts/7320273)) Or the "observation" of 26 tails in a row.
Comment: I agree. But let's assume we know for certain the coin is fair. What is the probability of the 27th toss to be Tails in order for the coin to be fair? Please let me know if I explained myself.
Comment: The (joint) probability for having 27 tail tosses in a row is $1/2^{27}$, just like the probability of any fixed sequence. The marginal probability of having a tail on the 27th toss remains $1/2$.
Answer: The key points here are that we are told (1) that the coin is fair and (2) that each flip is completely random and independent from the previous flip. If these two conditions are met, then the probability of the next flip being tails is 1/2. If the conditions are NOT met, then the probability is unlikely to be 1/2.
If we didn't know if the coin was fair, and we observed 26 heads in a row, suspiciousness should be fully aroused. This would be very strong evidence that the coin is not fair. Betting on heads would be the thing to do. (In your example, we assume the coin is fair so this does not apply here)
As Xi'an commented, the fact that each toss is independent means that the "history" is complete irrelevant. If the flips are not independent, then the history could give us information about the next flip. (Again this does not apply to your question because we are assuming independent flips.)
Comment: Good point. This makes me think that knowing for certain the coin is fair, then at some point we need to observe at some Tails. Therefore, there must be a way to calculate the probability of T for the next tosses in order for the coin to be fair. What do you think?
Comment: You aren't guaranteed to observe a tails. The probability of observing all heads under the assumptions of the problem tends to one as the number of flips tends to infinity. But, this does not mean you *must* observe a tails.


Sublime Text 2 - Encoding UTF-8 não funciona

Question: Estou com problemas na edição do código, não consigo modificar o Encoding para UTF-8 de acordo como está em meu código logo abaixo. Seleciono a opção no Sublime "File> Reopen with Encoding> UTF-8" mas não funciona:

Estou usando:
<code>meta http-equiv="Content-Type" content="text/html; charset=utf-8"
</code>
Obs.: Utilizo o Sublime Text 2.
Answer: Tente salvar com a codificação UTF-8 sem BOM, assim:
Comment: Oi Gabriel, funcionou! Abs


Irreducible algebraic group with unipotent lie algebra

Question: Let $G$ be an irreducible algebraic group with corresponding Lie algebra $\mathfrak{g}$ , which is unipotent. I'm trying to prove that $G$ is unipotent in this case.
What I know is that exponential map $\mathbf{exp}: \mathfrak{g} \rightarrow G$  is a morphism, and if $\mathbf{exp}\;\mathfrak{g}$  is closed in Zarisky topology then due to irreducibility of $G$ it is closed under left shifts in $G$, and since it ($\mathbf{exp}\;\mathfrak{g}$) contains identity element of $G$, it follows that $\mathbf{exp}\;\mathfrak{g}=G$. So that, all that i need is to show that $\mathbf{exp}\;\mathfrak{g}$ is closed. Can someone help?
Many thanks in advance!
Answer: It is very likely the consequence of isomorphism of nilpotent and unipotent operators (as varieties) induced by $\mathbf{exp}$.


Monitorando banco de dados MySQL c/ aplicação Java

Question: Eu tenho uma aplicação Java desktop c/ DB MySQL rodando em 100 filiais da empresa a mais de 6 anos. Hoje na matriz precisamos de algumas informações do banco de dados das filiais. Estou desenvolvendo um web service Rest, para realizar essa integração.
A primeira vez que acontecer essa integração, a aplicação desktop vai enviar todos os registros de 3 tabelas diferentes (em média vai ser algo em torno de uns 3000 registros por filiais). Ainda estou verificando a melhor maneira de realizar este bulk insert para não ficar tão pesada as transações.
Depois disso, apenas 1 vez ao dia as filiais vão enviar p/ o WS apenas as novas alterações e novos registros dessas 3 tabelas.
Gostaria de saber se existe uma maneira de realizar um monitoramento desse tipo, quando acontece qualquer mudança no banco de dados, mais específico essas 3 tabelas?
Ou se devo implementar alguma rotina para que tudo que for inserido, alterado ou removido, eu crie um arquivo na pasta da aplicação, e quando realizar o login no aplicativo desktop, enviar esse arquivo p/ o WS consumir e depois deletar este arquivo?
Estou meio perdido, pesquisando bastante e não encontrei nada ainda que seja uma melhor opção para este meu caso.
Valeu galera

Estou pesquisando agora algo como um sistema de auditoria, andei lendo
  sobre o Hibernate Envers e também estive pesquisando sobre Broadcast.
  Estou analisando e verificando se isso possa ser um caminho para solucionar este caso em particular. Alguém já trabalhou ou conhece essas "possíveis" soluções?

Estou realizando alguns testes, ainda em rede mesmo, e pegando outros
  micros para simular como se fosse filiais da empresa, claro que ainda
  esta longe do cenário real, mas só para ter uma idéia. Além do JMeter,
  existe alguma outra tecnologia para realizar estes tipos de testes?
Comment: Galera fiz um post maneiro sobre Hibernate Envers, lá eu ensino como customizar a auditoria de ações do hibernate e como consumir os dados gerados nessas tabelas de auditoria do envers por meio de codigo java.. ficou bem fácil de entender, bem bacana e tira essa dúvida sua amigo.. qualquer dúvidas, estou a disposição!! http://www.redspark.io/utilizando-o-hibernate-envers-com-spring-mvc/
Answer: Se o seu objetivo é receber dados de vários bancos e armazená-los em um banco de dados central, eu sugiro que você utilize um recurso do próprio MySQL, o Multi-Source Replication.
Com indicado neste site, um banco de dados MySQL pode agora se tornar slave de diversos masters:

Eles disponibilizam alguns tutoriais aqui.
Mas neste site, tudo parece bem mais simples! (Esse link eu achei aqui.)
Comment: Obrigado Daniel
Curti esses tutoriais, vou estudar mais sobre replicação.
As filiais estão usando o mysql 5.5, se eu optar por essa escolha, terei que atualizar todas, ai vou tem um grande problema, tem filiais no brasil todo, macapa, nordeste, sul. E minha idéia era apenas atualizar o JAR da minha aplicação, com os metódos p/ a integração com o WS. Pois mudanças simples, mesmo orientando por telefone, da muito problema.


I have added FLAG_ACTIVITY_NEW_TASK flag, but I still get "outside of an Activity context requires" error

Question: I still get the error "Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag" when I invoke PublicParFun.ShareAPP(getApplicationContext()); I have added FLAG_ACTIVITY_NEW_TASK flag.
BTW, PublicParFun.ShowMainUI(getApplicationContext()) can work well, why?
CallerMin.java
package ui;

import info.dodata.callernametalker.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import bll.PublicParFun;

public class CallerMain extends Activity {

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

    private void SetButtons() {
        findViewById(R.id.btnSettings).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PublicParFun.ShowMainUI(getApplicationContext());
            }
        });

        findViewById(R.id.btnShare).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PublicParFun.ShareAPP(getApplicationContext());
            }
        });

        findViewById(R.id.btnClose).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

}

PublicParFun.java
package bll;

public class PublicParFun {

    public static void ShowMainUI(Context myContext){
        Intent intent = new Intent().setClass(myContext,ui.CallerMain.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        myContext.startActivity(intent);
    }

    public static void ShareAPP(Context myContext){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

        intent.putExtra(Intent.EXTRA_TITLE, myContext.getString(R.string.ShareTitle));
        intent.putExtra(Intent.EXTRA_SUBJECT, myContext.getString(R.string.ShareTitle));
        intent.putExtra(Intent.EXTRA_TEXT, myContext.getString(R.string.ShareContent));

        try {
            myContext.startActivity(Intent.createChooser(intent,
                    myContext.getString(R.string.defautlClient)));

        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(myContext,
                    myContext.getString(R.string.defautlNoClient), Toast.LENGTH_SHORT)
                    .show();
        }
    }

}

Answer: In CallerMain activity class
instead of getApplicationContext() inside
PublicParFun.ShowMainUI(getApplicationContext());

do CallerMain.this as
PublicParFun.ShowMainUI(CallerMain.this);

Comment: To Rajen Raiyarela: Thanks! Your code works, could you tell me why?
Comment: Frankly speaking i do not have any technical explanation for this. I too faced this issue in one of my application and doing this solved it. At that time i almost spent a week searching for this after i solved to understand why activityname.this worked and getApplicationContext() did not, but did not find any explanation for this.
Answer: try add the FLAG on Manisfest.
Comment: This does not solve the problem.  This rather nonsense actually.


Adicionar linha em branco Excel usando VBA

Question: Tenho uma planilha com 10k linhas, nesse formato (exemplo):
3004977 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  2   \%D \^ S

3004972 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  3   \%D
3004972 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  2   \%D
3004972 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  2   \%D
3004972 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  2   \%D
3004972 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  1   \%D \^ S

3004967 \{DOWN} \{TAB 9}    REMESSAS    \%S 18082017    \{TAB}  110 \%D \^ S

A cada mudança na coluna A existe uma linha em branco. Mas preciso inserir mais 3, em todas. Com o código abaixo, que achei no SOen, ele só adiciona na primeira:
Sub AddBlankRows()
'
Dim iRow As Integer, iCol As Integer
Dim oRng As Range

Set oRng = Range("a1")

iRow = oRng.Row
iCol = oRng.Column

Do
'
If Cells(iRow + 1, iCol) <> Cells(iRow, iCol) Then
    Cells(iRow + 1, iCol).EntireRow.Insert shift:=xlDown
    iRow = iRow + 2
Else
    iRow = iRow + 1
End If
'
Loop While Not Cells(iRow, iCol).Text = ""
'
End Sub

Alguma sugestão?
Comment: Pelo que entendi sempre terá uma linha entre os dados e você precisa de três linhas? Se for isso creio que macro abaixo te ajudará!
Answer: Veja se desta forma te atende:
Sub AdicionaLinhaBranco()

Dim COLUNA_VERIFICAR As String
Dim ULTIMA_LINHA As Integer
Dim QTD_LINHAS As Integer
Dim i As Integer

Application.ScreenUpdating = False

COLUNA_VERIFICAR = "A"
QTD_LINHAS = 2
ULTIMA_LINHA =     ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

Range(COLUNA_VERIFICAR & "1").Select

Do While ActiveCell.Row < ULTIMA_LINHA

    If ActiveCell.Offset(1).Value <> "" Then
        ActiveCell.Offset(1).Select
    Else
        ActiveCell.Offset(1).Select
        For i = 1 To QTD_LINHAS
            ActiveCell.EntireRow.Insert Shift:=xlDown
        Next i
        ActiveCell.Offset(QTD_LINHAS + 1).Select
        ULTIMA_LINHA = ULTIMA_LINHA + QTD_LINHAS
    End If
Loop

End Sub

Boa sorte e sucesso!
Answer: Com algumas pequenas alterações consegui...
Sub AddBlankRows()
'
Dim iRow As Integer, iCol As Integer
Dim oRng As Range

Set oRng = Range("a1")

iRow = oRng.Row
iCol = oRng.Column

Do
'
If Cells(iRow + 1, iCol) <> Cells(iRow, iCol) Then

    Cells(iRow + 1, iCol).EntireRow.Insert shift:=xlDown

    Cells(iRow + 1, iCol).EntireRow.Insert shift:=xlDown

    Cells(iRow + 1, iCol).EntireRow.Insert shift:=xlDown

    iRow = iRow + 4

Else
    iRow = iRow + 1

End If

'
Loop While Not Cells(iRow, iCol).Text = ""

'
End Sub


What can you say about this set operation using principle of inclusion/exclusion

Question: Given:
A = [ Aaron features ],
B = [Bob features],
X = [all countries in Europe ]
What must be true if:
|A ∩ B ∩ X| = 1
Even though I don't see the relation between cardinality of sets, I kind of understand this set operation by doing a Venn diagram.
In the end what must be true for that operation logically speaking?
Answer: If $|A\cap B\cap X|=1$, then there is exactly one element that is in all three sets.  That is, there is exactly one country in Europe that is among Aaron's features and also among Bob's features.
This seems absurd, since countries are not "features" of a person, so it would seem that $|A\cap X|=|B\cap X|=0$ (and hence $|A\cap B\cap X|=0$).  I would consider "features" to be things like eye color, name, email address.  But perhaps "features" can include countries somehow, by redefining that word from its usual meaning.
Comment: Thanks for your answer. How this operation would change if Aaron is from Germany and Bob is from France, but both hometown's is Italy. Can you make an assumption based on that? I assume those to be features right?
Comment: I have no idea what features are, this needs to be part of the problem description somehow for this problem to be well-defined.


Bluemix > IBM API Connect > IBM Developer Toolkit: ECONNREFUSED Errors

Question: Learning how to deploy the demo project to IBM API Connect on Bluemix (get-started) and get the following errors after run apic edit to start IBM Developer Toolkit local site:
Screenshot of the error
Any suggestions will be appreciated.
Comment: The ECONNREFUSED error means that your app is unable to connect to the mentioned port. It may happen because of you didn't configure your the port or another app on that port is not running.
Comment: I have the same issue on Linux Mint 17.3 with port 33780...I have checked but nothing on it so I have tried reinstalling...anyway no success..
Answer: Just tried the same and I am not able to reproduce the issue, since the "apic edit" step works fine for me. I guess this is an issue related to your machine. The error is quite clear and it means that Express.js is not able to connect to that port. The first step is to check that port to see if it's blocked by the host system. However I see different ports in the error message, so the problem could be different (check your firewall settings). Moreover, I would try to install apic again running sudo npm install -g apiconnect and double check that the prerequisites are already installed. It could be throwing an error that you didn't notice.
Comment: Thanks for the suggestion, and will let you know what happens.  I was able to reproduce this issue on my home computer over the week.
Answer: Try publish in the interface 0.0.0.0:
export HOST=0.0.0.0
apic edit


How to perform Time Series Analysis on daily data?

Question: Sorry if my question is silly but I am extremely new to Data Science and Time series analysis.
So I have Tv program viewerships for the last 1 year and want to predict for the next 2 weeks. The data is of the form:
Year, Date, Week_day, Channel, Program, start_time, end_time, length, avg_impressions

avg_impressions is the average of all impressions of the program excluding the breaks. For example, if there were 10 impressions until first break, 20 impressions after first break until second and 30 impressions after the third break to the end, avg_impressions will be 20.
I want to do a time series analysis for the prediction. The data has 211,720 entries for 14 different channels. The data is from 10/10/2015 to 9/9/2016.
I am not very sure on how to convert the ``Impressions` into a time series object. I tried:
pts <- ts(train_agg$Impressions, start=c(2015, 10, 10), end=c(2016, 9, 9), frequency=357)

Is this format correct? I want to check for seasonality in the data. (I read I could tbats on the ts object for that).
Can someone please explain how to specify start dates and end dates for the vector? I read the answers from here, here and here but I am still not sure if I am doing it right.
My R code for what all i did till now:
train_data <- head(prog, 207595)
test_data <- tail(prog, 4126)
colnames(train_data)[12] <- "Impressions"
colnames(test_data)[12] <- "Impressions"
train_agg <- aggregate(Impressions~date_in_days, data=subset(train_data, Channel=="NBC" & Hour==19), mean)
test_agg <- aggregate(Impressions~date_in_days, data=subset(test_data,    Channel=="NBC" & Hour==19), mean)

pts <- ts(train_agg$Impressions, start=c(2015,10,10), end=c(2016,9,9), frequency=357)
plot.ts(pts)

pts.msts <- msts(pts,seasonal.periods=c(7,357))
model <- tbats(pts.msts)
plot(forecast(model, h=7))
forecast(model, h=7)
accuracy(model)

Is this the right way? I am totally lost. Can someone please give me pointers as to what I should do?
Answer: For starters, your data is too short.  When measuring seasonality(ie monthly) you need 3 iterations.  Can you get more data?  If not, then you are left to make a lot of assumptions which can be dangerous. Post your data and what country it is from and the beginning date.
By using regression, you can solve this problem. You can consider using 11 monthly dummies, 6 day of the week dummies and holiday dummies.  Not all may be significant.  Not all may be constant(ie june is high and then becomes low).  You need to look for outliers and build a dummy for them.  You need to look for lead and lag effects around holidays.  You need to consider day of the month impacts, week of the month impacts, long weekend, friday before a monday holiday, monday after a friday holiday.  You might have a trend or multiple trends.  You might have a change in the general volume called a level shift.
Comment: Thanks @Tom. Unfortunately, I can not post the data. I will still take your pointers and update soon.


Treatment effect in a balanced randomized experiment

Question: In an ideal balanced randomized experiment where every profile's propensity score is 0.5 (under binary treatment), regardless of the value of the profile, the best we can know of the treatment effect(AKA uplift) of the given subject is ATE (Average Treatment Effect) of the entire group: This is my understanding.
If this reasoning is correct, what is the point of using decision tree to estimate treatment effect of the subject with profile X because the ATE at the leaf node will be (statistically) same as that of the entire group.
The following is the relevant survey paper, where I could not find answer to my above doubt:
http://proceedings.mlr.press/v67/gutierrez17a/gutierrez17a.pdf
Answer: It's not generally the case that the conditional average treatment effect (CATE) for a given profile is equal to the average treatment effect in the sample (ATE). In fact, the average of the CATEs in the sample will equal the ATE, but if the CATEs differ from each other across profiles, then the CATE for a given profile won't necessarily be equal to the average of the CATEs. This situation is called "treatment effect heterogeneity" because the treatment effects (CATEs) are heterogeneous.
This has nothing to do with whether a randomized experiment was performed or not. In a randomized experiment, the ATE is given for free by computing the difference in observed outcome means, and in an observational study with confounding, we have to do analytic work to get the ATE (which is what the article describes). To get the CATE for a given profile, however, we have to do analytic work regardless of whether we have a randomized experiment or an observational study. In fact, this analytic work is almost the same in both cases, except for the situation mentioned in the paper you linked, in which an alternative and simpler method arise for estimating CATEs in a randomized experiment that would not be available in an observational study. But all methods for estimating CATEs in observational studies apply to randomized experiments as well.
So, to answer your specific question, it's not the case that CATEs in leaf nodes will equal the ATE in the sample. On average they will, but only because by definition the ATE is the average of the CATEs. For a given profile, you wouldn't expect the CATE to be equal to the ATE unless the treatment effect is exactly equal for all profiles.
For example, let's say an intervention performed better for younger than older customers (e.g., because it relies on social media). In a randomized experiment, there would be the same number of older and younger customers in each condition of the intervention (i.e., with the intervention present vs. absent). You could compute the ATE by taking the difference in sample means for the two conditions, but to estimate the CATEs for young and old customers, additional modeling would have to take place (which could be as simple as stratifying by age). You wouldn't expect the CATEs for these age profiles to be equal to the overall ATE based on the first premise of this example. The techniques for estimating CATEs in the article rely on the same reasoning except that the groups are more granular and harder to observe directly, so modeling (including machine learning) has to be done to get good CATE estimates.


Understanding Expected Value of observed responses in Regression

Question: I have a quick question about
the following is a discussion on the online Penn State Regression methods course:

Recall that, in fitting a regression model to data, we attempt to
  estimate the average—or expected value—of the observed responses
  $E(y_i)$ at any given predictor value x. That is, $E(y_i)$ is the
  population regression function. Because the average of the observed
  responses depends on the value of x, we might also denote this
  population average or population regression function as $\mu_{Y|x}$
Now, if there is no bias in the predicted responses, then the average
  of the observed responses $E(y_i)$ and the average of the predicted
  responses $E(\hat y_i)$ both equal the thing we are trying to
  estimate, namely the average of the responses in the population
  $μ_{Y|x}$. On the other hand, if there is bias in the predicted
  responses, then $E(y_i)$ = $μ_{Y|x}$ and $E(\hat y_i)$ do not equal
  each other. The difference between $E(y_i)$ and $E(\hat y_i)$ is the
  bias $B_i$ in the predicted response, i.e
$B_i$=$E(y_i)−E(\hat y_i)$

(See "Bias in predicted responses" section here for context).
My question here is about the average/expected value of observed responses, $E(y_i)$ that we're talking about. Could someone intuitively explain to me what this means? How can observed y-values in a sample have a "true" population value, or am I looking at it the wrong way?
Comment: What part of the question did you write, and what part of the question was copied from the course?
Comment: Do you mean *residual* instead of *bias*? Bias generally refers to a parameter being different from its true value; residuals refer to predicted values being different from their observed values.
Comment: Not bias. Sorry, I think I wrote the question a bit unclear.
In the first line, it says "We attempt to estimate the average/expected value of observed responses".
What do they mean by this? As in, I'm trying to intuitively understand what the "Average" of observed responses would be?
Comment: No apologies necessary! I was just clarifying to make sure that *I* understood the question correctly.
Answer: In the comment below, you write:

"We attempt to estimate the average/expected value of observed
  responses". What do they mean by this? As in, I'm trying to
  intuitively understand what the "Average" of observed responses would
  be?

This concept of "average" really clicked with me when I started modeling things explicitly in the Stan language (a statistical language for Bayesian inference). I'm going to be stealing some of my notation from their manual.
So, we can usually write a linear regression like this:
$y_i = \beta_0 + \beta_1x_i + \epsilon_i$ where $\epsilon_i \sim N(0, \sigma^2)$
A few things to note: $y$ is the observed dependent variable, $x$ is the observed independent variable, and $i$ represents that each individual has their own value for it. $\beta_0$ is the intercept and $\beta_1$ is the slope for $x$. $\epsilon$ is the residual term. We can see that we assume that the residuals are normally distributed with a mean of zero and some variance.
Now, this can be rewritten as:
$y_i - (\beta_0 + \beta_1x_i) \sim N(0, \sigma^2)$
Which we can further simplify to:
$y_i \sim N(\beta_0 + \beta_1x_i, \sigma^2)$
And lastly, since $\hat{y} = \beta_0 + \beta_1x_i$, we can simplify again:
$y_i \sim N(\hat{y_i}, \sigma^2)$
Notice the subscript $i$. This means that, for every individual, we say their observed score comes from a normal distribution with a mean of the predicted value and a given residual variance. Notice that, for every person, this predicted value is different, but the variance is the same. The variance being the same is where we get the assumption of homogeneity of variance.
Now, I don't really like using "average value" and "expected value" interchangeably, because for some distributions, they are not the same thing. But for the normal distribution, the average and expected values are the same (because the mean is equal to the mode of a normal distribution). But that is what they mean by average. You are basically saying:
"Every observation of y is distributed with a mean of y-hat and a variance of sigma squared." This only clicked for me when I started using Stan, because in that language, you can literally code it as:
<code>y ~ normal(beta[0] + beta[1] * x, sigma)
</code>
Comment: Well, I'm under the impression that: $E(y_i | x_i) = \hat{y}$. I don't know much about Mallow's Cp—besides what it is meant to do—and the Wikipedia page for it *does* act like the predicted value of $y$ and the value of $y$, given $x$, are different things. So I'm afraid I'm not much help at this point.
Comment: Thanks, that definitely did make sense! So then it would mean that the $E(y_i)$ = $\hat y_i$. Then what does the author mean when they write $E(\hat y_i)$ ? (Added bit of info, this explanation comes up when they're trying to explain the concept of mallow's cp.)
Comment: @ricksanchez Ah. I read through part of that chapter. $E(y)$ refers to what the *actual, population* regression line would predict. $E(\hat{y})$ refers to what our *fitted, sample* regression line predicts. As the author of that course notes, we don't know $E(y)$: "Did you notice all of those Greek parameters... [those] are generally used to denote unknown population quantities. That is, we don't or can't know about the value of $\Gamma_p$—we must estimate it." Since you don't know $E(y)$ (which is a part of $\Gamma_p$), Mallow's $C_p$ estimates it.
Comment: @ricksanchez So, in the words of that course: The residual value is how far our *predicted* value is from our *observed* value. And bias is how far our predicted value from the *sample* regression line is from the predicted value from the *true, population* regression line. We obviously do not know the true population regression line, so it is estimated by Mallow's $C_p$. I apologize—I got hung-up on terminology I wasn't familiar with; my original comment trying to clarify if you meant "residual" was incorrect—bias was the correct word. I just needed some context to figure it out.


Arrival times of taxis is poisson process

Question: You are waiting in line for a taxi. There are two people ahead of you. Taxis arrive in a
Poisson process, at average rate of one every two minutes
Let T$_2$=time until 2nd taxi arrives
I'm trying to find the CDF for T$_2$, The answer I'm given is F$_T$$_2$(t)=1-(1+λt)e$^($$^-$$^λ$$^t$$^)$
Can anyone explain or give me a hint on how to do this?
Comment: Sum of two i.i.d. exponential random variables has a Gamma or Erlang distribution.  Try a Poisson distribution with parameter $\lambda t$ and the probability that at least two events occur, i.e. $1 - $ the probability zero or one occur
Answer: Let $\tau_n$ be the interarrival times of the taxis, i.e. $\tau_n\stackrel{i.i.d.}\sim\mathsf{Exp}(\lambda)$, where we may interpret $\lambda$ as $\frac12\mathrm{min}^{-1}$ or $30\mathrm{h}^{-1}$. Then $T_2=\tau_1+\tau_2$, so the density of $T_2$ is (for $t>0$)
\begin{align}
f_{T_2}(t) &=f_{\tau_1}\star f_{\tau_2}(t)\\ &= \int_0^t f_{\tau_1}(s)f_{\tau_2}(t-s)\ \mathsf ds\\
&= \int_0^t \lambda e^{-\lambda s}\lambda e^{-\lambda(t-s)}\ \mathsf ds\\
&= \lambda e^{-\lambda t} \int_0^t \lambda\ \mathsf ds\\
&= (\lambda t)\lambda e^{-\lambda t}.
\end{align}
Integrating yields
\begin{align}
F_{T_2}(t) &= \int_0^t f_{T_2}(s)\ \mathsf ds\\
&= \int_0^t(\lambda s)\lambda e^{-\lambda s}\ \mathsf ds\\
&=\lambda s e^{-\lambda s}|_t^0 + \int_0^t \lambda e^{-\lambda s}\ \mathsf ds\\
&= -\lambda te^{-\lambda t} + 1 -e^{-\lambda t}\\
&= 1 - (1+\lambda t)e^{-\lambda t},\ t>0.
\end{align}


unoconv fails to save in my specified directory

Question: I am using unoconv to convert an ods spreadsheet to a csv file.
Here is the command:
unoconv -vvv --doctype=spreadsheet --format=csv --output= ~/Dropbox
/mariners_site/textFiles/expenses.csv ~/Dropbox/Aldeburgh/expenses
/expenses.ods

It saves the output file in the same directory as the source file, not in the specified directory.  The error message is:
Output file: /home/richard/Dropbox/mariners_site/textFiles/expenses.csv
unoconv: UnoException during export phase:
Unable to store document to file:///home/richard/Dropbox/mariners_site
/textFiles/expenses.csv (ErrCode 19468)

I'm sure that this worked initially, but it has since stopped.
I have checked for permissions and they are identical for both directories.
Answer: I translated ErrCode 19468 for you and it boils down to meaning ERRCODE_SFX_DOCUMENTREADONLY.
You can find more information about the specific meaning of LibreOffice ErrCode numbers from the unoconv documentation at: https://github.com/dagwieers/unoconv/blob/master/doc/errcode.adoc
The clue here is that you have a whitespace-character between --output= and the filename (--output= ~/Dropbox
/mariners_site/textFiles/expenses.csv) and because of that unoconv gets an empty output value (which means the current directory) and is given 2 files. And that explains why you get this specific error IMO


Mysql replication from two masters

Question: Here's my mysql cluster setup
All nodes have a database db with following tables
table1
table2
table3
NODE1 gets table2 from NODE2, table3 FROM NODE3
NODE2 gets table1 from NODE1
NODE3 gets table1 from NODE1
Is this possible with mysql replication?
Comment: I know that we can exclude or include some tables/databases in mysql replication and also that a master can also be a slave. The only problem is `Can a slave have multiple masters?`
Answer: I think its not possible with a normal master/slave replication. For this you need something like the mysql cluster version.
The main problem is the master / master replication without the cluster. Then you get some trouble with IDs and something else. I have tried this before a lot of time. And when you write on both master and one master is before the other and will write to the other and the primary key exists and you cannot write its very strange.
I have put a link to HowToForge there is an article to set up a master / master replication you can try it.
Perhaps you can look for alternatives like couchedb or mongodb its no mysql but with the nosql databases you can better replicate and scale.

Mysql replication from two masters


How we can compute this integral $\int \frac{1}{(1+\arccos(x))(1-x^2)} dx$?

Question: $$\int \frac{1}{(1+\arccos(x))(1-x^2)} dx$$
i tired first to use substitution $u=\arccos(x)$ then $du=-\frac{1}{\sqrt{1-x^2}}$
but this may not give me what im looking for
as result is there any shortcut to attack this problem >?
Comment: Seems [wolframalpha](https://www.wolframalpha.com/input/?i=%5Cint+dx%2F%28%281%2Bacos%28x%29%29%281-x%5E2%29%29) can't give a closed form
Answer: I think that only a series solution could work. Use for example
$$\frac{1}{1+\cos ^{-1}(x)}=$$ $$\frac{2}{2+\pi }\left(1+\frac{2 x}{2+\pi }+\frac{4 x^2}{(2+\pi )^2}+\frac{(28+4\pi  +\pi^2 ) x^3}{3
   (2+\pi )^3}+\frac{4 \left(16+4 \pi +\pi ^2\right) x^4}{3 (2+\pi)^4}+O\left(x^5\right) \right)$$ to face integrals looking like
$$I_n=\int \frac {x^n}{1-x^2}\,dx$$ which are quite simple after partial fraction decomposition.
Edit
ANothe solution could be to let $x=\cos(u)$
$$\int \frac{dx}{(1+\arccos(x))(1-x^2)} dx=\int \frac{\csc (u)}{u+1} \,du$$
$$\frac{\csc (u)}{u+1}=\sum_{n=0}^\infty (-1)^{n+1}\frac{\left(4^n-2\right) B_{2 n}}{(2 n)!}\frac {u^{2n-1}}{1+u}$$
$$\int \frac {u^{2n-1}}{1+u}=\frac{u^{2n}}{2n}\, _2F_1(1,2 n;2 n+1;-u)$$


Are there any infinite (virtually) polycyclic groups with lattice orders that are not linear orders?

Question: I am interested in noetherian group algebras, so I am learning about polycyclic groups. Specifically, I want to generalize some ideas that work well with $k[\mathbb{Z}^n]$ utilizing the lattice structure of $\mathbb{Z}^n$.  So if I want noetherianness AND the lattice structure, a natural place to look is polycyclic $\ell$-groups. My issue is that I can't find any (other than $\mathbb{Z}^n$) that have nonlinear orders.
I am far from an expert in this area, but I have just spent a fair bit of time working with groups of the form $\mathbb{Z}\ltimes\mathbb{Z}^n$ using the map $z\mapsto A$ where $A\in SL(n,\mathbb{Z})$ with all positive eigenvalues.  This group was suggested by a colleague as it is known to be linearly ordered in a natural way, but that natural way breaks down for any nonlinear ordering I have tried.
I have also looked into the possibility of finitely generated abelian groups, as they are polycyclic.  This breaks down almost immediately, though, as $\ell$-groups that are finitely generated AS $\ell$-groups are rarely finitely generated as abelian groups, too.
Answer: Chapter 2, exercise 11 of Steinberg's book Lattice-Ordered Rings and Modules gives $G=(\mathbb{Z}\oplus\mathbb{Z})\ltimes_{\phi} \mathbb{Z}$ with $\phi(1)$ being the automorphism $\tau(x,y)=(y,x)$ as an example of an $\ell$-group.  Since $G$ is the semidirect product of polycyclic groups, it is polycyclic itself. Thus, $G$ is an example of a polycyclic $\ell$-group that is not a linear order.


What is the range of $y$ if $x+y+z=4$ and $xy+yz+xz=5$ for $x, y, z \in\mathbb{R}_+$

Question:
What is the range of $y$ if $x+y+z=4$ and $xy+yz+xz=5$ for $x, y, z \in\mathbb{R}_+$

How to explain the following method?
Let $x=z$ then:
$$2x+y=4\quad;\quad 2xy+x^{2}=5$$
$$\implies \left( 4-y\right) y+\left( \dfrac {4-y} {2}\right) ^{2}=5 $$
Simplify: $(3y-2)(y-2)=0$. Then I get $\dfrac {2} {3}\leq y\leq 2$.
But why?
Thanks and sorry for my poor English
Comment: Replacing the values of $z$  with $4-(x+y)$  we get $$x^2+x(y-4)+(y^2-4y+5)=0$$  whose discriminant is $$-(3y-2)(y-2)$$ which needs to be $\ge0$
Comment: It is not obvious that the extremal possible values of $y$ take place when $x=z$. This should be a result of the argument.
Answer: $\bf{Another \; Way::}$
Given $x+y+z = 4\Rightarrow x+z=4-y$ and $xy+yz+zx = 5$
Using $$(x+y+z)^2 = x^2+y^2+z^2+2(xy+yz+zx)\Rightarrow x^2+y^2+z^2 = 6$$
So we get $x^2+z^2 = 6-y^2$
Now Using $\bf{Weighted\; A.M\geq G.M\;,}$ We get
$$\frac{x^2+z^2}{2}\geq \left(\frac{x+z}{2}\right)^2$$
So $$\frac{6-y^2}{2}\geq \left(\frac{4-y}{2}\right)^2\Rightarrow (4-y)^2\leq 12-2y^2$$
So $$16+y^2-8y\leq 12-2y^2\Rightarrow 3y^2-8y+4\leq 0$$
So $$3y^2-6y-2y+4\leq 0\Rightarrow \frac{2}{3}\leq y\leq 2$$