Maximum likelihood estimate of $\theta$ with $f(x|\theta) = -(\theta+\theta^2)(1+x)^{\theta-1}x, -10 $

Question: Let $X_1, X_2, ..., X_n$ be a random sample from the pdf $f(x|\theta) =  -(\theta+\theta^2)(1+x)^{\theta-1}x, -1<x<0, \theta>0,$ zero elsewhere.
How could I deal with the negative sign when I take partial derivative w.r.t $\theta$ ?
Comment: Just treat it as a constant.
Comment: Your title is too long and does not agree with the body of the post. The hint below assumes you're looking for the MLE of $\theta$ not of $f(x|\theta)$.
Comment: Just compute $\Pi f$ and take logs $\sum log(f)$. Do your straighforward computations and pose derivate $=0$. You get $\sum g(\theta) = \sum log(1+x_1)$ RHS is a constant. LHS are $N$ summands all equal to each other, where $g(\theta)$ is a ratio of two polynomials in $\theta$ of degree 1 and 2. Solve this equation of order 2 and pick the $\theta$ which is $>0$.
Answer: Hint: let $A=\prod_{i=1}^n(1+x_i)$ and $B=\prod_{i=1}^n(-x_i)$. You're to find $\theta$ that maximizes
$$
(\theta+\theta^2)A^{\theta-1}B.
$$
Since $\theta$ cannot affect $B>0$, you can just maximize $(\theta+\theta^2)A^{\theta-1}$. Taking derivative:
$$
\partial_\theta((\theta+\theta^2)A^{\theta-1})=A^{\theta-1}[1+\theta(2+\log A)+\theta^2\log A].
$$
When setting the RHS above to $0$, you don't need to worry about $A^{\theta-1}$ so what remains to select the positive root of the quadratic in square brackets above.
Answer:
How could I deal with the negative sign...

If you mean the restricion $\theta >0$ : that only gives you the domain of your variable: $\theta$ is restricted to $(0,+\infty)$. To find the (global) maximum of a real function you do as usual: if the function is derivable in all its domain, you find the critical points and check if they are indeed local extremes. Of course, you must only consider the critical points (zeroes of the derivative) that lie inside your domain. That's where the restriction  $\theta >0$ comes into play.
Also (this is important) you must check if your local maxima is really a global maximum (in particular, look at your domain boundary).


Every matrix is a limit of a sequence of invertible matrices.

Question: I'm trying to prove that every matrix $n\times n$ is a limit of a sequence of invertible matrices $n\times n$.
I know this intuitively, but I couldn't prove formally. I'm trying to prove this using the fact the set of the non-invertible matrices is closed. Am I on the right way?
Thanks in advance
Comment: If the matrix is invertible, you are done (use the constant sequence).  If the matrix is non-invertible, think about an open neighborhood of the matrix.  What happens if we add a slight "random" perturbation to the matrix?
Answer: Let $A$ be your matrix, then $A-tI$ is invertible for all sufficiently small non-zero values of $t$, so just let $t$ run through any sequence of sufficiently small values approaching zero.
Comment: Why $A-tI$ is invertible for all sufficiently small non-zero values of $t$? I mean how to prove it formally?
Comment: $A-tI$ is invertible unless its determinant is zero. $\det(A-tI)=0$ is a polynomial equation of degree $n$ in $t$, so it has at most $n$ real roots, so its nonzero roots are bounded away from zero.
Comment: Yes, thank you. It's my fault. I didn't understand "bounded away from zero", I'm sorry my bad English.
Comment: I'm sorry, but why the nonzero roots are positive?
Comment: Who said they were positive? I wrote that they are bounded away from zero, that's all. In any event, there is an open interval $(0,a)$ that doesn't contain any of them, and that's all you need, right?


Units in definite integral

Question: I've been given a problem in my electrical engineering class which is confusing me.
I'm given $i(t) = 5\sin(6 \pi t/\mathrm s)\, \mathrm{mA}$ (mA is mC/s) and I need to find the total charge transferred from $0$ to $1\,\mathrm s$.
$i = \frac{\mathrm dq}{\mathrm dt}$, so I take the definite integral of $i$ over $0\,\mathrm s\le t \le 1\,\mathrm s$.
Unfortunately, while I know how to do this without units, with units is confusing me, especially the way it's written since $t/\mathrm s$ would look like 1/second when $t$ is 1...
The result should be in mC (or possibly some other magnitude of C).
Comment: $t$ is not 1. $t$ is one second.
Comment: The *dt* in the integral expression has units of seconds, so after multiplying mA/s yields mC as the units of the integral result.
Comment: If t is one second then t/s would be 1 s/s which would be 1 and make even less sense.
Answer: Since $t$ is a time, it is measured in a time unit, for example seconds. Thus after dividing by the time unit $t$, we obtain a dimensionless number, which is just the right thing to feed into the sine function. After multiplication with the current unit mA, we do indeed have a current. Then integrating over time give us a charge. That should be fine.
$$ \int_{0\,\mathrm s}^{1\,\mathrm s} 5 \sin\frac{2\pi t}{\mathrm s}\,\mathrm{mA}\,\mathrm dt=5\,\mathrm{mC}\cdot \int_{0\,\mathrm s}^{1\,\mathrm s} \sin\frac{2\pi t}{\mathrm s}\,\frac{\mathrm dt}{\mathrm s}=5\,\mathrm{mC}\cdot \int_{0}^{1} \sin{2\pi \tau}\,\mathrm d\tau$$
if you prefer.
Comment: So I just treat units as constants?

Units in definite integral


Choose image based on switch and case for notifcation

Question: At the moment when I press a button the image is always the phone but what I want is to be able to change this picture depending on what button is pressed.
eg. button imageButton1 is pressed set the notification image to the car
NotificationManager nm;
static final int uniqueID = 101;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button stat = (Button) findViewById(R.id.btnSet);
    stat.setOnClickListener(this);
    ImageButton img1 = (ImageButton) findViewById(R.id.imageButton1);
    img1.setOnClickListener(this);
    ImageButton img2 = (ImageButton) findViewById(R.id.imageButton2);
    img2.setOnClickListener(this);
    ImageButton img3 = (ImageButton) findViewById(R.id.imageButton3);
    img3.setOnClickListener(this);
    ImageButton img4 = (ImageButton) findViewById(R.id.imageButton4);
    img4.setOnClickListener(this);
    ImageButton img5 = (ImageButton) findViewById(R.id.imageButton5);
    img5.setOnClickListener(this);
    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(uniqueID);
}

@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
    int picture = R.drawable.phone;
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.imageButton1:
        // do something
        picture = (R.drawable.car);
        break;
    case R.id.imageButton2:
        // do something else
        picture = (R.drawable.clock);
        break;
    case R.id.imageButton3:
        // do something else
        picture = (R.drawable.globe);
        break;
    case R.id.imageButton4:
        // do something else
        picture = (R.drawable.little_tv);
        break;
    case R.id.imageButton5:
        // do something else
        //setImageResource(R.drawable.phone);
        break;
    case R.id.btnSet:
     // do something else
        EditText etT = (EditText) findViewById(R.id.etTitle);
        EditText etB = (EditText) findViewById(R.id.etBody);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        String setTitle = etT.getText().toString();
        String setBody = etB.getText().toString();
        String body = setBody;
        String title = setTitle;
        Notification n = new Notification(picture, body, System.currentTimeMillis());
        n.setLatestEventInfo(this, title, body, pi);
        n.defaults = Notification.DEFAULT_VIBRATE;
        nm.notify(uniqueID, n);
        finish();
     break;
    }
}

}
Comment: I'm sorry, but I can't see your question / problem? Can you add further information?
Comment: through your code you will see only phone image in notification every time
Comment: Everything is fine, but what is your question ? I don't seems any question ?
Answer: remove declaration & initialization of 'picture' from onClick function and set it as class variable.
For better understanding refer below
NotificationManager nm;
static final int uniqueID = 101;
int picture;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Add below line here
    picture = R.drawable.phone;

    ...... All your code

}

@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
    // Remove below line
    // int picture = R.drawable.phone;

    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.imageButton1:
        // do something
        picture = (R.drawable.car);
        break;
    case R.id.imageButton2:
        // do something else
        picture = (R.drawable.clock);
        break;
    case R.id.imageButton3:
        // do something else
        picture = (R.drawable.globe);
        break;
    case R.id.imageButton4:
        // do something else
        picture = (R.drawable.little_tv);
        break;
    case R.id.imageButton5:
        // do something else
        //setImageResource(R.drawable.phone);
        break;
    case R.id.btnSet:
     // do something else
        EditText etT = (EditText) findViewById(R.id.etTitle);
        EditText etB = (EditText) findViewById(R.id.etBody);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        String setTitle = etT.getText().toString();
        String setBody = etB.getText().toString();
        String body = setBody;
        String title = setTitle;
        Notification n = new Notification(picture, body, System.currentTimeMillis());
        n.setLatestEventInfo(this, title, body, pi);
        n.defaults = Notification.DEFAULT_VIBRATE;
        nm.notify(uniqueID, n);
        finish();
     break;
    }
}

In your code whenever btnSet get click the "picture" variable get initialize with R.drawable.phone and then according to switch case it directly execute "case R.id.btnset"
I think you got my point
Comment: Thank you this fixed everything all it needed was a global variable and move what it was set as


Understanding the Rejection Sampling for a vector

Question: I am thinking about this classical problem in statistical simulations. We want to apply the Rejection sampling to simulate a random vector $Y=(Y_1, Y_2)$ of a uniform distribution from a unit disc $D = \left\{ (X_1 , X_2) \in R^2: \sqrt{x^2_1 + x^2_2} ≤ 1\right\}$ such that $X = (X_1 , X_ 2)$ is random vector of a uniform distribution in the square $S = [−1, 1]^2$ and the joint density
$$ f(y_1,y_2) = \frac{1}{\pi} \mathbb{1}_{D(y_1,y_2)}.$$
Many answers presented a very simple solution like the answer of Haitao Du and page 26 but I can't understand how did they applied the rejection sampling method.
In the rejection method, we accept a sample generally if $f(x) \leq C \times g(x)$. In the linked answers they simply do
Repeat generate independent V1, V2  which distribute U(−1,1)
Until (V1)^2 + (V2)^2 <= 1
Return (V1,V2).

So the code
x=runif(1e4,-1,1)
y=runif(1e4,-1,1)

d=data.frame(x=x,y=y)
disc_sample=d[d$x^2+d$y^2<1,]
plot(disc_sample)

What I am can't understand how did they use the definition of Rejection sampling. Where did the define the constant $C$, the function $g(x)$ or even found the maximum of $f(x)$. I understand what did they do but I don't see how it is applying the definition of the Rejection sampling. Thanks for help
Answer: The constant is irrelevant because all distributions are uniform. If you take the formal set-up, you can quickly see that you can simplify it to the procedure you describe.
The maximum of $f(x)$ is the same as the value throughout, because of the uniformity. Therefore, we don't need to do the comparison.
By the way, there is a mistake in the code. d$x^2+d$y^2<1should be (d$x^2+d$y^2)<1.


Eigen named access to vector segment

Question: I would like to create a custom Eigen vector class which has named references to specific segments (or blocks for matrices). This should allow me to alter specific parts of the vector at once without having to remember the specific indices, which in my opinion leads to more readable code when working with large vectors/matrices. After following some advice in the Eigen documentation I came up with the following demo implementation:
#include "Eigen/Core"
#include <iostream>

struct State : public Eigen::Matrix<double,12,1>{
    static constexpr unsigned int SIZE = 12;
    using data_t = Eigen::Matrix<double,SIZE,1>;

    Eigen::Ref<Eigen::Vector3d> pos;// Same problem using Eigen::VectorBlock<data_t,3>
    Eigen::Ref<Eigen::Vector3d> ang;
    Eigen::Ref<Eigen::Vector3d> vel;
    Eigen::Ref<Eigen::Vector3d> ang_vel;

    State(const Eigen::Vector3d& pos, const Eigen::Vector3d& ang, const Eigen::Vector3d& vel, const Eigen::Vector3d& ang_vel)
    : State(){
        this->pos = pos;
        this->ang = ang;
        this->vel = vel;
        this->ang_vel = ang_vel;
    }

    State() : State(data_t::Zero()){}

    // This constructor allows you to construct State from Eigen expressions
    template<typename OtherDerived>
    State(const Eigen::MatrixBase<OtherDerived>& other)
    : data_t(other), pos(this->segment<3>(0)), ang(this->segment<3>(3)), vel(this->segment<3>(6)), ang_vel(this->segment<3>(9)){}

    // This method allows you to assign Eigen expressions to State
    template<typename OtherDerived>
    State& operator=(const Eigen::MatrixBase<OtherDerived>& other)
    {
        this->data_t::operator=(other);
        return *this;
    }
};

State createState(){
    State x;
    x.pos = Eigen::Vector3d(1.0,1.0,1.0);
    return x;
}

int main(){
    State x = createState();
    std::cout << x.pos << std::endl;
    State dx;
    dx.pos = x.pos/2;
    std::cout << dx.pos << std::endl;
    return 0;
}

This code works perfectly fine in Release mode (with optimizations enabled) and prints

1, 1, 1
0.5, 0.5, 0.5

However when I turn on Debug mode (without optimizations and added debug symbols) it prints something like

-9.25596e+61, -9.25596e+61, 0
-4.62798e+61, -4.62798e+61, -4.62798e+61

I am using MSVC Build tools 2019 on a windows 10 laptop to compile and run this example.
When investigating more closely with the debugger it seems the data in the vector itself is still intact, however the named references are now pointing to different memory locations (dangling pointers). It is also important to note that this behaviour only occurs for a State returned by another function. If the State is constructed inside the main function, everything works as expected.
I found a solution to this problem which I will describe in an answer below, but wanted to see if someone more familiar with the Eigen internals can explain this and/or come up with a better solution.
Update:
I just tested the above code on another computer (Linux) using GCC 6.4.0 and there everything works fine. So it might also be compiler related.
Answer: I found out that providing a custom (otherwise default created) copy constructor and move constructor resolves the above issue.
State(const State&)
: data_t(other), pos(this->segment<3>(0)), ang(this->segment<3>(3)), vel(this->segment<3>(6)), ang_vel(this->segment<3>(9)){
    // Default copy constructor causes dangling references in debug mode.
}
State(State&& other)
: data_t(std::move(other)), pos(this->segment<3>(0)), ang(this->segment<3>(3)), vel(this->segment<3>(6)), ang_vel(this->segment<3>(9)){
    // Default move constructor causes dangling references in debug mode.
}

Because of these changes the compiler complained that the copy assignment operator was deleted by default, hence I needed to add an implementation for this operator as well (this was only necessary in a more elaborate scenario than the simple demo above):
State& operator=(const State& other){
    this->data_t::operator=(other);
    return *this;
}

For now this works fine for my approach, the drawback however is that I have to repeat the initialization of the named references in three constructors now.

Eigen named access to vector segment


Trabalhando com resources C#?

Question: Adicionei o resource de dicionários ao meu projeto, agora preciso converter ele em um dicionario via código, mas está trazendo o recurso nulo, alguém consegue me ajudar?
<code>List<string> dic = new List<string>();
List<string> aff = new List<string>();

Assembly _assembly;
StreamReader _textStreamReader;

_assembly = Assembly.GetExecutingAssembly();
string line;

_textStreamReader = new StreamReader(
    _assembly.GetManifestResourceStream("tx_spell_open_dict_resource.pt_BR.dic"));
while ((line = _textStreamReader.ReadLine()) != null)
{
    dic.Add(line);
}

_textStreamReader = new StreamReader(
    _assembly.GetManifestResourceStream("tx_spell_open_dict_resource.pt_BR.aff"));
while ((line = _textStreamReader.ReadLine()) != null)
{
    aff.Add(line);
}

OpenOfficeDictionary dic_ptBR = new OpenOfficeDictionary(
    dic.ToArray(), aff.ToArray(), new CultureInfo("pt_BR"));
txSpellChecker1.Dictionaries.Add(dic_ptBR);
</code>
Talvez a parte errada , esteja na string que tento pegar o resource.
Comment: No momento em que estou dando `GetManifestResouceStream`
Comment: Em qual linha ou linhas está acontecendo isso?
Comment: O nome do `tx_spell_open_dict_resource.pt_BR.dic` seria `tx_spell_open_dict_resource.pt_BR.dic.resx`?
Comment: Da uma olhada ve se ajuda https://stackoverflow.com/questions/10726857/why-does-getmanifestresourcestream-returns-null-while-the-resource-name-exists-w
Comment: Dei uma olhada , mais infelizmente não é isso o problema.  tentei renomear com o namespace, mesmo assim ele retornar nulo.
Answer: Verin,
Utilizo da seguinte forma.
Crio um arquivo de nome Resources.resx em Properties.
Em seguida crio os arquivos com os nomes Resources.pt-BR.resx, Resources.en-US.resx e etc.
Crio a strings iguais nos 3 arquivos (ou nos demais idiomas que preciso).
Para traduzir textos específicos utilizo esta função que montei:
<code>    public static string Tradutor(string pVariavel)
    {
        try
        {
            ResourceManager rm = new ResourceManager(typeof(Resources));
            return rm.GetString(pVariavel);
        }
        catch
        {
            return "Variável não localizada.";
        }
    }
</code>
Na entrada da classe BaseController (aqui utilizo MVC).
<code>/*CULTUREINFO DO USUÁRIO*/
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("pt-BR");
</code>
A chamada do pt-BR é só para exemplo, você inclui de acordo com a forma que armazena esta variável.
Está é a forma simples, fora as outras integrações, como por exemplo utilizar no DataAnnotations dentro de Views e etc.

Trabalhando com resources C#?


Weblogic 10.3 weblogic.jar classpath issues

Question: I am upgrading an old WLS8.1 app to 10.3 (11g)
My ant build includes only the new weblogic.jar in the compile classpath and the build runs with no issues but when I include weblogic.jar as a libeary in the IDE (Intellij) i see many unresolved imports (for example: weblogic.xml.xpath.DOMXPath) when I check the weblogic.jar I see that the classes are indeed missing from it.
compiling with verbose revealed that by including weblogic.jar in the ant classpath, many other jars in the BEA_HOME/modules are loaded to the classpath as well (for example: com.bea.core.xml.weblogic.xpath_18.104.22.168.jar)
Can anyone explain what is going on?
How can I fix my IDE classpath - do I need to import all the module-jars?
Many of the module jars seems like they are there to support old deprecated weblogic 8 APIs (like: weblogic.xml.xpath.DOMXPath) how can I exclude these modules from my ant build? (I want to expose the APIs I need to upgrade)
Thanks,
NY
Answer: The default class loader is replaced by the WebLogic one which adds the WebLogic specific classes and some lib folders to your CLASSPATH. You should have some support for J2EE in your IDE.
Answer: I am not 100% sure but this might be resolved by using wlfullclient.jar instead of weblogic.jar.


Use of the Bonferroni correction

Question: I am conducting an analysis of survey data.
I have carried out sign tests comparing the answers provided by two different groups to each question. There are several questions for which I am making this analysis.
Am I right in thinking that I do not need to use a Bonferroni (or any other type) of correction?
Thanks in advance :)
Comment: @Deepak. A call perhaps 'better' made by someone who has participated actively in the 'statistics' tag.
Comment: Better on https://stats.stackexchange.com/
Comment: @BruceET. Thanks. Does the instance below change anything?  am currently analysing survey data.One of the questions is how two different types of product would impact on a company across multiple parameters (sales, customer relations etc) I have conducted sign tests to compare the two different types of product for each of the parameter (But not across different parameters.
Comment: Should I be correcting for the multiple tests? On one hand, the tests are to be considered individually for each parameter, but on the other hand there is an implicit 'overall hypothesis' that one product type has a more positive impact on all the parameters.
Comment: If you are looking at the tests one at a time, then there is no need for the Bonferroni correction. If you are looking at several significant test results in conjunction to discuss an 'overall picture', then use the correction.
Answer: If you have made $k$ confidence intervals (CIs) at the 95% level and wish to
use them in conjunction in order to get the overall picture of your data,
then the Bonferroni correction would be to make all of these CIs at the
level $100\% - 5\%/k.$ According to Bonferroni's Inequality for probabilities,
the overall 'error rate' of the $k$ CIs cannot exceed 5%. The Bonferroni
procedure for CIs is a little too aggressive (in the sense that it can
'over-correct'), but this effect is usually not important for a small (e.g.
5% overall rate, and a small $k$).
Similar advice holds for testing $k$ related hypotheses. The overall or
'family' significance level for $k$ hypotheses considered together
does not exceed 5% if the individual hypotheses are all significant
at level $5\%/k.$
Perhaps this kind of comparison occurs most often in the context of an
analysis of variance where a factor with $g$ levels is significant at
level $\alpha.$ Then to assess the overall pattern of significant
differences for the $k = {g \choose 2}$ pairwise comparisions, some
sort of 'correction' is needed in order to keep the 'family' type I
error rate under reasonable control.
Particularly when all $g$ levels
have the same number of replications and the same variance, there
are very many possible competitors to the Bonferroni method of
controlling the 'family' significance level. Some of the possibilities
are 'Fisher LSD', 'Tukey HSD', 'SNK', and 'Duncan'. Which one to use
depends on the experimental design, how many comparisons are being
made, and exactly what you mean by 'family error rate'.
You do not give enough information about your overall experimental
design for me to recommend a specific one of these possible methods
of controlling the family error rate for $k$ paired comparisons.
Although the Bonferroni method can be too 'conservative' (overall
power too low), it is also among the most generally applicable method,
not to mention the simplicity of computation. [For example, in R statistical
software, the (Welsh)
procedure for a one-way ANOVA on levels that may have diverse variances,
uses the Bonferroni method as the default multiple-comparison method.]

Use of the Bonferroni correction


In which situation use position:absolute, position:relative, position:fixed and position:static in css

Question: I am getting started in html5 and css, I have little bit confused using css position .
I can find from stack overflow these links,
Difference between relative and absolute
When to use CSS positioning?
Position absolute but relative to parent
still i can't able to fixed out, I need to know all the position property with example and in which situation have to use which position property for developing web page.
Can you help me sir?
Any help would be highly appreciated. Thanks in advance.
Answer:

.parentClassDiv{
  position:relative;
  border-color:red;
  border-radius:4px;
  border-style:solid;
  height:150px;
  top:100px;
  }
.relativeClass{
  position:relative;
  border-color:green;
  border-radius:4px;
  border-style:solid;
  top:80px;
  left:30px;
  }
.absoluteClass{
  position:absolute;
  border-color:blue;
  border-radius:4px;
  border-style:solid;
  top:120px;
  }
.fixedClass{
  top:30px;
  position:fixed;
  border-color:yellow;
  border-radius:4px;
  border-style:solid;
  left:10px;
  }
.staticClass{
  top:10px;
  left:10px;
  position:static;
  border-color:brown;
  border-radius:4px;
  border-style:solid;
  }

  <title>difference b/w relative,absolute,fixed,static</title>

    hello..I am relative..positioned top-40px and left:30px..relative to my parent div(red color)
    hello..I am absolute
    hello..I am Fixed..I will be positioned from the page top(i.e:it parent always be html tag)
    I am Static.even top is 100px.i will be positioned on my place in my parent tag(red color).i will not take top,bottom,left,right.and also i started here only because green color is relative (reserved it place and moved to bottom)


Can I use the environment variable %PROGRAMDATA%?

Question: I type:
echo $USERPROFILE and get C:\Users\rob
echo $PROGRAMFILES and get C:\Program Files (x86)
echo $PROGRAMDATA and get nothing.
Under windows %PROGRAMDATA% evaluates to C:\ProgramData
Why are some windows environment variables supported and not others, or am I just doing something wrong here? If not, is there a list somewhere of which ones are converted for use under cygwin?
Answer: It is mixed case
$ set | grep -i programdata
ALLUSERSPROFILE='C:\ProgramData'
ProgramData='C:\ProgramData'

$ echo $ProgramData
C:\ProgramData


significant page load speed difference : directly accessing Tomcat (localhost) VS accessing tomcat via Apache (mod_jk connector)

Question: I have a tomcat v6 which contains 2 web applications (JSF2.0 and JSP). The physical server is RedHat Enterprise with 16GB memory.
In current form, the tomcat is exposed to the internet via apache 2.2 and we're by using mod_jk v1.28 connector. so in essence when a user types in www1.example.com/myWebApp where webApp has been configured in httpd.conf as worker1 which in turn points to above mentioned tomcat v6 above listening on port 8009 to handle the request.
Tomcat server.xml has the following relevant bits:
 <Connector port="8080"
             protocol="HTTP/1.1"
             maxThreads="150"
             connectionTimeout="20000"
             redirectPort="8443"
  />

 <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

in workers.properties worker1 has been configured as:
worker.worker1.type = ajp13
worker.worker1.host =localhost
worker.worker1.port = 8009

and in httpd.conf :
JkMount     /myWebApp/* worker1

In testing the page load speeds, when i access the web application by accessing the above tomcat directly using its localhost address (localhost:8080/myWebApp), the web application is fast and page load averages about 2-3 seconds max.
Now if i access the same web application, on same network except this time by going via apache (www1.example.com/myWebApp) the page is visibly slower and page load speed average between 10-12 seconds.
is this normal? I am suspecting that the leg work that happens between  apache ---> mod_jk --> tomcat v6 to handle any given request is adding up to the slow speeds? Can someone suggest ways in which i can improve the responsiveness of the web applications when requesting are coming from apache?
UPDATE:
DNS lookup delays is out of question given www1.example.com which is mapped to our local IP address so there is definitely no DNS look up delays contributing to this delay.
Comment: Do you have reverse DNS lookups enabled anywhere? `HostnameLookups` in apache, or maybe in your application. Is DNS correctly set up in your environment?
Comment: @Oliver `HostnameLookups Off` . I am not sure how to answer _"Is DNS set-up correctly_" as i don't really know how to test and find out if issues with DNS is slowing things sown. My role in this company is a Developer and you would normally think Networking/Infrastructure team would deal with such issues but unless i can prove there is an actual problem no one in interested in looking into it...
Comment: The reason I am asking about DNS is that such long delays are an indication of something such as a DNS lookup timing out. To check if your server does some DNS lookups it shouldn't, you could sniff port 53 traffic with tcpdump: `tcpdump port 53`.
Comment: @Oliver please see updated question but in short DNS lookup does not seem to be causing the delay.
Answer: Try testing on the localhost hostname first:
i.e with the localhost hostname via Apache. If it is faster, then you know you have a DNS issue.
If it is still slow try using mod_proxy to reverse proxy requests to 8080 and see if that slow e.g.
so firstly do
a2enmod proxy

and then in your VirtualHost (put in a separate conf, don't use http.conf), and remove the JKMount from http.conf
ProxyPassReverse /myWebApp/ http://localhost:8080/myWebApp/

If it isn't then you know its the AJP connector. It it is, then their is something else on your Apache server causing the problem
Comment: "_try with the localhost hostname via Apache...._" how can localhost name go through apache? i.e. if localhost name is `interna.melbourne.com` and typing  `interna.melbourne.com:8080/myWebApp` takes me to directly to tomcat (equivalent of typing localhost:8080/myWebApp) what do i need to do to make it go through apache? right now you would have to type `wwww.example.com/myWebApp` to go through apache.


f continuous and differentiable?

Question: Consider the function $$f:\mathbb{R}^2\to\mathbb{R}\; (x,y)\mapsto \begin{cases}
  \frac{x^ay^b}{(x^2+y^2)^c},  & (x,y)\not=(0,0)\text{,}\\
  0, & \text{else }
\end{cases}$$
I am trying to proof
a)f is continuous in $(0,0)\iff a+b\ge 2c+1$
b)f is differentiable in $(0,0)\iff a+b\ge 2c+2$
My try:
What I tried:  $\lim\limits_{r\to 0}f(rcos\varphi,rsin\varphi)=\lim\limits_{r\to 0}\frac{(rcos\varphi)^a(rsin\varphi)^b}{(r^2)^c}=\lim\limits_{r\to 0}r^{a+b-2c}cos^a\varphi sin^b\varphi=0$ $\iff$ $a+b-2c\ge 1$.
I'm not sure if the last step is ok. Or shall I seperate both directions in the proof?
b) $\lim\limits_{t\to 0}\frac{f((0,0)+tv)-f((0,0)}{t}=\lim\limits_{t\to 0}\frac{f(tv_1,tv_2)}{t}=\lim\limits_{t\to 0}\frac{t^{a+b}v_1^av_2^b}{t^{2c-1}(v_1^2+v_2^2)^c}=0$ $\iff$ $a+b-2c-1\ge 1$.  Is it correct?
Answer: Your first part looks great. You don't need to add any more steps, but you should say something about how cosine and sine are continuous and bounded, so they don't affect the convergence behavior around 0. Both directions seem clear to me.
For your second part, how are you defining differentiability? You have only checked verified that the directional derivative exists for each $v$. You have to do a little more work to prove that $f$ is fully differentiable at $(0,0)$. I would try it with an sequence of vectors of the form $t_n u_n$ where $t_n \to 0$ and $|u_n|=1$. It will looks very similar to what you've done. You have the right idea for evaluating the limit.
There is also a typo in the last limit. It should read $t^{2c+1}$.

f continuous and differentiable?


Flex 3.0 : Showing data in the legend of a Pie Chart

Question: I'm a newbie to Adobe Flex 3.0. I need to show data within the Pie Chart Legend, alongside the colored markers. I have a few vague ideas about how to go about it. (Maybe I would have to write my custom legendMarkerRenderer.) Could anybody give any pointers? There aren't many examples on the net regarding this.
Thanks in advance!
P.R.
Comment: It would be a good idea to specify that this is a question regarding Flex in the title or at least in the question description. The flex tag is the only pointer to that and I am pretty sure it's not clear enough.
Answer: To show the data on the Legend you will need to extend LegendItem class. Example you can see in my blog: http://northam.blogspot.com/2009/05/flex-showing-data-in-legend-of-pie.html
Enjoy!
Answer: Here's a really useful link for you. The Flex 3 Component explorer... It has examples of how to implement the majority, if not all, of the adobe flex components.  If you want something more complex you may need to extend legend and create you own component. By the sounds of things it should give you enough to go on
Flex 3 Component Explorer (broken link)
Answer: You can always customize the UI controls in flex as per ur requirements.
So you can extend the legend class
have a look @ this also:liveDocs


convert a point, in a given DIV, to point wrt to another DIV

Question: I want to covert a point, positioned in one DIV into a point wrt another DIV.
I have a following html in place

           <link href="default.css" rel="stylesheet" />

the default.css has following in it
#complete_canvas
{
    width:100%;
    height:100%;
    position:absolute;
}
#myDIv{
    position:absolute;
     left:100px;
     top:100px;
     width:760px;
     height:100px;
}

in the default.js i am adding event listeners for
    var canvas = getElem("complete_canvas");

    canvas.addEventListener("mousedown", onTouchDownOnDOMCanvas, false);

now, the point i get in onTouchDownOnDOMCanvas function is wrt to complete_canvas DIV.
i want this point wrt to myDIV div element.
so, for eg:, if i click at 100px , 100px (in complete_canvas) then i wrt to myDiv it will be 0 , 0
is there a way to do that conversion ?
thanks,
Answer: Using jquery
$("#complete_canvas").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
    //Calculations here
});

Using Javascript

Comment: Thanks for the answer. Is there a way to do this without using jquery ? thanks,
Comment: the javascript doesnt seem to do what is expected - it just prints the position where the user clicked rt ?
Comment: the jquery one would work i guess .. i am going to accept that as an answer. thanks.


Organise Trac's 'Available Projects' page

Question: Does anyone know how to split the list of projects on the 'Available Projects' page into a list of active and archived projects? At the moment they are all listed together and I have a large number of projects so it is difficult to identify just the active projects.
I'm not a web developer or python expert so I would appreciate simple, easy-to-follow answers.
Thanks in advance.
Answer: The project index can be customized. You'll need a criteria for grouping the projects into active and archived. Here you can see the variables that are listed for each project. You could add a value in the config/trac.ini file for each project, such as [project] archived = true, and read that value when rendering the project index in order to determine which group to list the project in - active vs. archived. The value can be read using env.config.get('project', 'archived').
Here is a proof-of-concept.
Create 4 projects and set 2 of them as archived:
$ mkdir projects && cd projects
$ virtualenv pve
$ source pve/bin/activate
$ pip install trac
$ mkdir environments && cd environments
$ for i in `seq 1 4`; do
    trac-admin env$i initenv "Project $i" sqlite:db/trac.db
  done
$ trac-admin env3 config set project archived true
$ trac-admin env4 config set project archived true

Add the following in projects/index.html:
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Available Projects</title>

Active Projects

        $project.name
        <py:otherwise>
          $project.name: Error
 ($project.description)
        </py:otherwise>

Archived Projects

        $project.name
        <py:otherwise>
          $project.name: Error
 ($project.description)
        </py:otherwise>

Run TracStandalone:
$ cd projects
$ TRAC_ENV_INDEX_TEMPLATE=`pwd`/index.html tracd -r -p 8001 --env-parent-dir=environments

The result is:
Comment: Great! Thank you RjOllos!
Comment: For those who are using fcgi, you need to add os.environ['TRAC_ENV_INDEX_TEMPLATE'] = "/path/to/template.html" to /usr/share/pyshared/trac/cgi-bin/trac.fcgi


Raid 1 disk failure recovery on Dell Poweredge 2850 - how to repair?

Question: Ive just spotted an amber disk error message on my 2850, E0D76 BP drive 4 fail. Drives are ULTRA 320 SCSI. Its been a while since this server was set up so I cannot be abolutely sure my memory is accurate but I think it was
Drive 0 73GB
Drive 1 73GB paired as RAID 1
Drive 2 146GB
Drive 3 146GB paired as RAID 1
Drive 4 146GB as hot swap
(I had a dodgy 146gb drive that was giving me flashing amber as a predicted fail but I thought better than nothing to leave it as the hot swap in drive 4)
I think I had the config as

<code>   Raid Ch- 0
ID

0 ONLIN A00-00
1 ONLIN A00-01
2 ONLIN A01-00
3 ONLIN A01-01
4 HOTSP
</code>

So on checking the config i now see

Seeing drive 4 as failed I removed it , and re-sited it and rebooted but still failed. So I rebooted without it in which gave a POST warning but corrected the LED error from amber to blue.
My question is, can someone with a clue help me figure what has happened, and how can I recover it?
[EDIT] Whats the best way to monitor hardware RAID failure, its PERC 4e/Di controller, OS is Windows Web Server 2008 R2. Can the state of the RAID array be monitored from within windows? Is there some error thrown in the event log that I can hook a warning event on to?
Answer: Logical drive 0 (RAID 1) has a failed hard drive or has not been rebuilt.  Drive 4 appears to be the mirror of drive 1.  Be very careful here and make sure you have a backup of all your data before proceeding.  I'd consider placing drive 0 in slot 4 and see if it rebuilds.  But, I can't verify from the screen shots which physical drives belong to which logical drives and what sizes they are.  At this point be very sure of what you're doing.
EDIT:  Looking at the screen shots again it appears that LD0 is using slots 1 and 4 and LD1 is using slots 2 and 3.  Confirm the hard drive sizes in the slots and proceed accordingly.  (Have a backup!)
Comment: I've got my data backed up already but I would still like to get this right :) If I put a new 73GB drive into drive 0 , it doesn't look like it would simply rebuild? presume I would have to config it as part of A00, then it would ? What I don't get is how the config seems to have migrated from what I remember to what I see now, unless my memory is worse than I thought
Comment: It really appears that LD0 is using slot 1 and 4.  So I'd put the new 73GB drive into slot 4 and it should rebuild.  Memory is the first thing to go with age :)
Comment: Ive got one on order murisonc and Ill update when I have put in the replacement
Comment: I moved the 73 GB drive from drive0 to drive4, will it simply rebuild over a few hours? Is there any way I can check from outside the SCSI config screen at bootup ?
Comment: It should rebuild on it's own but I'd verify it's working.  There is a tool called Dell OpenManage Server Administrator (free) that can be installed to manage the RAID without rebooting the server.


When is it OK not to keep a testing/holdout set?

Question: I am performing data imputation on a large matrix [100000,34] of past measurements that contains missing values (rows are time-steps and columns are stations).
So far I've used several machine-learning techniques for the imputation and I want to compare between them.
I do it using 10-fold CV on the non-missing values (i.e., in each fold, additional 10% of the non-missing values are set as nan, and then I perform the imputation on the entire matrix and evaluate on the 10% I put aside). I also do repeated-holdout (Monte Carlo cross-validation) so I can sample different missing interval lengths for evaluation.
Eventually, I want to find the best performing algorithm FOR IMPUTATION and to impute my entire matrix. I am not using the imputed matrix or features for prediction at all (i.e, I don't have a target).
What bothers me is that I don't set aside a testing-set for the final evaluation of the chosen imputation model, and I'm not sure that this is the right workflow. In my intuition, it shouldn't matter much since my testing set is the real missing values in the matrix and my only goal is to choose the algorithm that will impute it best. Nevertheless, everywhere I read people highlight how important this stage is.
So, Is this stage critical to my application? I would appreciate some advice from experienced machine learners...
Thanks
Comment: It might make you feel better if you chose the winner based on the average of CV scores... the holdout is the holdout so you can see that you're stable but choose your model using the CV scores. If the holdout was vastly different I might wonder if you're even able to simulate the "missing" properly. Maybe true missing isn't random?
Comment: I used CV for hyperparameter tuning (for example, one of the estimators is Random Forest and it has many parameters). Later, I use the repeated holdout for choosing the winner, since that way I am able to estimate the performance of the tuned models per different missing interval lengths (I extract different sizes of missing chunks for this validation). I think the results are pretty consistent.
Answer: This is not necessarily an answer, but it was too long for the comment section.
In a simple scenario one would like to impute features to predict a target. Which imputation method works best is indeed a question of experimentation, a hyperparameter if you will; to be found out using for example k-fold cross-validation. The final verdict on the whole procedure though would be gotten by applying the imputation, the model to predict the target in order to find out the final metric on the target. It would also answer the question if the imputation helped at all; maybe dropping observations is better.
If there is no target, i.e. the targets are the imputed values, then one can still hold out a test set and report the accuracy of the imputation method per feature by indeed masking some known values.
Depending on the workflow, it might be advisable to mark each value as imputed or not. The fact that the value was missing might be a signal of itself, more so than the imputed value. Some digging into the causes of the missing values could give more confidence in the imputation. A weather station not reporting in a hurricane might have a very specific meaning! Missing at random (MAR) and missing completely at random (MCAR) are some keywords to look for.
HTH
Comment: Thanks for the reply, you've raised some good points. Yes, in my case, I don't have a target. And yes, I can hold out a final test set. But should I? BTW, I'm doing a multivariate imputation (using IterativeImputer from scikit-learn) with different estimators (Bayesian Ridge, Ransom forest, KNN). So far CV was used for hyperparameter tuning of the estimators of the IterativeImputer and repeated holdouts for later validation per interval length. Other than that, MCAR is never a reasonable assumption, but I do assume MAR.
Comment: You loose nothing by setting apart a test set, no? It is just used for reporting the error on of the imputation. It would mainly serve to validate the cross-validation procedure.
Comment: Well, I loose some data I can learn from and so I might end up underestimating the error of the imputation... Also, technically, when I perform an imputation of the matrix, the entire matrix in imputed. So any test-set set apart will necessarily be imputed. Notice I wrote that after the CV I do repeated holdouts so I can estimate performance per missing interval lengths. In that stage, I choose the winner. As I see it, in that stage (many repeated holdouts), I already have a good estimation on the performance of the different models per different missing chunk sizes. So isn't that enough?
Comment: My point is, I can't see why the error of the imputation on a test-set I set aside would be any different than the estimation obtained by many repeated holdouts.
Comment: Well, to make sure you did not overfit using the holdouts; as always. Imagine trying thousands of combinations using the holds.
Comment: Ok, I think I'm convinced. I probably don't even need both CV and repeated holdout, I can just use the latter for parameter tuning. And of course save a test set for final validation.
Answer: We build a prediction model using one or machine learning algorithms for future use. The historic data used to train the model, for those you know the outcome already. So what you want to know at the end of the day, is how your prediction models perform on future data. Your test set or validation set are these 'future data'.
In general, the larger your training set is in terms of cases/observations the less likely overfitting is to occur - the situation you want to investigate using a separate test or validation set. On the other hand, the more flexible a prediction model is the higher the risk over overfitting.
For training classifiers some theoretical results are available. Confidence intervals for the error rate has been derived for linear and quadratic discriminant analysis. See chapter 10 in the book Discriminant Analysis and Statistical Pattern Recognition by G.J. McLachlan (Wiley), 2004. These confidence intervals provide bounds for the performance on future test data. For more complex learning algorithms, such theoretical results do not yet exist (to my knowledge, that is).
For nonparametric classifiers, you can only assess future performance using validation data.

Specifically, you perform imputation of missing values. As stated, different missing value mechanisms can be the case:

MCAR (Missing Completely At Random)
MAR (Missing At Random)
NMAR (Not Missing At Random)

MCAR means that the probability that a data point is missing (i.e. a '?' in your data matrix), the observed data you do have - they give no clue what so ever about the most likely value (range) of the missing data point. Strict independence between the missing data mechanism and the observed data variables is present.
MAR means that the (unknown) value of the missing data point itself does not influence in any way the probability that the data point has gone missing. However, one or more observed data values do statistically determine whether that particular data value is missing. Strict independence between the actual value of the missing data point and the probability that it is missing, that is the case with MAR.
NMAR means MAR, plus that the value of the absent value itself statistically influences the probability that it has gone missing.
Imputation of missing values can be successful using existing schemes (such as the EM-algorithm), when the missing data mechanism is MCAR or MAR. Nonetheless, many scientific studies have shown that missing value imputation by the EM-algorithm tends to yield imputed values closer to the (conditional) means of the distribution of the missing data than is the case in the true underlying distribution. Multiple imputation is one approach to overcome this problem - a real challenge when your data are not normally distributed.
Final conclusion and my advice is as follows. You model the missing data mechanism, perform imputation and build a predictive model afterwards. Hence, even more parameters are being fitted in your scheme than when just building a prediction model in 'one go'. More parameters combined with a complex scheme that models possible higher order relations between variables (namely the missing data mechanism) - these factors make validation by independent test sets even more necessary.
Comment: Thanks, but I'm not sure you're answering my specific question regarding the imputation I'm performing
Comment: Answer has been expanded as to completely cover your question.
Comment: Thanks, did you see my comment to @spdrnl? I don't build a predictive model at all. Sorry if my original question was not clear enough.


Understanding some statement in proof of the Lagrange's Theorem ( Rosen's Elementary number theory, Theorem 12.21 )

Question: I am reading the Rosen's Elementary number theory (sixth edition), proof of theorem 12.21 and stuck at understanding some statement.

Theorem 12.21. Lagrange's Theorem.. The infinite simple continued fraction of an irrational number is periodic if and only if this number is quadratic irrational.

I am reading the 'if' part ( his book p.510 ). He argued as follows :
Let $\alpha$ be a quadratic irrational, so that by Lemma 12.5, we can write $\alpha$ as
$$\alpha = (P_0 +\sqrt{d})/Q_0 ,$$
where $P_0 , Q_0, d$ are integers, $Q_0 \neq 0$, $d>0$, $d$ is not a perfect square, and $Q | (d-P_0^2)$.
Furthermore, by Theorem 12.22, we have $\alpha = [a_0 ; a_1, a_2 , \ldots]$, where
$$ \alpha_k=(P_k+ \sqrt{d})/Q_k,$$
$$ a_k = [ \alpha_k],$$
$$ P_{k+1} = a_kQ_k - P_k,$$
$$ Q_{k+1} = ( d- P_{k+1}^2 ) /Q_k, $$
for $k=0,1,2, \dots$
And through some argument ( If needed, I will upload more detailed argument ), the author shows that there is an integer $N$ such that $0 \le Q_k \le d $ and $ -\sqrt{d} < P_{k+1} < \sqrt{d}$ for $k \ge N$.
And he wrote that " we see that there are only a finte number of possible values for the pair of integers $P_k, Q_k$ for $k>N$." I don't understand why this statement is true until now. Isn't there a possibility that the sequence $(Q_k)$ and $(P_{k})$ could be bounded? Perhaps, if the subset $\{P_k\}$ ( or $\{Q_k\}$ ) of 'integers' is infinite set, then is it unbounded? Having written it, I think that this is a soft question but I propose this question to make this certainly sure :) Can anyone helps?
Comment: It is true that any bounded set of integers is finite (equivalently, any infinite set of integers is unbounded). Do you see why this is true? Does that resolve your question?
Comment: Thanks. Can we try to imitate https://proofwiki.org/wiki/Subset_of_Naturals_is_Finite_iff_Bounded ? :)  ( using that subset of finite set is finite ).
Answer: I'm not sure if I understand the question, but here is what I think is an answer (I'm posting this as an answer because it's a bit too long for a comment): the sequence $(Q_k)$ and $(P_k)$  are bounded, as the author has shown, but they are also integers, by definition. Therefore, they can only take finitely many values, because there are only finitely many integers between any two numbers. In this case, $Q_k$ (for sufficiently large $k$) can only be one of the finitely many $0, 1, 2, 3,..., d,$ and $P_k$ (for sufficiently large $k$), can only be one of the finitely many $a, a+1, a+2,...,0, 1, 2,..., b-2, b-1, b,$ where $a$ is the least integer greater than $-\sqrt{d}$, and $b$ is the least integer less than $\sqrt{d}.$
Comment: Thanks for kind and detailed answer. And..I think that there is a small errata : $a, a+1 , a+2 , \dots, 0 , \cdots $ is more correct? (  $a < a+1 < a+2 < \cdots $ )
Comment: I'm glad my answer helped, and you're certainly right! I've fixed it now.
Comment: Thank you!!~~~~


O que são artefatos do design de software?

Question: Estou estudando Design de Software através do SWEBOK e não consegui entender o que seriam os artefatos do design de software, como por exemplo em que tipo de documento seriam especificados os tipos de assuntos chave do design, como segurança, concorrência e internacionalização. Além disso, existe alguma ferramenta ou framework indicado para fazer esse tipo de documentação?
Comment: https://pt.stackoverflow.com/q/90308/101 parece responder melhor, se a resposta aqui fosse sobre isso a pergunta seria duplicata.
Answer: Acho que o que você está procurando é uma forma de especificar requisitos, sejam eles funcionais ou não funcionais. Já que você está estudando por uma metodologia bem bem clássica, eu recomendo dar uma passada de olho no Enterprise Architect.
segurança, concorrência e internacionalização são geralmente classificados como requisitos não funcionais, mas ainda são requisitos, podem/devem estar ligados a diagramas e a testes.


colocar um div dentro de uma funcao no php

Question: Tenho esse comando que faz a verificação no banco de dados e verifica se o usuário está bloqueado, em caso positivo mostra uma mensagem de erro, se não estiver bloqueado ele continua a execução normal.
O que estou querendo é quando ele fizer a verificação mudar a mensagem de erro para uma caixa, que quando o usuário clicar no botão login e se ele estiver bloqueado vai aparecer essa caixa.
Segue o codigo da "caixa":

                    <button type="button" data-dismiss="modal" aria-hidden="true" class="close"></button>

Atenção!

Usuario Bloqueado

PorFavor contatar algum adm para resolver.

e quero colocar essa div nessa funcao onde ele verifica o bloqueio
public function bloqueado(){
    $model = self::findByUsuLogin($this->usu_login);

    if ($model->usu_block){
         $this->addError('usu_login', "Usuario Bloqueado, por favor entrar em contato com algum adm.");
        return false;
    }else{
        return true;
    }
}

quero mudar a mensg de erro que aparece que é essa   para essa tela com a mensg de erro
se alguem puder me ajudar eu ficaria agradecido.
Comment: Desculpa amigo, nao entendi muito bem sua pergunta, pode explicar um pouco melhor???? obrigado.
Comment: vc falou pra fazer o echo pra aparecer essa caixa no caso eu quero aquela caixa que coloquei no exemplo que e o primeiro codigo so coloco ela no echo seria isso?
Comment: Opa, li seu comentario e é isso mesmo, porque assim que a função for chamada ela irá chamar o modal e mostrar assim como quer.
Comment: uai, troca a linha da mensagem por `$("#mod-danger").modal('show');`
Comment: Marque a resposta como aceita, veja como em https://i.stack.imgur.com/jx7Ts.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: Como não há elementos suficientes para reproduzir seu código, fiz com uma simples condicional para mostrar a tela de mensagem de erro

    $model="bloqueado";

    if ($model=="bloqueado"){
         $("#mod-danger").modal('show');
        //return false;
    }else{
        //return true;
    }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

           <button type="button" data-dismiss="modal" aria-hidden="true" class="close"></button>

Atenção!

Usuario Bloqueado

PorFavor contatar algum adm para resolver.

Comment: deu certo vlw irmao


Why are the standard errors the same for Anova + lsmeans results

Question: I am working with a type 3 ANOVA + lsmeans. I was wondering why sometimes the standard error of all factor levels have the same value?
This is my dataset. var, SW, trt are my factors. RG is my metric y-variable.
<code>trialdata<-structure(list(var = c("A", "A", "A", "A", "A", "A", "A", "A",
                       "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C",
                       "C", "C", "C", "C", "C", "C", "A", "A", "A", "A", "A", "A", "A",
                       "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C",
                       "C", "C", "C", "C", "C", "C", "C", "A", "A", "A", "A", "A", "A",
                       "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C",
                       "C", "C", "C", "C", "C", "C", "C", "C", "A", "A", "A", "A", "A",
                       "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B",
                       "C", "C", "C", "C", "C", "C", "C", "C", "C", "A", "A", "A", "A",
                       "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B",
                       "B", "C", "C", "C", "C", "C", "C", "C", "C", "C", "A", "A", "A",
                       "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B",
                       "B", "B", "C", "C", "C", "C", "C", "C", "C", "C", "C"), SW = c(28,
                                                                                28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31,
                                                                                31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29,
                                                                                31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29,
                                                                                29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28,
                                                                                28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31,
                                                                                28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31,
                                                                                31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29,
                                                                                29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28,
                                                                                29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31, 31, 28,
                                                                                28, 28, 29, 29, 29, 31, 31, 31, 28, 28, 28, 29, 29, 29, 31, 31,
                                                                                31), trt = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                                                                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                                                                                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
                                                                                3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
                                                                                3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
                                                                                4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
                                                                                6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6),
               RG = c(8, 7, 8, 7, 5, 8, 7, 5, 4, 7, 7, 5, 7, 5, 6, 7, 7,
                      4, 9, 8, 6, 8, 6, 7, 8, 5, 7, 7, 6, 5, 7, 8, 7, 7, 7, 6,
                      9, 7, 6, 8, 5, 8, 7, 6, 7, 7, 6, 7, 7, 6, 8, 9, 7, 6, 9,
                      6, 8, 8, 6, 7, 8, 7, 8, 4, 7, 6, 7, 6, 5, 6, 5, 4, 6, 8,
                      7, 9, 7, 6, 7, 8, 5, 3, 8, 7, 5, 6, 6, 6, 4, 5, 7, 9, 5,
                      8, 5, 7, 7, 4, 8, 6, 7, 6, 7, 8, 7, 6, 4, 6, 4, 5, 8, 6,
                      7, 7, 5, 4, 7, 8, 7, 6, 6, 4, 6, 6, 8, 6, 7, 6, 8, 7, 8,
                      6, 7, 5, 8, 7, 6, 7, 6, 7, 8, 8, 8, 7, 7, 7, 8, 9, 7, 7,
                      6, 7, 8, 7, 7, 8, 7, 8, 8, 7, 7, 8)), row.names = c(NA, -162L
                      ), class = c("tbl_df", "tbl", "data.frame"))
</code>
This is my code to calculate the ANOVA and lsmeans:
The lsmeans are displayed in a letters display (cld).
<code>#load libraries
library(readxl)
library(lme4)
library(ggplot2)
library(ggridges)
library(car)
library(emmeans)
library(multcompView)
library(multcomp)

trialdata<-read_excel("Evaluation.xlsx",sheet=1,col_names=TRUE)

#factorize
trialdata[1:3]<-lapply(trialdata[1:3],as.character)

#make numeric
trialdata[4:4]<-lapply(trialdata[4:4],as.numeric)

#ANOVA; Lsmeans, CLD, ggplot
print(Anova(model<- lm(RG~SW+trt+var,data=trialdata),type="III",singular.ok = TRUE))
lsmeans<-emmeans(model,pairwise  ~trt)
clddata <- cld(lsmeans,
               alpha=0.05,
               Letters=letters,
               adjust="tukey")
clddata$.group<-gsub(" ", "",  clddata$.group, fixed = TRUE)

print(ggplot( data= clddata, aes(x=trt,y=emmean)) +
        geom_text(size=4,aes(y=emmean+SE*2.0,label=.group),position=position_dodge(0.9),angle=0,vjust=0.5, hjust=0.3 ) +
        geom_bar(stat="identity", position=position_dodge(), colour="black")+
        geom_errorbar(aes(ymin=emmean-SE, ymax=emmean+SE), width=.1,position=position_dodge(0.9))+
        geom_line(position=position_dodge(0.9))+
        geom_point(position=position_dodge(0.9)) +labs(y="RG", x = "", fill= "")+
        theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))+
        theme(axis.title.y = element_text(size=16))+
        theme(axis.text.x = element_text(margin = margin(t = 10, r = 20, b = 0, l = 0)))+theme(axis.text.x = element_text(size=16,angle=0)))
</code>
Here is the ggplot output, where you can see that the standard errors are all the same:

Here is the output of the lsmeans table:
Comment: Hello, thanks for your comment. I used dput. Is it better now?
Comment: Welcome to CV. Since you're new here, you may want to take our [tour], which has information for new users. Could you use `dput` to share your data?
Answer: I think the answer by Russ Lenth, the emmeans package author, here, answers your question.  Interpreting the standard error from emmeans - R


Symfony 2.1 Security Cross Subdomain

Question: Running Symfony 2.1 on an application and we have different sandboxes of the code. Eg.

aequasi.someurl.com
dev.someurl.com
hotcarl.someurl.com

I cant seem to figure out why, but when im logged into aequasi, and i go to hotcarl, i need to log in again. When i do, it logs me out of aequasi.
All sandboxes are using the same database for auth
i have this in my config.yml:
framework:
    session:
        cookie_domain: .someurl.com
        domain:        .someurl.com

ive got the php.ini set up to use the same url too
also, the session_id's are the same
Comment: What happens when you point all three domains to the same sandbox? Does this still occure? As per default, symfony is saving the session information inside the cache directory, so if you access a different sandbox, the session information are again sent (I guess) but the new sandbox cannot find them in it's own cache directory, so you have to log in again.
Comment: Are the security firewalls on all 3 sites named the same thing?
Comment: three three branches of code are completely identical, at the moment. Only thing that differs, is the url
Comment: Is there a way to change that functionality?
Comment: Both pointed to the same directory and this is still occuring
Answer: Use a database, or memory as the Session storage. This allows you to share session data across three different symfony applications (each with their own sandbox). This will remove the inconsistencies between application caches and allow you to use a *.domain.com type cookie.
Symfony2 provides several drivers for alternative session storage.
http://symfony.com/doc/current/components/http_foundation/session_configuration.html#custom-save-handlers
Comment: where is this logic supposed to go?
Comment: well, did some research, wasnt very easy to find, but i used this
http://hipaway.com/blog/symfony2-sessions-in-memcache/
Comment: Little out of date tho, i think im gonna make my own blog post and updating the solution a bit. Thanks for your help james!

Symfony 2.1 Security Cross Subdomain


Computing determinant of this matrix

Question: I have a very specific kind of matrix and I have to find the formula to find the determinant of these matrix.
a(i,j)=a if(i==j) and a(i,j)=0 if(floor(i/2)=floor(j/2) and i!=j) and n is odd
$$ A=(a_{i,j})_{n \times n}=\left(
\begin{array}{ccccc}
a&0&b&b \cdots &b&b\\
0& a&b&b \cdots& b&b\\
b& b& a&0 \cdots& b&b\\
b& b& 0&a \cdots& b&b\\
\vdots& \vdots& \vdots& \ddots&\cdots\\
b&b&b & \cdots&b&a
\end{array}
\right)? $$
Comment: What's the rule for the placement of the $0$'s ?
Comment: Try writing down its eigenvectors.
Comment: a(i,j)=a if(i==j) and a(i,j)=0 if(i/2=j/2 and i!=j)
Comment: Please notice n is odd
Answer: The problem is closely related to this one posted and answered yesterday, with $p\leftarrow2$, $np\leftarrow n-1$, $c\leftarrow a/b$, with the entire matrix divided by $b$.
Since according to a comment under the question $n$ is odd, we need to deal with the last component separately. All eigenvectors in the linked question except for the one filled with $1$s sum to $0$. Thus we can append a $0$ to them to obtain eigenvectors of the present matrix. That leaves a two-dimensional subspace to be dealt with, spanned by the vector $x$ that has a $1$ in the last component and the vector $y$ that has $1$s everywhere else. Applying $A$ to these vectors yields $Ax=ax+by$ and $Ay=(n-1)bx+((n-3)b+a)y$. Thus the product of the remaining two eigenvalues is
$$
\left|\matrix{a&b\\(n-1)b&(n-3)b+a}\right|=((n-3)b+a)a-(n-1)b^2\;.
$$
Multiplying this by the $n-2$ eigenvalues from the linked question, with the above substitutions and the factor $b^{n-2}$ that was divided out, yields the determinant of the present matrix:
\begin{align}
\det A
&=
\left(((n-3)b+a)a-(n-1)b^2\right)b^{n-2}\left(\frac ab\right)^{(n-1)/2}\left(\frac ab-2\right)^{(n-3)/2}
\\
&=
\left(((n-3)b+a)a-(n-1)b^2\right)a^{(n-1)/2}\left(a-2b\right)^{(n-3)/2}\;.
\end{align}
Comment: @achille: Aha -- thanks for pointing that out -- yet another reminder why it's a bad idea to bury clarifications of the question deep in the comments...
Comment: It sounds pretty close but $n$ is odd...
Comment: Can this matrix have a particular formula?
Comment: @Alen: How do you mean, can it?
Comment: Means, can I derive a formula for calculating the det A?
Comment: @Alen: There you are.
Comment: @joriki : Sorry to ask for you favour again and again but can you please help me to understand it cause I want myself to be able to find the determinant when a(i,j)=0 if(floor(i/3)=floor(j/3) and i!=j) and time n=3*k-1. Pleaseee...
Comment: @Alen: I don't know what kind of a response you expect to "please help me understand it". If you're having trouble understanding parts of the answer, please point out which parts you don't understand and what's causing the problems.
Comment: @joriki: If I exactly have  [link](http://math.stackexchange.com/questions/383244/determinant-of-matrix) this question just with (pn-1)*(pn-1) dimension of matrix, can I get a generalized solution?
Comment: @Alen: Yes, you can proceed much like I proceeded in this answer here. You'll have $p-2$ vectors that sum to zero in the last, incomplete block (these didn't exist here in the case $p=2$), and these are eigenvectors with eigenvalue $a$; and you'll have one vector that's filled with $1$s in the last block, and that's the one you have to treat specially like I did in this answer. The fact that it had only a single entry in the present case isn't important; you can do practically the same thing I did here also if $p-1\gt1$.
Comment: @joriki: Treating the last component separately, I am not being able to understand this part. :(
Comment: @Alen: These comments are getting a bit out of hand. I don't mean anything other than what I did in this answer. If you don't see how to apply that for $p\gt2$, you should ask a separate question about that; that's not something that should be explained in comments.
Comment: @joriki: as you suggested I have asked another question. [This](http://math.stackexchange.com/questions/384712/generalizing-formula-for-calculating-determinant-of-specific-matrix), please help
Answer: Since $n$ is odd, let $n = 2m+1$ and $u_n$ be the $n \times 1$ column vector with all entries one.
The matrix $A$ can be rewritten to have the form $X + b u_n u_n^{T}$ where $X$ is a block
diagonal matrix consists of $m$ $2\times 2$ block $\tilde{X}$ and one $1 \times 1$ block:
$$X = \begin{pmatrix}
\tilde{X} & 0 & 0 & \dots & 0\\
0 & \tilde{X} & 0 &\dots  & 0\\
0 & 0 & \tilde{X} &\dots  & 0\\
\vdots &\vdots & \vdots & \ddots & 0\\
0 & 0 & 0 & 0 & a - b
\end{pmatrix}
\quad\text{ and }\quad \tilde{X} = \begin{pmatrix}a - b & -b\\-b & a-b\end{pmatrix}
$$
When one perturb an invertible matrix $X$ by a rank one matrix like $b u_n u_n^T$, it is known that the determinant of the updated matrix $X + b u_n u_n^{T}$ is given by:
$$\det( X + b u_n u_n^{T} ) = \det(X)( 1 + b u_n^{T} X^{-1} u_n )\tag{*}$$
Substitute our special form of $X$ into $(*)$ and notice:
$$\begin{align}
\det(X) &= \det(\tilde{X})^m (a - b) = ((a-b)^2 - b^2)^m (a - b)\\
u_n^{T} X^{-1} u_n &= m\;u_2^T \tilde{X}^{-1} u_2 + \frac{1}{a-b}
= \frac{2m}{a-2b} + \frac{1}{a-b}
\end{align}$$
We get:
$$\begin{align}
\det A &= ((a-b)^2 - b^2)^m (a - b)\left\{1 + b \left(\frac{2m}{a-2b} + \frac{1}{a-b} \right)\right\}\\
&= a^m (a-2b)^{m-1}\left(a^2 + 2 (m-1)ab - 2mb^2\right)
\end{align}$$
Update
For the general case when the matrix elements is given by:
$$a_{i,j} = \begin{cases}
a, & \text{ for } i = j\\
0, & \text{ for } \lfloor\frac{i}{q}\rfloor = \lfloor\frac{j}{q}\rfloor \wedge i \neq j\\
b, & \text{ otherwise }.
\end{cases}$$
where $0 \le i, j < n$ and $q$ is an integer $> 1$. Let $n = mq + r$ where $0 \le r < q$. Once again, we rewrite $A$ into the form $X + b u_n u_n^T$ where X is now a block diagonal matrix consists of $m$ $q \times q$ block $\tilde{X}_q$ and one $r \times r$ block $\tilde{X}_r$.
It is not hard to verify the entries on $\tilde{X}_s$ is given by:
$$(\tilde{X}_s)_{i,j} = \begin{cases} a-b, &\text{ for } i = j\\-b, &\text{ otherwise. }\end{cases}
\quad\implies\quad
\begin{cases}\det(\tilde{X}_s) &= a^{s-1}(a - sb)\\
u_s^{T} \tilde{X}_s^{-1} u_s   &= \frac{s}{a-sb}\end{cases}
$$
Repeating the same procedure as above, we obtain the formula for $\det(A)$ in the general case:
$$\det A = (a^{q-1}(a - qb))^m (a^{r-1}(a-rb)) \left\{1 + b \left(\frac{mq}{a-qb} + \frac{r}{a-rb}\right)\right\}$$
Comment: hue:r can be -1 here?
Comment: @Alen that is a typo, should be $0 \le r < q$. In principle, one should treat $r = 0$ as a special case. However, it turns out the final expression also work for the $r = 0$ case.
Comment: I was actually thinking of (pn-1)*(pn-1) dimension matrix
Comment: @Alen, your $pn-1$ case is equivalent to setting the parameters $(m,q,r)$ to $(n-1,p,p-1)$ in my answer.

Computing determinant of this matrix


Interesting Locus problem

Question: A variable line passes through $P(2,-1)$ and cuts the co-ordinate axes at $A$ and $B$ respectively.
$Q$ lies on line AB such that $$\frac{2}{PQ} = \frac{1}{PA} + \frac{1}{PB}$$ Find the locus of point Q
Comment: @ Lucas. Without loss of generality, you can shift $P$ to origin and call it a harmonic mean locus for $Q$. Its locus is available. If you agree I could edit it. But at first please put down how you started  solving it.
Comment: @Narasimham What will happen to PA and PB when P becomes origin?
Comment: I meant to shift the entire diagram so that P is center of origin  in finding inversion circles.
Comment: @Lucas 1) Is length of PQ ( harmonic average ) always the same? 2) How sure are you that that the locus exists and is unique? 3) Should the locus pass through the given fixed points A and B ? 4) Is it not a repeat question?
Answer: $Q$ lies on a line through the origin with slope $\frac{1}{2}$.

Let we prove it through the properties of the circular inversion. We take a circle with centre at $P$ and radius $1$, then consider the inverse of the $x$-axis and the inverse of the $y$-axis. They are two circles ($\Gamma_x,\Gamma_y$) meeting at $P$. We have $A^{-1}\in\Gamma_x$ and $B^{-1}\in\Gamma_y$: in order to get $Q$, we just need the inverse of the midpoint of $A^{-1}B^{-1}$. But the midpoint of $A^{-1}B^{-1}$ always lies on a particular circle (the red circle in the above picture) of the coaxal bundle given by $\Gamma_x$ and $\Gamma_y$, i.e. the circle through $P$, the centre of $\Gamma_x$ and the centre of $\Gamma_y$. It follows that $Q$ always lies on a particular line, the line through $(2,1)$ and $(-2,-1)$.
That is also a consequence of the fact that the initial condition grants that the cross-ratio $(P,A,Q,B)$ is always the same. A third alternative is provided by the following fact: in a trapezoid having bases with lengths $a,b$, the segment parallel to the bases through the point of intersection of the diagonals has length given by the harmonic mean of $a$ and $b$, i.e. $\frac{2ab}{a+b}$.
Answer: I have taken a related case where P is the origin ( without loss of generality, the entire graph can be shifted to required point) with harmonic mean of two free  segments (shown as dots $A,B$ , intersection points with radius vector) as constant (represented by the unit purple circle shown).

Interesting Locus problem


Given that $y = \frac{2x+1}{x}$, show that $x\frac{\mathrm{d}^{2}y}{\mathrm{d}x^{2}} + 2\frac{\mathrm{d}y}{\mathrm{d}x} = 0$

Question: Given that $y = \frac{2x+1}{x}$, show that
$$x\frac{\mathrm{d}^{2}y}{\mathrm{d}x^{2}} + 2\frac{\mathrm{d}y}{\mathrm{d}x} = 0$$
My though process has been to differentiate and solve for y and substitute dy/dx with it in the equation. Maybe then rearrange for x and substitute as well? This and everything else I've thought of seems wrong though.
Advice on how to solve and hints would be greatly appreciated over providing the answer, please. Thank you
Comment: **Hint:** Find the first and second derivative, substitute and simplify and see if you get zero. I just tried it and it works. You can simplify $y = 2 + \dfrac{1}{x}$.
Comment: Use `\frac{}{}` instead of `\over`
Answer: The proposed ODE is actually solvable:
\begin{align*}
xy'' + 2y' = 0 & \Longleftrightarrow x^{2}y'' + 2xy' = 0\\\\
& \Longleftrightarrow (x^{2}y')' = 0\\\\
& \Longleftrightarrow x^{2}y' = a\\\\
& \Longleftrightarrow y' = \frac{a}{x^{2}}\\\\
& \Longleftrightarrow y(x) = -\frac{a}{x} + b\\\\
& \Longleftrightarrow y(x) = \frac{bx - a}{x}
\end{align*}
In the particular case of the proposed question, $a = -1$ and $b = 2$.
Hopefully this helps!
Comment: Looking at it now, the solution seems so obvious and simple. Thank you for taking the time to answer. This  was exactly the help that I needed!
Comment: @Raelyn You are welcome! I am glad I could help.


Modifying generic maps in Scala

Question: I'm new to the Scala landscape after spending the last 10 years in Java and the last ~year in Groovy. Hi Scala!
For the life of me I can't seem to get the following code snippet to compile, and its just complicated enough to the point where the Google Gods aren't helping me.
I have a map that will contain Strings for keys and Lists of Tuples for values. The tuples will be a String-Long pair. In Groovy this would look like:
Map<String,List<Tuple2<String,Long>>> data = [:]

I need to be able to add and modify keys and values for this map. Specifically, I need to:

Add to the List of Tuples for existing keys
If a key doesn't exist, instantiate a new List of Tuples, and then add the key and list as a map entry

In Groovy this would look like:
Map<String,List<String,Long>> data = [:]

def addData(String key, String message) {
    Long currTime = System.currentTimestampInMillis()
    Tuple2<String,Long> tuple = new Tuple2<String,Long>(message, tuple)

    if(data.contains(key)) {
        data.key << tuple
    } else {
        data[key] = new List<Tuple2<String,Long>>()
        data.key << tuple
    }
}

I'm trying to do this in Scala, albeit unsuccessfully.
My best attempt thus far:
object MapUtils {
    // var data : Map[String,ListBuffer[(String,Long)]] = Map()
    val data = collection.mutable.Map[String, ListBuffer[(String, Long)]]()

    def addData(key : String, message : String) : Unit = {
        val newTuple = (message, System.currentTimeMillis())
        val optionalOldValue = data.get(key)

        optionalOldValue match {
            case Some(olderBufferList) => olderBufferList += newTuple
            case None => data
                .put(key, ListBuffer[(String, Long)](newTuple))
        }
    }
}

Complains with this compiler error on the case Some(olderBufferList) => olderBufferList += newTuple line:
value += is not a member of Any

Any ideas what I can do to get this compiling & working?
Comment: `ListBuffer[String,Long]` -> `ListBuffer[(String,Long)]`
Comment: Thanks @talex (+1) - please see my changes which incorporate your suggestion. This produces a new compiler error. Any ideas? Thanks again!
Comment: Which string produce it?
Comment: you declare a `var tupleOpt : ListBuffer[String,Long] -> ListBuffer[(String,Long)]` but don't assign any value to it.
Comment: and I don't think `ListBuffer[String,Long]` takes two type paramereters
Answer: The short version for your needs will be:
val map = mutable.Map[String, ListBuffer[(String, Long)]]()
map.put(key, map.getOrElse(key, ListBuffer[(String, Long)]()) += ((message, System.currentTimeMillis())))

You have some syntax issues with your code, If I'll try to change addData it would look like this:
def addData(key : String, message : String) : Unit = {
  val newTuple = (message, System.currentTimeMillis())
  val optionalOldValue = map.get(key)

  optionalOldValue match {
    case Some(olderBufferList) => olderBufferList += newTuple
    case None => map.put(key, ListBuffer[(String, Long)](newTuple))
  }
}

Comment: The default map implementation in Scala is immutable. In order to use mutable map we should explicitly ask to use the mutable collection. val map = mutable.Map[String, ListBuffer[(String, Long)]]()
Comment: `collection.mutable.Map[...]()`
Comment: Thanks @Michael K. (+1) - I think we're close but Scala doesn't seem to like the line with your `case Non =>...` statement. It doesn't like the use of `map.put` there, saying `value put is not a member of Map[String,scala.collection.mutable.ListBuffer[(String, Long)]]`. Any ideas?
Comment: Thanks again @Michel K (+1) - please see my edit above. I have now included the full SSCCE including the class definition and `data` instantiation. When I comment out my `data` instantiation and replace it with  your suggestion above, the Scala compiler now complains `not found: value mutable`.
Comment: Thanks @jwvh (+1) - please see my edits. Now I'm getting `value += is not a member of Any` in the `case Some(...` line.
Comment: `import scala.collection.mutable.ListBuffer`
Comment: Thanks @jwvh please see [my gist of this](https://gist.github.com/zharvey-welltok/763ca2e11eb40c373b5f6d560decac4b), as you can see, the `import` statement *is* there. But this code does not compile.
Comment: Don't know what to tell you.  I plugged it in to my IDE (Intellij 2016.2.2). It compiles and runs for me.
Answer: You are missing an import for ListBuffer. The following code works perfectly fine in 2.9.1 (tested on TryScala), 2.11.7 (tested on IDEOne) and 2.11.8. Note the only addition is the first line adding the import:
import collection.mutable.ListBuffer

object MapUtils {
    // var data : Map[String,ListBuffer[(String,Long)]] = Map()
    val data = collection.mutable.Map[String, ListBuffer[(String, Long)]]()

    def addData(key : String, message : String) : Unit = {
        val newTuple = (message, System.currentTimeMillis())
        val optionalOldValue = data.get(key)

        optionalOldValue match {
            case Some(olderBufferList) => olderBufferList += newTuple
            case None => data
                .put(key, ListBuffer[(String, Long)](newTuple))
        }
    }
}

MapUtils.addData("123", "message 1")
MapUtils.addData("456", "message 2")

MapUtils.data
//=> Map(456 -> ListBuffer((message 2,1472925061065)), 123 -> ListBuffer((message 1,1472925060926)))

Modifying generic maps in Scala


How can my function take csv files as an input?

Question: I need to take a csv file as a function argument and as an example code I have:
import openpyxl
from openpyxl import load_workbook
import csv
import xlrd

def supermarket(filename):
dictionary = {}
with open(filename, newline='') as filename:
    read_csv = csv.reader(filename, delimiter=',')
    for row in read_csv:
        dictionary += row[0]
        dictionary[row[0]] = row[1]
return dictionary

print(supermarket(prices1.csv))

However, when I debug the code, the traceback error says it is a NameError for which

prices1

is not defined. My professor is telling me that my argument should be able to take prices1.csv as an argument but I don't see how that's possible.
Answer: Your code is actually referring to a member csv of variable prices1, which obviously doesn't exist. Filename should actually be a string. So your code can be changed to this (assuming the csv file lies in the same directory as your working directory):
import openpyxl
from openpyxl import load_workbook
import csv
import xlrd

def supermarket(filename):
    dictionary = {}
    with open(filename, newline='') as filename:
        read_csv = csv.reader(filename, delimiter=',')
        for row in read_csv:
            dictionary += row[0]
            dictionary[row[0]] = row[1]
    return dictionary

print(supermarket("prices1.csv"))

Answer: If it is convenience, use pandas library to handle CSV file in much more efficient way.


Importar arquivo .csv para o servidor

Question: Estou realizando uma tarefa para importar dados de um arquivo .csv para o servidor.
Já consigo importar o arquivo tudo certinho no lado do servidor, porém cada arquivo contém cerca de 25 mil registros e o usuário fica aguardando até completar o upload. Eu coloquei um simples load na página enquanto o usuário aguarda.
Porém gostaria de saber se tem alguma biblioteca que cria uma barra com o status de upload para que o usuário saiba quanto tempo resta pra finalizar o upload.
Comment: Olá, veja essa pergunta aqui.http://stackoverflow.com/questions/24545780/bootstrap-progress-bar-for-mvc-file-upload
Comment: sua aplicação é webforms?
Comment: Olá @MarconcilioSouza é em MVC
Answer: Tem algumas, como o jQuery File Upload. Aqui tem um artigo que explica como implementar para o ASP.NET MVC.
O dropzone.js é outra solução elegante, com o mesmo princípio.
Mais alguns:

Plupload;
Uploadify;
FancyUpload;

Mas acredito também que você quer processar o CSV e reportar o usuário do progresso disso. Esta parte é explicada pelo Dino Esposito em duas partes, aqui e aqui, respectivamente.

Importar arquivo .csv para o servidor


is $x^2+x+1 \in \mathbb{F}_2$ solvable by radicals?

Question: Is $x^2+x+1 \in \mathbb{F}_2$  solvable by radicals?
First of all, this polynomial is irreducible in $\mathbb{F}_2$. It is also separable since f'(x)=1.
But the zeros of f(x) are $(-1)^{2/3}, - (-1)^{1/3} \in \mathbb{C}$.
So im unsure how i can define K, its field of decomposition.
Also, after defining K, is there a "tower" of radicals?
Thanks
Comment: Sorry I gave away my Galois Theory books. There are exercises in Lang's Algebra, though, that show that in characteristic $p$ a GG of order $p$ arises from a $X^p-X+a$.
Comment: @ancientmathematician: That is, indeed, a standard result/exercise. For a local solution see [here](https://math.stackexchange.com/a/50062/11619).
Comment: The splitting field of $x^2+x+1$ over $\mathbb{F}_2$ is $\mathbb{F}_2^2\simeq \mathbb{F}_2[x]/(x^2+x+1)$.
Comment: In general, if $\Phi_n(x)$ is the $n$-th cyclotomic polynomial, its splitting field over $\mathbb{F}_p$ is $\mathbb{F}_p^d$ with $d$ being the least integer such that $n$ is a divisor of $p^d-1$.
Comment: So here $d=2$. But now how do I verify if it has a tower of radicals? @JackD'Aurizio
Comment: Modulo $p$ "solvability" is more complicated than characteristic $0$. Instead of $p$-th roots we've got to allow ourselves to adjoin roots of $X^p-X+1$.
Comment: can you give me more details @ancientmathematician
Answer: Over a finite field $K$ every polynomial is solvable by radicals in the following sense. If $p(x)\in K[x]$, then the splitting field $L$ of $p$ over $K$ is another finite field. But any extension of finite fields, such as $L/K$, is cyclic because the Galois group is generated by the Frobenius automorphism $F(x)=x^q$, where $q=|K|$. Thus the Galois group is solvable.
We also get $L/K$ as a kind of root tower extension. This is trivially so, because every element of $L$ is a root of unity of order that is a factor of $|L|-1$.
The splitting field of your polynomial is the field of four elements. Its zeros are third roots of unity.
A catch is that it is often impossible to generate an extension of degree $n$ by adjoining an $n$th root of an element of the base field. You may need to use higher roots.


NodeJS + SocketIO pushing to Mobile App

Question: I see on SocketIO's web site that it's possible to use SocketIO for mobile device. I tried to find a documentation on its site about how to do this but I could not find any.
Has anyone figured out how to emit a message to mobile device using SocketIO? My guess is that it has to live inside a WebView or something that can run javascript?
EDIT
What if I am not planning to use Sencha or PhoneGap. I wanna go native. Objective-C/Java. Would this be possible?
Adding to the chosen Answer
I found a java socket.io client
https://github.com/benkay/java-socket.io.client
Answer: Socket.io which leverages web socket protocol (An upgrade request sent to server by the client over HTTP) offers a full duplex channel for communication. It is being supported by many web browsers in mobile space as you mentioned.
To implement this, one of the use case would be, for instance you having a phonegap based app to be developed which is basically HTML, CSS & JS. So to have a dedicated full duplex communication channel you can use socket.io.
When you write your Node JS Server : Referring the Socket.io Website
var io = require('socket.io').listen(80); // beauty is web socket still runs in 80/443(WSS) and leverages TCP's capabilities.

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

But in your mobile dev  side, you will have to include the JS in your HTML where you wanted to leverage web socket's capabilities.

A downloadable client JS is available in the socket.io website.
Hope this helps.
Comment: Hey thanks for the response. What if i wanna do this natively?
Comment: I believe This should work for you - http://code.google.com/p/unitt/wiki/UnittWebSocketClient
Comment: It does not need to live inside a webview , socket.io has api for java and other languages also

NodeJS + SocketIO pushing to Mobile App


Quantum: Define superposition as linear combination of orthonormal basis

Question: I'm testing a code for define a superposition state using a percentage of both basis.
All seems to run well, when the linear percentage is real. But it fails when the percentage is complex parameter.
from cmath import sqrt
from typing import List, Tuple

# Standard basis |0>, |1> (Z axis)
zero_qubit = np.matrix([[1.+0.j], [0.+0.j]])
one_qubit = np.matrix([[0.+0.j], [1.+0.j]])
standard_basis: Tuple[np.matrix] = (zero_qubit, one_qubit)

def superposition(
        percentage: float = 100.0,
        basis: Tuple[np.matrix] = (zero_qubit, one_qubit)):

    p=sqrt(percentage/100)
    q=sqrt(1-p*p)

    q1 = p*basis[0]+q*basis[1]
    q2 = p*basis[0]-q*basis[1]
    q3 = -p*basis[0]+q*basis[1]
    q4 = -p*basis[0]-q*basis[1]
    return q1, q2, q3, q4

# This works
q1,q2,q3,q4 = superposition(50,standard_basis)

print(q1)
print(q2)
print(q3)
print(q4)

# This generate weird values
q1,q2,q3,q4 = superposition(50j,standard_basis)

print(q1)
print(q2)
print(q3)
print(q4)

Answer: Answering my own question.
The superposition has to consider modules of coeficients (not the coeficient themselves).
So, my current code looks like
from math import sqrt
from typing import List, Tuple

# https://en.wikipedia.org/wiki/Quantum_superposition
def superposition(
        alfa: complex = sqrt(.5)+0.j,
        basis: Tuple[np.matrix] = (zero_qubit, one_qubit)):

    assert abs(alfa)<=1.0,"Module of assertion coef has to be lower or equal 1"

    if abs(alfa) >= 0.9999999:
        beta: complex = 0.+0.j
    elif abs(alfa) <=0.0000001:
        beta: complex = 1.+0.j
    else:
        alfa_module=abs(alfa)
        beta_module=sqrt(1-alfa_module**2)
        beta: complex=(beta_module/alfa_module)*(alfa.conjugate())
        assert abs(abs(beta)-beta_module)<0.0000001,"Internal error calculating modules"

    q1 = alfa*basis[0]+beta*basis[1]
    q2 = alfa*basis[0]+(-beta)*basis[1]
    q3 = (-alfa)*basis[0]+beta*basis[1]
    q4 = (-alfa)*basis[0]+(-beta)*basis[1]
    print(get_bloch_coordinates(q1))
    print(get_bloch_coordinates(q2))
    print(get_bloch_coordinates(q3))
    print(get_bloch_coordinates(q4))
    return q1, q2, q3, q4


Join específico entre tabelas

Question: Tenho duas tabelas
clientes

id
razao_social

1
empresa_1

2
empresa_2

e tarefas

id
id_cliente
tarefas
competencia

1
1
'101'
'032021'

2
1
'102'
'032021'

3
2
'101'
'032021'

Quando eu faço um join entre essas tabelas, obtenho um resultado correto, mas NÃO é o que eu estou procurando:
select c.razao_social , s.tarefas , s.competencia
from clientes c
join tarefas s on c.id = s.id_cliente
 where s.competencia = '032021'
 order by s.id_cliente;

Resultado obtido:

razao_social
tarefas
competencia

empresa_1
'101'
'032021'

empresa_1
'102'
'032021'

empresa_2
'101'
'032021'

Resultado que eu gostaria de obter:

razao_social
tarefas
competencia

empresa_1
'101'
'032021'

empresa_1
'102'
'032021'

empresa_2
'101'
'032021'

empresa_2
null ou vazio
'032021'

(ou qualquer outra coisa que indique que a tarefa '102' não foi feita pra empresa_2)
Existe alguma consulta que me ajude a gerar essa tabela resultado? Eu posso (e estou) a usar a linguagem de programação pra corrigir essa "linha faltante", mas queria saber se tem outro jeito, a nível de consulta SQL.
Testado: aplicar left join ou right join foram insuficientes pra fazer o que eu quero.
Comment: Relacionado: [Qual é a diferença entre INNER JOIN e OUTER JOIN?](https://pt.stackoverflow.com/q/6441/3774)
Comment: é difícil fazer com um simples query isso, pq teu modelo não obriga que uma tarefa seja feita por mais de um cliente
Answer: Você pode utilizar consultas aninhadas, seguindo os dois passos seguintes:
Primeiro: Deve-se fazer uma consulta que resulte em um conjunto preliminar que chamarei de  base das informações desejadas;
Segundo: Left Join com as tabelas que foram utilizadas para construir a base.
Primeiro passo - Obter tabela base:
select distinct id_cliente, t2.tarefa, t.competencia  from tarefas t,
    (select distinct tarefas as tarefa, competencia  from tarefas) t2
      where t.competencia = t2.competencia
        and t.competencia = '032021'
      order by id_cliente, t2.tarefa

Resultado - Tabela base:

id_cliente
tarefa
competencia

1
101
032021

1
102
032021

2
101
032021

2
102
032021

Desta forma obtemos todos os clientes combinado com todas as tarefas e o campo competencia.
Segundo passo: Usar a tabela base com Left Join:
Tendo obtido a tabela base das combinações, agora basta fazer o Left Join, vejamos:
select c.razao_social, t3.tarefas, base.competencia from (
    select distinct id_cliente, t2.tarefa, t.competencia  from tarefas t,
        (select distinct tarefas as tarefa, competencia  from tarefas) t2
     where t.competencia = t2.competencia
       and t.competencia = '032021'
     order by id_cliente, t2.tarefa
) base left join clientes c on base.id_cliente = c.id
       left join tarefas t3 on base.id_cliente = t3.id_cliente
                           and base.tarefa = t3.tarefas
                           and base.competencia = t3.competencia

Resultado obtido:

razao_social
tarefas
competencia

empresa_1
101
032021

empresa_1
102
032021

empresa_2
101
032021

empresa_2
[NULL]
032021

Desta forma é possível obter o resultado desejado.
Comment: Vi agora pouco sua postagem no meta sobre negativos. Não tenho muito como elaborar agora (e nem seria aqui na resposta), mas uma sugestão seria evitar postagens cuja resposta seja específica para o autor, este não é o objetivo do site. Tanto perguntas quanto respostas que fujam do [repositório coletivo de conhecimento](https://pt.meta.stackoverflow.com/q/7256/70), tendem a ter uma recepção menos favorável do que perguntas e respostas canônicas (a pergunta aqui até está melhor que a média, mas provavelmente é duplicata, importante verificar. Meu comentário não é restrito a esta pergunta aqui).

Join específico entre tabelas


Do I need to EQ frequencies before layering or after?

Question: I want to create kick-samples, snare-samples, etc... by layering recorded samples (e.g. 909-Bass-Drum + click + crunch). Also I want to cutoff frequencies to get suitable samples for the mix. I use the EQ-Eight in Ableton to do this, but this is not relevant for my question.
My Question:
Do I need to layer and merge the raw samples into a single sample first before I cut the frequencies away?

Or do I need to cut off the frequencies of each sample before I merge them into a single sample?
Comment: Is the signal path on the 2nd image correct? Are you only going to be EQing the lows on sample 1, mids on 2 etc? The difference is significant.
Comment: @Tetsujin: I have updated the images.
Answer: Assuming each of those EQ diagrams is a band-pass filter, eliminating the frequencies outside the permitted band, then to EQ all after you comp the sample will affect the entire combination sample, so you will be allowing a little of the mid & high through from the low sample, & the same for the other two.
If you apply your EQ individually to each before you comp, then you will effectively eliminate all frequencies above 150Hz [allowing for your slope but no matter] from the low, everything outside 120Hz to 1kHz from the 2nd sample & so on.
Neither of these methods is right or wrong, but the sonic result will be different.
Your ears will have to tell you which they prefer.