Clickhouse altering materialized view's select

Question: I have following setup:
CREATE TABLE IF NOT EXISTS request_income_buffer (
    timestamp UInt64,
    timestamp_micro Float32,
    traceId Int64,
    host String,
    type String,
    service String,
    message String,
    caller String,
    context String
) ENGINE = Kafka('kafka:9092', 'request_income', 'group', 'JSONEachRow');

CREATE MATERIALIZED VIEW IF NOT EXISTS request_income
ENGINE = MergeTree(date, microtime, 8192) AS
    SELECT
        toDate(toDateTime(timestamp)) AS `date`,
        toDateTime(timestamp) as `date_time`,
        timestamp,
        timestamp_micro AS `microtime`,
        traceId,
        host,
        type,
        service,
        message,
        caller,
        context
    FROM
        request_income_buffer;

I want to add new column, ex. ip to my request_income table.
According to docs in order to do so I will need to follow next steps:

Detach view to stop receiving messages from Kafka.

DETACH TABLE request_income;

Drop table that streams data from Kafka since Kafka engine doesn't support ALTER queries.

DROP TABLE request_income_buffer

Recreate table that streams data from Kafka with new field.

CREATE TABLE IF NOT EXISTS request_income_buffer (
  timestamp UInt64,
  timestamp_micro Float32,
  traceId Int64,
  host String,
  ip String,
  type String,
  service String,
  message String,
  caller String,
  context String
  ) ENGINE = Kafka('kafka:9092', 'request_income', 'group', 'JSONEachRow');

According to this post update .inner table of the detached materialized view

ALTER TABLE `.inner.request_income` ADD COLUMN ip String AFTER host;

According to post from above update view's select query
Attach view

ATTACH TABLE request_income

Question is how to update view's select query?
Answer: So it appears the way to update materialized view's select query is as follows:

Get path to views metadata

SELECT metadata_path FROM system.tables WHERE name = 'request_income';

Use your favorite text editor to modify view's sql. In my case edited sql will look like

ATTACH MATERIALIZED VIEW request_income (
      date Date,
      date_time DateTime,
      timestamp UInt64,
      microtime Float32,
      traceId Int64,
      host String,
      ip String,
      type String,
      service String,
      message String,
      caller String,
      context String ) ENGINE = MergeTree(date, microtime, 8192) AS SELECT
      toDate(toDateTime(timestamp)) AS date,
      toDateTime(timestamp) AS date_time,
      timestamp,
      timestamp_micro AS microtime,
      traceId,
      host,
      ip,
      type,
      service,
      message,
      caller,
      context FROM default.request_income_buffer

Attach modified view back

ATTACH TABLE request_income;
Comment: How would this be influenced if the tables are of the `ReplicatedMergeTree` family?
Answer: Try this out:

DETACH TABLE request_income;
ALTER TABLE `.inner.request_income` ADD COLUMN ip String AFTER host;

ATTACH MATERIALIZED VIEW request_income
ENGINE = MergeTree(date, microtime, 8192) AS
 SELECT
     toDate(toDateTime(timestamp)) AS `date`,
     toDateTime(timestamp) as `date_time`,
     timestamp,
     timestamp_micro AS `microtime`,
     traceId,
     host,
     ip,
     type,
     service,
     message,
     caller,
     context
 FROM
     request_income_buffer;

Comment: I'm doing this, but reattached materialized view does not contain the new column. What's wrong?
Comment: It looks like `TO` materialized views (with explicit target table) work differently. I see ATTACH for them work incorrectly. However, for them you can just DROP and then CREATE them again.


Generating multivariate random vectors Excel

Question: I want generate a m=8 numbers of n-dimensional vectors, each being multivariate normal with variance  $\sigma_m^2$.
There is an excel macro for this, at http://www.quantcode.com/modules/mydownloads/singlefile.php?lid=470
Putting a <code>=normsinv(rand())</code> in each cell, and then scaling these values to get the correct stdev is not the same thing is it?
Answer: That depends. You mentioned that you want each coordinate of each multivariate normal variate to have a certain variance, namely $σ^2_m$, but you didn't say anything about the covariance between the coordinates.

If you want the coordinates to be uncorrelated (i.e., the covariance matrix is a diagonal matrix), then the method you described, which means drawing from a univariate normal distribution one at at time, is indeed the same as drawing from a multivariate normal distribution. (Why? Because if two random variables are multivariate normally distributed and uncorrelated, then they're independent.)
But if at least one pair of coordinates should have nonzero covariance, then the method you described can't account for this covariance.
Comment: I do want to have a non-diagonal covariance matrix. In fact, I have historical data on their return series, which could give me an idea of how their covariances have been in the past. I took the covariance for two years of data, did a rolling window for 6 years (i.e. rolled from year 0-2 to year 4-6) and found that according to this measure they follow each other quite well. Because they are all metals.
Comment: Sorry, I took a rolling stdev() over time for each asset, not cov().
Comment: @user1603548 Okay then, you definitely don't want to just use `=normsinv(rand())` and scale, since that wouldn't use the off-diagonal entries of the covariance matrix.


Valor entre formulários Asp.Net C#

Question: Boa Tarde Pessoal
Estou pegando o valor de uma gridview até ai tudo bem:
gridCadastro.GetRowValues(gridCadastro.GetFocusedRowIndex(), 'id_cliente', OnGetRowValues);

Agora preciso pegar esse valor e passar para um ASPxButton de uma metro.master, porém não consegui via
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

Comment: você quer passa para outro form?
Comment: Por favor, explica melhor isso.
Comment: Bom vamos la.. Tenho uma aplicação onde um arquivo metro.master recebe os botões padrões.
E em outro lado tenho um formulário com uma gridview.
A ideia é quando o usuário clicar na gridview, o id da row seja passado para metro.master como parâmetro para eventuais funções.
Answer: Na sua Masterpage, coloque um campo Hiddenfield com id que desejar.
A partir da sua tela, pra use:
(Masterpage.findcontrol("Id_do_hiddenfield_da_master_page") as HiddenField).value = "VALOR";

Comment: Tentei como informado e retornou o seguinte erro:

        Syntax error, unrecognized expression: unsupported pseudo: HiddenField
Comment: poderia me explicar melhor sua ideia....sou novo no asp.net c#, e não intendi

Valor entre formulários Asp.Net C#


artifactory license manager with bamboo

Question: I'm having trouble finding anything definitive in the artifactory documentation.
With Bamboo, using the Artifactory plugin, I want to enable license checks (as shown in https://www.jfrog.com/confluence/display/RTF6X/License+Control )
However using generic deployment, I'm not finding any option for license checks.
If anyone can give me a pointer on how to enable the license checks properly for release builds etc it would be appreciated.  Only real documentation I can find on the latest version keeps pushing x-ray which is overkill for my requirements.
Answer: The license control capability was deprecated in the Artifactory 7.0 release and was replaced, as you noted, by the Xray license compliance which provides richer information and support for additional package types.

artifactory license manager with bamboo


Como autenticar múltiplos grupos de usuários no Laravel 5?

Question: Estou tentando criar um ambiente no laravel 5 onde existe a área de acesso de clientes (Frente da Loja) e a área de administração de páginas, produtos, etc. (CMS), porém o problema é que não estou conseguindo encontrar uma forma de dividir as sessões, por exemplo: quando eu autentico uma conta como administrador através da área de login do CMS, essa mesma sessão é válida para todo o site, e portanto o administrador pode acessar as urls que só usuários autenticados poderiam, como o Painel de usuário, por exemplo, e vice versa.
<code>// CMS ADMINISTAÇÃO
Route::group(array('prefix' => '/admin', 'middleware' => ['auth', 'roles'], 'roles' => 'administrator'), function()
{
    // INDEX
    Route::any('/', array('as' => 'admin', 'uses' => 'Admin\AdminController@Index'));
});

// PAINEL DO USUÁRIO
Route::group(array('middleware' => ['auth', 'roles'], 'roles' => 'client', 'prefix' => '/panel',), function(){
    Route::get('/', array('as' => 'panel', 'uses' => 'PanelController@Index'));
});
</code>
Para isso eu implementes este sistema de roles, que através dos routes identifica se o usuário possui permissão suficiente para acessar aquela área, o problema é que depois de logado a sessão funcionaria em qualquer lugar, e mesmo que eu utiliza-se algum filtro ainda assim não seria permitido eu ter uma conta de administrador logado no CMS e outra conta de usuário logado no site normal, a não ser que eu dividisse a aplicação em 2, o que eu não gostaria de fazer.
Em resumo, o que eu quero é que ambas as sessões possam existir ao mesmo tempo, sem que uma possa acessar o que é restrito a outra.
Como posso resolver isso?
Comment: http://pt.stackoverflow.com/questions/170252/como-posso-diferenciar-autentica%C3%A7%C3%B5es-no-laravel-exemplo-administrador-e-usu%C3%A1ri[acho que isso resolveria seu problema ][1]
Answer: Uma solução que vejo para esta situação seria criar um middleware de autenticação para usuários, e outro para administradores.
Comment: Olá, Leandro! Bem-vindo ao SOpt. Recomendo fazer um [tour](http://pt.stackoverflow.com/tour) pelo site para conhecer as melhores formas de resposta. Sendo assim, poderia detalhar melhor sua ideia para ajudar o colega?


To make a plan for my first MySQL project

Question: I need to complete the plan of a ask-a-question site for my uni. in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.
Questions about the project which do not fit here

to make efficient tables
to improve a relation figure
to improve a ERD diagram
to SHA1-hash you password in a MySQL database by Python
to have a revision history for the questions
to get the right way in designing databases
to get primary and foreign keys right in ERD
to understand login -variable in cookies/URL
to get info about my Uni's servers
to improve SQL -queries
to write SQL queries in DDL correctly
to prevent to use of duplicate tags in a question
to improve SQL queries in DDL
to have no duplicate tags in a table
to separate answers in a databse

My uni. offers little support for tools which I selected:
Tools in building the backend

Python in building the database schema??? (I am not sure which components I can build by Python)
MySQL to store data
I am not sure which tool to use in building login and logout -system. They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.

Tools in building the frontend

Django (if we can use MySQL in Django)

Tools for Planning

Google Docs' Spreadsheet for illustrating the usecases
TopCoder UML Tool to show primary keys and other relations in the database

Tools for coding

Vim, Screen, Zsh, OS X's Visor: my dot-files
EasyEclipse for Python (only if I get a difficult error message)

My focus in the project: I aim to build a database system only for users and moderators such that I only provide the following features

to allow user to add to a database such that I neutralize the input (I know that there is some tool for that, but I am not sure about its name.)
to arrange questions by time
to arrange questions by name
to arrange questions by their subject
to allow users to remove their questions
to send an email to user that the question was successfully asked

Things about which I am uncertain

how to integrate the login -system to the database such that the user sees only his data that is his username when he logins successfully, similarly as in Joomla
Which components should I not build by Python when I use MySQL for databases?
My uni. does not give me hardware support for the project. This suggests me that I will be better of in using a host which is specialized in my project. I used Djangohosting.ch the last month, and by their toos, I got started. Which host would you use such that I can show the final product to my Uni.?

This is my first official database project so my plan apparently has shortcomings, since there must be tools which I do not know. Please, pinpoint any one of them.
Comment: There is a LOT of material here to cover, do you have any specific questions?
Comment: You should post another question -- "What's the best way to explain to my boss/professor that there's no way on the planet I will finish this project within the deadline?"
Comment: This is an incredible amount of work for a week. Are you doing this by yourself or is it part of a team project? It's hard for us to point out things that you don't know, since it's impossible for you to list everything you know.
Comment: @Janie: Please, see the parts about which I am uncertain at the moment. --- @Greg: I am doing everything by myself. This thread acts as a roadmap for me. I will open new questions when I see things clearly such that I post the links here.
Comment: should be community wiki
Comment: I'd be interesting to know when the project was set; it may have been set weeks, even months ago, rather than last week, in which case the "No way do you have enough time" comments don't apply
Comment: @blowdart: The project was set up six days ago.
Answer: First, this is all a lot to work with in a week. But here it goes.
Tools for the backend:

SQLAlchemy - This is an ORM toolkit that is plenty powerful for most smaller tasks when using a MySQL database built with Python. To my knowledge, it is the best  for this job. http://www.sqlalchemy.org/
Django - "...is a high-level Python Web framework..." This might be better for rapid development of a site with login/logout methods included and a minimal learning curve for someone with web/Python understanding.

Tools in building the frontend:
If you already plan on using Django for the backend, I'd recommend using it for the frontend as well.
Things about which you are uncertain:

The users can be specified in MySQL and their permissions can be set accordingly.
From some of the requirements you listed, most of these sound like they can be contained within the capabilities of Django.
Comment: Thank you for your answer! I did not know that I can use SQLAlchemy for databases, while Django in building up the login -system.
Answer: Use the django Model to create the Object-Relational Mapping (ORM) that injects and retrieve your data.
For login/logout, django has an AuthenticationMiddleware feature you can probably use, although I am not sure if you can solve your problem with it.
In any case, your project, with the given deadlines is totally unrealistic. Be prepared to miss the deadline, and hear the whooshing sound they do as they fly by.
Comment: an ORM is a layer that decomposes an object and store it into a relational database (and viceversa: recover from a relational and recreate the object). django already has an ORM which creates the SQL tables and do all the SQL for you. If you want to reinvent the wheel and create your own ORM so they can see your SQL-fu at work you are free to do so, but it's boring.
Comment: Can I use ORM such that I need to use MySQL too? --- I need to prove my skills in MySQL for them.
Answer: I think this can all be accomplished in django. See the official tutorial.
Answer: I'm guessing that you wouldn't be allowed to use an ORM, since you call this a "MySQL project".
If this is an incorrect assumption, I'd agree with N Arnold's recommendation of using Django. Rather than using SQLAlchemy, I think you'd find that Django's ORM is good enough (especially if you use v1.1rc or trunk).
Like some of the comments to your initial question, this does seem like a large amount of work if you have to learn a framework as well as produce a project in it. On the other hand, someone who knew Django could crack out the base of such a project in a day or two.
Comment: I need to some database system from Oracle/PostGre/MySQL. I aim to use MySQL because it is the one which I have used before. --- @ **Do you mean that Django does not uses MySQL as its database system? --- Is ORM Python's database system built into the language?**
Comment: The Django ORM can use a multitude of database engines, one of which is MySQL. Django uses the Python database connector for the db engine you want to use.

At the start of the tutorial it explains how to set up your Django project for a specific database: http://docs.djangoproject.com/en/dev/intro/tutorial01/#database-setup
Answer: You can build your database with MySQL, go read the official docs. It really doesn't matter what language you use to program a front-end whether it be a website, command line interface, gui interface, most languages handle this pretty well but it seems you're set on building a web application and this can be achieved very easily with Django, which is a Python web framework.
Doing what I've told you, if you keep at it you'll be done in under 16 hours. Good luck.
Btw. your project seems to focus on a lot of irrelevant things. You're creating a database application, unless you already know CSS and JQuery, why don't you just create it in simple unstyled XHTML; that way you have less work to do!
Comment: Thank you for pointing them out! --- I removed the languages which I already know well in my plan.
Answer: Ehh, what is the purpose of this development? To build a real production-ready system, or to pass an exam by building a mini-project that will never see real use?
If your purpose is to pass an exam, then build what your teachers like to see. Take you cues from the material they have been using in classes, and also ask them outright what they think is good.
If you want to build a production system, then Django would be a great choice. Respectfully however, given the limited understanding of Django you demonstrate, you will most likely not complete the project in time.
Django has pre-existing functionality for:

Building the database schema. The DB tables will be buildt when you define your model classes in Django and run manage.py syncdb.
A login system. Django has a login system with cookies etc build into it; and several 3rd party Django addons extend this system.
Encrypting passwords in the database, Django uses SHA-1 with a salt if memory serves.

Thus your teachers could legitimately say that you haven't demonstrated your own skills at modeling a DB schema, you have just used Djangos pre-existing functionality. Will they be OK with this, or will they fail you on this exam?
If you need to demonstrate understanding of the core concepts, perhaps you would be better off by staying with a system you know well already, instead of mixing in Django as another complexity, another thing you'll need to learn in very little time...
Comment: I agree with you. I will not use Django in this project.
Comment: If you agree, is this answer then your chosen, accepted answer? :-)
Answer: Django can use many different database backends one of which is MySQL, to help support this it provides an ORM (Object Relational Mapping) layer which abstracts away the SQL code and storage medium and allows you to write Models containing storage fields and logic as necessary without worrying about how they are stored in the persistence layer.
Django also contains basic authentication (login/logout) functionality and has the concept of users and admin-users built into it.
As an example using the built in user models and the ORM would allow you to get all questions asked by a user with something like the following code:
<code>Question.objects.all.filter(asker=request.user)
</code>
Where Questions is the model you have defined to hold your questions (with a field called 'asker' which is a foreign key to the user) and the request.user is the user logged into the website.
I suggest you read up on the Django ORM.
As far as hosting it, you could use Ubuntu on a desktop computer, or if you need an external  host then would recommend Webfaction or Djangohosting.ch as two of the most 'Django Friendly' Hosts.
Answer: About Moderators and Users
What is the difference between moderators and users? Moderators can modify text, but how? Are they planning you to practise permissions, fs or some open-source system to differentiate users from moderators?
Very odd that they do not allow Google products, but they allow open-source. Interestingly, USFCA encourages Google products in similar projects. Perhaps, there are some users, who could help you with userspaces.
Good luck!
Answer: They give us only this example of the web app. The code is not useful for me, since the code is in Finnish and it is written in PHP. It is also not open-source such that I cannot paste the code here.
I would like to see similar examples in Python. Please, put links to the comments.


Difference of two symmetric, positive semidefinite matrices

Question: Let $A$ and $B$ be $q \times p$ matrices of rank $q < p$.
Moreover, $D_{1}$ and $D_{2}$ are $p \times p$ diagonal matrices with all diagonal elements are strictly positive.
In this case, can
$$
D_{1} - A^{\operatorname{T}}A = D_{2} - B^{\operatorname{T}}B
$$
guarantee $D_{1} = D_{2}$ and $A = B$?
I think this is not true, but finding counter example is quite hard to me. I am also curious about conditions which make the above equation valid.
Thank you for your answer in advance.
Comment: ...but if $A = B$, then $A^\mathsf{T} A - B^\mathsf{T} B = A^\mathsf{T} A - A^\mathsf{T} A = 0 \neq D$. Typo?
Comment: Thank you for your comment! I've edited the question.
Answer: First of all, it is not true that $A^TA = B^TB$ implies that $A = B$. So, let's stick to the weaker condition of
$$
D_1 - A^TA = D_2 - B^TB \implies D_1 = D_2, \quad A^TA = B^TB.
$$
Even so, the statement does not hold. Take $p=1,q=2,$ and
$$
D_1 = \pmatrix{2&0\\0&1}, \quad D_2 = \pmatrix{1&0\\0&2}, \quad A = \pmatrix{1&0}, \quad B = \pmatrix{0&1}.
$$
Comment: I've corrected the question! Sorry to confuse you :)
Comment: See my latest edit.
Answer: This is not true: take
$$D_1 = D_2 = \begin{bmatrix} 5 & 0 & 0 \\ 0 & 5 & 0 \\ 0 & 0&5\end{bmatrix}, ~ A = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0\end{bmatrix}, ~ B = -A$$
As seen, this equation almost never implies that $A = B$, because $A = -B$ will satisfy the equation too. Even discounting for this trivial counterexample, and even if $D_1 = D_2$, it is not guaranteed that $A = B$. The relation
$$M = A ^T A = B^T B$$
is far from implying $A = B$. In fact, any spectral decomposition $Q D Q^T$ of $M$ can be used to find a matrix $C$ such that $C^T C = M$. Indeed, any $C = Q \sqrt{D}$ (recall $\sqrt{D}$ is well-defined as $M$ is positive semi-definite) will fit the bill. The spectral decomposition is not unique, and hence neither is $A$ or $B$.
In a nutshell: this equation doesn't come close to implying $A = B$, much less $D_1 = D_2$ and $A = B$.


Solving $f(x+f(y)) = f(x) + y$

Question: I found this problem in an old book of mine. The question asks to find all the functions $f: \mathbb Q \to \mathbb R$ which satisfy $f(x+f(y)) = f(x) + y$ for all rational numbers $x,y$. Also I am unsure what $f: \mathbb Q \to \mathbb R$ means exactly when compared to $f: \mathbb R \to \mathbb R$
I have been experimenting with this problem and the only two functions I could find were $f(x) = x$ or $f(x) = -x$. Although these functions seem to be the only working ones (purely based on guess and check), I cannot seem to find a proof.
Comment: Does the condition assume that $f(y)$ is not rational? That is, when $f(y)$ is not rational, it does not make sense to say that $f(x + f(y)) = f(x) + y$.
Comment: @Servaes Thanks, I came to the same conclusion. The reason I was asking is that it is possible the condition as given is missing some modifiers.
Comment: @JacobMaibach If $f:\ \Bbb{Q}\ \longrightarrow\ \Bbb{R}$ is a function that satisfies
$$f(x+f(y))=f(x)+y,$$
for all $x,y\in\Bbb{Q}$, then in particular $x+f(y)$ is in the domain of $f$ for all $x,y\in\Bbb{Q}$, which implies that $f(y)\in\Bbb{Q}$ for all $y\in\Bbb{Q}$.
Answer: As Servaes pointed out in a comment, we see that $f(x)\in \mathbb{Q}$ for all $x$.

Set $x=0$ and you get $f(f(y)) =f(0)+y$ so $f$ is injective.
Let $y=0$ you get $f(x+f(0))=f(x)$ and since $f$ is injective we have $x+f(0)=x$  so $f(0)=0$ and $f(f(y))=y$ for all $y$.
Let $y=f(t)$ then $f(x+t) = f(x)+f(t)$, so $f$ is solution of Cauchy FE and thus $f(x)=ax$ for some $a$.
Plug that in original equation to get $a=\pm 1$.

To solve $f: \mathbb R \to \mathbb R$ you need some aditional asumption for $f$. You can not say $f(x)=ax$ immediately.
Comment: Regarding the first line, what about if $f(y)$ is not rational?
Comment: If $f(y)$ is not rational, then the statement does not make sense so you can't claim $f(f(y)) = y$ for all $y$.
Answer: In general, $f : A \to B$ means that the domain of $f$ is $A$ and that for all $a \in A$, $f(a) \in B$. In this case, $f : \mathbb{Q} \to \mathbb{R}$ means that $f(x)$ only needs to be defined for $x$ a rational number, and $f(x)$ is always a real number.
In this case, because $f(x + f(y))$ is defined for all $y$, it must be the case that $x + f(y) \in \mathbb{Q}$ for all $y$. In particular, $0 + f(y) = f(y) \in \mathbb{Q}$ for all $y$. So we're looking for some $f : \mathbb{Q} \to \mathbb{Q}$ satisfying the above.
Let's start by plugging in $x = 0$. We have $f(f(y)) = f(0) + y$. This tells us that $f$ is injective, since if $f(a) = f(b)$, then $f(0) + a = f(f(a)) = f(f(b)) = f(0) + b$ and hence $a = b$.
Now, let's plug in $y = 0$ into $f(f(y)) = f(0) + y$. This gives us $f(f(0)) = f(0)$. Since $f$ is injective, we have $f(0) = 0$.
So we have $f(f(y)) = y$. Then $f$ is a bijection, and $f$ is its own inverse.
Now let's plug in $y = f(z)$. Then we see that $f(x + z) = f(x + f(f(z))) = f(x) + f(z)$.
Now all functions $f : A \to B$ satisfying $f(x + z) = f(x) + f(z)$ for all $x, z$ are linear whenever $A, B$ are $\mathbb{Q}$-vector spaces. So $f$ must be a linear function.
The only linear functions $\mathbb{Q} \to \mathbb{Q}$ are of the form $f(x) = ax$. For such a function, we must have $f(x + f(y)) = f(x) + y$; that is, we must have $a(x + ay) = ax + y$. So we must have $a^2 = 1$.
So the only functions that could possibly work are $f(x) = x$ and $f(x) = -x$. And these functions do work.
Answer: There is a small but tricky subtlety to this problem needs to be resolved first, which is the question of whether $f(y)$ can be irrational. This is an issue because if it is irrational, then for any rational $x$, the expression $x + f(y)$ is irrational and so
$f(x + f(y))$ is not defined. Assuming the condition
$$ f(x + f(y)) = f(x) + y $$
really holds for all rational $x, y$, it must therefore be the case that $f(y)$ is always rational.
Then we can proceed by considering particular $x, y$, especially zero. That is, taking $x = 0$, we get
$$ f(0 + f(y)) = f(0) + y $$
which implies that
$$ f(f(y)) = f(0) + y. $$
Similarly, considering $y = 0$ gives
$$ f(x + f(0)) = f(x) . $$
Edit: This is essentially the same steps as Mark's answer which was posted moments before mine, but I figure I'll leave it if only for a slightly different perspective.

Solving $f(x+f(y)) = f(x) + y$


how to create a trigger to remove lat values that are almost duplicates

Question: I have a table of lat, lng and deleteflag. Its MariaDB 5.3...
If someone inserts a value "close to existing items" I want it rejected or the deleteflag set.
I thought I could do it with a trigger??  Is this possible in mysql which seems has only limited trigger capabilities??

CREATE TABLE `test` (
  `lat` decimal(10,8) NOT NULL,
  `deleted` decimal(11,0) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TRIGGER mytrigger
BEFORE INSERT
ON test FOR EACH ROW
BEGIN
    DECLARE distance INT;

    SELECT COUNT(*)
    INTO distance
    FROM test
    WHERE
    lat between new.lat-.1 and new.lat+.1
    ;

    IF distance > 0 THEN
        UPDATE test
        SET new.deleted=1;
    END IF;
END

It works.
lat 39.2 39.5 39.8 40.0 40.2 40.4 40.6 40.8 41.0
But throws this error on closedups/dups.
#1442 - Can't update table 'test' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Q: How to silence that error??
Comment: Which one - rejected or delete flag? Define "close" is something approaching a mathematical sense. Why MyISAM? What mysql server version? What is your table definition `SHOW CREATE TABLE tablename`?
Comment: What makes you say MySQL has limited trigger capabilities?
Comment: You can build the logic into the INSERT itself
Comment: #strawberry  I want to use a trigger because I have INSERTS coming in from varried places. The trigger protects the data from any source.
Comment: @danblack .I show the distance calculation I use. The lat,lng are indexed so "between" works.
Answer: You almost have it and the restriction is that triggers can't modify the table on which the trigger is has been applied (avoid many cases of cascading infinite recursion failures).
Instead of:
IF distance > 0 THEN
    UPDATE test
    SET new.deleted=1;
END IF;

Use:
IF distance > 0 THEN
    SET new.deleted=1;
END IF;

When the trigger completes the NEW.x values are used.
Ref; syntax of triggers per manual
Other notes;

unclear why deleted is a decimal.
MariaDB-5.3 - probably time you updated to a supported version. When you do, you can use Innodb instead of MyISAM.

If only a boolean is needed for deletion:
SELECT 1
INTO distance
FROM test
WHERE
lat between new.lat-.1 and new.lat+.1
LIMIT 1
;


Is there a difference between controlling for population size directly vs. putting variables in per capita terms?

Question: I want to look at the impact of a number of factors (e.g nutrition, alcohol sales, GDP, etc.) on mortality. I have a dataset with 10-30 years of data on these variables aggregated at the state level. (i.e. I'm looking at the impact of total state-wide alcohol sales in a given year on total deaths in that state in that year). Obviously, population size is a likely omitted variable if I don't include it. However, I am wondering whether I should include it by transforming variables to their per-capita form or whether I should control for population directly.
It seems that creating per capita variables is the conventional thing to do, but it seems to me that just adding in population size as a control is simpler and it allows for population size to have its own unique effect on the dependent variable. For example, in this case, we might think that states with larger populations, all else being equal, have more deaths because it is harder to organize the healthcare system efficiently to meet the demands of a large population.
What should I do here? Are these two approaches functionally equivalent?
Comment: The following is relevant: https://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353
Comment: Let $Y_{ij}$ be the number of death at state $i$ in year $j$, $P_{ij}$ be the corresponding # of people, $X_{ij}$ be a vector of other covariates, such as GDP. Then fit a Poisson regression model with random state specific intercept:
$$Y_{ij} \sim Poisson(\lambda_{ij}P_{ij})$$
$$\lambda_{ij} = exp(X_{ij}\beta + \epsilon_i)$$
$$\epsilon_{ij}\sim N(0,\sigma)$$
In most software, $\log(P_{ij})$ is called as offset.
Answer: Its not that simple, at least not in a linear additive model. It also fundamentally depends on your dependent variable.
Take a simple example where the true Data Generating Process (DGP) a increase from 1 in a 1000 individuals with a certain condition to 2 in a 1000 is associated with a 10% increase in some variable of interest and there is no association between population size proper and your dependent variable. Take two states with resp. 10,000 and 100,000 inhabitants and resp. 20 and 40 individuals with a certain treatment.  You propose adding as regressors [20, 10,000] and [40, 100,000] whereas per capita regressors would have been 2 and 0.4. Your model will not accurately reflect the association you are looking for because the per capita ratio between the two observations is decreasing (2 versus 0.4) whereas in absolute terms it is increasing (20 versus 40). Therefore, the two approaches are clearly not equivalent. Which you prefer depends on your dependent variable and the relationship you are testing, but in an OLS framework variables are independent so adding the total population as one regressor doesn't mean the other regressor is scaled by such a variable - they are approached as independent numbers by the model. Note that if your dependent variable is a rate or per capita value, you generally would want your regressors to be the same (just think about the above situation).
There is no problem, however, adding both per capita ratios AND some population size indicator (probably best to take the natural log of the true population) - that seems to be the best approach in your case?
Hope this helps
Comment: Yes, exactly. In fact, you'd just be dividing the left and right hand side by a constant (e.g. 1,000). It just depends on what you're testing, and it would be a bad idea if you would e.g. have an absolute number as the dependent variable and a ratio as the independent! Given that it is 'just' adding a constant on both sides, adding the total population in the first or second versions, it is simply adding an additional regressor for the total state size into the equation. It doesn't functionally change the interpretation of the other regressor, except it being conditional on something else then
Comment: "Your model will not accurately reflect the association you are looking for because the per capita ratio between the two observations is decreasing (2 versus 0.4) whereas in absolute terms it is increasing (20 versus 40)." But wouldn't the model with population size as a control take into account the fact that the population sizes are different?
Comment: Again it depends on what you are looking for. In a model with just the per capita variable as a regressor, the interpretation of your coefficient will be the association between an increase of one per thousand on your dependent variable. In a model with population size and for example the actual number of people with some condition, the interpretation for the two coefficients is the association between a. one more person with a certain condition and b. between one more person living in your state and your dependent variable, conditional on one another. Clearly not the same, right?
Comment: I suppose they're not literally the same, but with the latter model, you're getting at the impact of one more person with a certain condition **holding population constant**, which is functionally very close, right? Like other the math of figuring out state-wide averages for variables, wouldn't we expect that the relationship between, say, per capita mortality and per capita alcohol sales would be very similar to the relationship between mortality and alcohol sales while controlling for population size?
Answer: I answered your more general question, Controlling for population size, using per capita or including a variable for population size with reference to this one. To address this more specific question:
No, they are not functionally equivalent. Controlling for alcohol sales per capita is controlling for sales rate. It is density of how much alcohol is being imbibed (or purchased for some other reason..?) per individual person.
If you control separately for alcohol sales and population, your regression is modeling, separately, the impact of alcohol sales AND the impact of population WITHOUT considering that the relation between the two is key.
If you control for alcohol sales per capita, your regression is modeling how much alcohol is purchased per person WITHOUT considering how much alcohol was purchased OR how many persons there are.
In short, when you say

Obviously, population size is a likely omitted variable if I don't include it. However, I am wondering whether I should include it by transforming variables to their per-capita form or whether I should control for population directly.

I think that the core of the misunderstanding becomes clear. The answer is that you can't "include it by transforming variables to their per-capita form," because per capita is not a form of the variables. It is created by the variables, but the information gleaned from the variables separately in a regression analysis is NOT simply absorbed into the per capita variable.


Hide "Your name" field in comment form from everyone except admin

Question: What I want to achieve is to hide the "Your name" field in comment form from all anonymous and authenticated users but visible to users with the admin role.
I was able to use CSS to hide the field, but it also hides from admin.
Please is there a way to selectively hide the field to anonymous and authenticated users but not to administrators?
Answer: function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  global $user;

  if ($user->uid != 1) {
    unset($form['author']['name']);
  }

}

Another way is, if your theme has a comment.tpl.php file, putting a condition to restrict authenticated and anonymous user.
<?php print $author; ?>

To limit this to a particular content type, you can create a separate comment template file for that content type.
Comment: Thank you. I used the first solution and it works! Please, is there a line to add to the code to limit this to a particular content type e.g article content type?
Answer: If you have more than one users having administrator role then you may use this snippet. Place this piece of code at the bottom of template.php of your current theme.
Note: Replace YOUR_THEMENAME with the name of your current theme and YOUR_FORM_ID_HERE with id of your form.
function YOUR_THEMENAME_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id){
    case 'YOUR_FORM_ID_HERE':
      global $user;
      if (!in_array('administrator', $user->roles)) {
          unset($form['author']['name']);
      }

    break;
  }
}

Comment: @seyi this solution is better as it will work for all the admin users, not just only one user with uid 1.


How to programatically submit an entityform?

Question: My use case:

Anonymous user submits information via an entityform.
The form data ($_POST) is cached and a modal dialog box displays with a login form.
The user authenticates, and the cached form data is retrieved and then submitted.

I've been able to do this with webforms, but I haven't been able to accomplish the same task for entityforms. I can get the form using the following code...
<?php
$entityform = entityform_empty_load('my_eform_type');
$form = entityform_form_wrapper($entityform);
?>

What I've had trouble with is creating a $form_state array with the correct structure and values from the cached $_POST that I can then pass to drupal_form_submit(). My entityform has image, date, and checkbox fields, so that adds to the complexity.
I've been able to manually create and save an entityform submission using the following code...
<?php
$values = array(
  'type' => 'my_eform_type',
  'uid' => $user->uid,
  'created' => time(),
  'changed' => time(),
  'language' => LANGUAGE_NONE,
);

// For brevity's sake, I don't show adding all the fields
// from the cached $_POST to the $values array.

$entityform = entityform_create($values);
$entityform->save();
?>

...but that doesn't provide the form validation and reload on error functionality. Errors such as the wrong size image being uploaded, which is caught during form submission.
When my entityform is submitted, there is also an entityform notification email sent and the user is redirected to the confirm page. I don't want those things to happen prior to the user authenticating.
There's some code in the d.o. handbook, but it doesn't talk about drupal_form_submit().
I'm using Entityform 1.1.
Answer: I don't think you can submit entityform using drupal_form_submit() as it's entity, not a standard form.
The best way is to save the entity as you did, but you are missing field_attach_submit which is necessary to perform operations on field data submitted by a form.
The syntax is:
field_attach_submit($entity_type, $entity, $form, &$form_state, $options = array())

Example based on given $form_state:
$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

// Copy top-level form values that are not for fields to entity properties,
// without changing existing entity properties that are not being edited by
// this form. Copying field values must be done using field_attach_submit().
$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);

Alternatively you can submit entity form by using entityform_save(), e.g.:
$form = new Entityform(array('type' = 'my_entitty_form', 'language' => LANGUAGE_NONE));
$form->field_entityform_1 = array(LANGUAGE_NONE => array(array('value' => 'field_1')));
$form->field_entityform_2 = array(LANGUAGE_NONE => array(array('value' => 'field_2' )));
$form->uid = 1; // this is the form id
entityform_save($form);

Source: sushantpaste's gist


Wpf open all windows when click any of window in taskbar

Question: In my wpf application, when user click on menu, a new window will open, and user click an item in that window, another window will open. And when these all window minimized the user, and click any of the window in taskbar, I need to open these three window.
When user click on any of the window, I want to open the three window.
Comment: Set the window state to Maximized for all the windows when one of them is maximized.
Answer: WindowState is a property on Window.
Subscribe to StateChanged event on the window.
this.StateChanged += MainWindow_StateChanged;

When this changes to Maximized for one of the windows, update the state for other windows as well.
this.WindowState = System.Windows.WindowState.Maximized;

Comment: It's simple savePopUp.owner=this;
Comment: When user click on any of the window in taskbar, I want to open the three window. WindowState.Maximized means the size of the window set to maximized, my requirement is not this.
Comment: Use windowstate normal.
Comment: Not working, when I click any of the window, only the corresponding window opening, not all windows opening.
Comment: Could you please show us some code that you've tried.
Comment: Title="Project"  Background="#2B2B37" WindowState="Normal" Width="1300" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" Height="650"
Comment: where have you subscribed to the StateChanged event? Please read the entire answer, now i have added the code too.
Comment: public Home()
        {
            InitializeComponent();
            vm = new HomeViewModel();
            this.DataContext = vm;
            this.StateChanged += new EventHandler(Window1_StateChanged);
        }
        void Window1_StateChanged(object sender, EventArgs e)
        {
            var project = new Project();
            project.WindowState = WindowState.Maximized;
            var savePopUp = new SavePopUp();
            savePopUp.WindowState = WindowState.Normal;
        }
Comment: Is this method called?
Comment: yes, I think the issue, when windows not minimized, just hide from screen, then the user click to taskbar icon, only the clicked window will open. That time this method not fired.
Comment: In that case, i think you should try making two windows the children of the first window.
Comment: That's great.. any sample


how to add an inline policy to allow s3:ListBucket for a certain User

Question: I'm trying to add this as an inline policy, with arn for user (principle) and arn for bucket (resource).

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::00000000:user/name"
            },
            "Action": "s3:ListBucket"
            "Resource": "arn:aws:s3:::bucket name"
        }
    ]
}

error: Unsupported Principal: The policy type IDENTITY_POLICY does not support the Principal element. Remove the Principal element
tried adding this snippet as an inline policy but I have to find another way due to error Unsupported Principal: The policy type IDENTITY_POLICY does not support the Principal element. Remove the Principal element
Comment: Where are you going to attach the policy?
Answer: Just remove the principal element.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:ListBucket"
            "Resource": "arn:aws:s3:::bucket name"
        }
    ]
}

Comment: if I remove principle I get a message ''This policy does not grant any permissions. To grant access, policies must have an action that has an applicable resource or condition. For details, choose Show remaining"
Answer: There are two places you might place such a policy:

Bucket Policy
Policy on an IAM User

If you are creating a Bucket Policy, it will require a Principal.
However, if you are wanting to assign rules to a specific IAM User, then it is better to create a policy on the IAM User themselves. When doing this, there should not be a Principal because this is inferred by the IAM User on which the policy is placed.
Answer: This should be working for you, just replace the user with correct AWS user.
{
  "Id": "Policy1673568063233",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1673568062150",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::bucket name",
      "Principal": {
        "AWS": [
          "arn:aws:iam::00000000:user/name"
        ]
      }
    }
  ]
}

AWS policy generator is always a great place for dealing with policy generation
https://awspolicygen.s3.amazonaws.com/policygen.html
Comment: have to make sure principle element is removed...
Comment: what is SID here?
Comment: SID is an optional field that is used as a description for the Policy statement. It can hold alphanumeric values


Showing $\frac{k + a}{k + b} > \frac{a}{b}$ with $a > b$ and $a, b, k \in \mathbb{R^+}$

Question: Given the 2 terms
$$ \frac{k + a}{k + b}$$
and $$\frac{a}{b}$$
with $a, b, k \in \mathbb{R^+}$ and $a > b$
I want to show, that the first term is always bigger than the second one.
My try
$$
  \frac{k + a}{k + b}  > \frac{a}{b} \\
  \frac{k + b + (a - b)}{k + b} > \frac{b + (a - b)}{b} \\
  1 + \frac{a - b}{k + b}> 1 + \frac{a - b}{b} \\
  \frac{1}{k + b} > \frac{1}{b} \\
  k + b > b
$$
the problem is, that I think the inequality sign has to change to $<$ in the last step because of calculating the inverse on both sides. That would mean
$$ k + b < b$$
which is nonsense.
Comment: I don't think your assertion is true. For example, take $a=2,b=1,k=1$. Then you would say "$\frac32>21$", which is clearly false. In fact, the fraction decreases to $1$ as $k$ increases. So the very opposite is true, isn't it?
Answer: Note that you're trying to prove the wrong inequality: what's true is that
$$
\frac{k+a}{k+b}<\frac{a}{b}
$$
Since all terms are positive, the inequality is equivalent to
$$
b(k+a)<a(k+b)
$$
that is
$$
bk<ak
$$
that's true.
You can also go backwards:
\begin{gather}
b<a\\
bk<ak\\
bk+ab<ak+ab\\
b(k+a)<a(k+b)\\
\frac{b(k+a)}{b(k+b)}<\frac{a(k+b)}{b(k+b)}\\
\frac{k+a}{k+b}<\frac{a}{b}
\end{gather}

You could do in a different way:
\begin{gather}
\frac{k+a}{k+b}=\frac{k+a}{k+b}-\frac{a}{b}+\frac{a}{b}
=\frac{kb+ab-ka-kb}{b(k+b)}+\frac{a}{b}=\frac{k(a-b)}{b(k+b)}+\frac{a}{b}
\end{gather}
Comment: @user236182 Yes, I went to the correct one without even noticing!
Answer: You have :
$$
a > b
$$
and  $$
k > 0$$
then
$$ ak > bk$$
then
$$ak+ab >bk+ab$$
then
$$a(k+b) >b(k+a)$$
Answer: It's true that $\frac{k+a}{k+b}<\frac{a}{b}$ for all $a,b,k\in\mathbb R^+, a>b$ (i.e. the opposite of the original claim is true). Proof (I'm copying your solution with some changes):
$$\frac{k + a}{k + b}  < \frac{a}{b} \\
  \iff \frac{k + b + (a - b)}{k + b} < \frac{b + (a - b)}{b} \\
  \iff 1 + \frac{a - b}{k + b}< 1 + \frac{a - b}{b} \\
  \iff \frac{1}{k + b} < \frac{1}{b} \\
  \iff k + b > b\iff k>0,$$
which is true. But the better approach here is to simply multiply both sides by $(k+b)b$ (all the terms are positive, so we can do that without changing $<$,$>$) to get:
$$\iff b(k+a)<a(k+b)\iff bk<ak,$$
which is true.
Answer: Suppose you have $a$ apples and $b$ bananas, with more apples than bananas.  If someone gives you $k$ more of each fruit, the new ratio of apples to bananas is less than the old ratio (since the new fruit came in at a ratio of $1:1$ which is less than $a:b$).
So $\frac{a+k}{b+k}<\frac{a}{b}$.
Answer: HINT:
Say there are $b$ ounces of pure alcohol in $a$ ounces of solution, so the concentration is $\frac{b}{a}$ ( $< 1$). Adding  $k$ ounces of pure alcohol will increase the concentration to $\frac{ k+b} {k+a}$ .
Answer: With the basic rules on inequalities:
The general fact is this:

Suppose $a, b, k>0$. Then:

If $\dfrac ab >1$, then $\;\dfrac ab >\dfrac{a+k}{b+k}> 1$;
If $\dfrac ab <1$, then $\;\dfrac ab <\dfrac{a+k}{b+k}< 1$.

Indeed the first upper inequality is equivalent to
$$\dfrac ab >\dfrac{a+k}{b+k}\iff a(b+k)>b(a+k)\iff ak>bk\iff a>b. $$
The second upper inequality results from $a>b\implies a+k>b+k$.
The lower inequalities come down to the upper ones taking reciprocals.


How to you regex to extract just the name from a CString?

Question: Take a CString that has the following definition:
CString strNameText = _T("Mr Happy [12]");

I have a series of names with all have the space with a number is brackets at the end. Now I want to extract just the name from the string.
I realise that I can find the first index of " [" and then extract the text on the left up to that index. But can I use any regex command to do the same?
Comment: ```[A-Za-z ]+``` this includes the space at the side of ```[``` is this okay for you?
Comment: ```([A-Za-z]+ ?\b)``` now this one ignores unwanted trailing spaces, and even i don't know to perform a regex operation in c++, sry
Comment: @GhostOps Thanks. I don't want the trailing spece at the end of the name. I am also not sure how to perform an actual regex operation.
Comment: Is this an academic interest? For such a simple pattern, I'm sure regex is an overkill.
Comment: @vlad. No I had need for this. And I did not want to split the word manually.
Answer: I might suggest a regex replacement here, to remove the bracketed term at the end of the string.
std::string strNameText ("Mr Happy [12]");
std::regex r ("\\s+\\[\\d+\\]$");
std::cout << std::regex_replace (strNameText, r, "");  // Mr Happy

C++ Example
#include <regex>

CString strNameText = _T("Mr Happy [12]");

std::string s1 = CT2A(strNameText);
std::regex r("\\s+\\[\\d+\\]$");
std::string s2 = std::regex_replace(s1, r, "");

return CString(s2.c_str());

Comment: @TimBiegeleisen it's not the same thing at all, but both are c++ classes that implement string handling. CString is the from MFC and std::string is the standard C++ class.
Comment: Thanks. How do a pass a `CString` into the `regex_replace` function?
Comment: I tried `std::regex_replace(strNameText.GetString(), r, "");` and it doesn't like it.
Comment: @AndrewTruckle I'm not a C++ person, but AFAIK `std::string` is the same thing as a `CString`.
Comment: I added c++ version to your answer


Solving three-equations nonlinear system

Question: I am stack at solving the following non linear system
$$\dot{x}= x(1-x-y-z)-ax$$
$$\dot{y}= y(1-x-y-z)-ay$$
$$\dot{z}= z(1-x-y-z)-az$$
where $a<1$ And  the empty space 1 − x − y − z.
And I can only find its trivial solution $(0,0,0)$
How can I find its non trivial steady state solution?
The definition of steady state is the point $(x^*,y^*,z^*)$ such that $\dot{x}=0$ ,  $\dot{y}=0$ ,  $\dot{z}=0$
That is I need to find the solution of the following system
$$0= x(1-x-y-z)-ax$$
$$0= y(1-x-y-z)-ay$$
$$0= z(1-x-y-z)-az$$
Thanks a lot
Comment: What's $/dot x$? Or $/dot y$ or $/dot z$. Is it derivative? If so, by which variable?
Comment: @mdave16 first order differential equations.
Comment: Okay, I have explained clearly. Please look at the question box again. Thanks @mdave16
Comment: @mdave16 there was no need to grill OP so much, $\dot{x}$ is an *extremely* common notation for $\frac{d}{dt}$ and that much should have been inferred from context.
Answer: Let $w=x+y+z$. Then we have that
$$\dot{w} = \dot{x} + \dot{y} + \dot{z} = w(1-w)-aw$$
$$\implies \int dt = \int\frac{dw}{w(1-a-w)} = \frac{1}{1-a}\int \frac{1}{w}+\frac{1}{1-a-w}dw$$
by separation of variables. Solving, we get
$$(1-a)(t+C) = \log\left(\frac{w}{1-a-w}\right) \implies w(t) = \frac{1-a}{1+Ce^{(a-1)t}}$$
We can plug this back in to get the following system of equations:
$$\begin{cases} \dot{x} = (1-a)\left(1-\frac{1}{1+Ce^{(a-1)t}}\right)x \\
 \dot{y} = (1-a)\left(1-\frac{1}{1+Ce^{(a-1)t}}\right)y \\
\dot{z} = (1-a)\left(1-\frac{1}{1+Ce^{(a-1)t}}\right)z \\ \end{cases}$$
which is now fully decoupled. We can solve them by using the fact that
$$\dot{x}(t) = f(t)x(t) \implies x(t) = C\exp\left(\int f(t) dt\right)$$
so we get
$$x(t) = C_x \exp\left((1-a)\int 1 - \frac{e^{(1-a)t}}{e^{(1-a)t}+C}dt \right) = C_x \frac{e^{(1-a)t}}{e^{(1-a)t}+C} = \frac{C_x}{1-a}w(t)$$
with equivalent answers for $y$ and $z$.
To find nontrivial steady state solutions, notice that the $w$ equation was in the form
$$\dot{w} = (1-a-w)w$$
so either $w=0$ or $1-a-w=0$. The steady state solutions are all constants such that
$$w(t) = 1-a$$
or in other words, $x(t)+y(t)+z(t) = 1-a$
Comment: @user315 I'm about to edit the answer because I found a way to more fully proceed.
Comment: Thanks a lot. But I add some important information about the question. Please look at the question box. Is it enough to find unique solution. I need to find steady state point in fact.
Comment: Thank you so much. I am waiting for the edited version of your answer. Thanks :)
Comment: Here $\dot{w}$ is equal to zero. So how can I find it? Again I find trivial steady state solution.
Comment: @user315 check it now
Comment: I am so sorry. But I don't understand. Why there are no exact values $(x^*,y^*,z^*)$?
Comment: @user315 because there are an infinite number of answers...
Comment: Okay. I'm gonna think again. Thank you so much :)
Comment: Can I ask one more thing? The question states that "  the empty space 1 − x − y − z". Then, should I assume $x+y+z=1$?
Comment: @user315 I'm sorry I don't know what that means. And no, you shouldn't assume that. Look at the answer and tell me why.
Comment: Hmm yes I see. I added the original solution. When I look at the question, I need to find an exact solution. But, you are right as well... I confused. Please you also look at the original question.
Comment: For example, in the original question, in the next step, which steady state point will I use?
Answer: Solutions to the system of equations are
x = y = z = 0.
x = y = 0, z /= 0, a + z = 1 and coordinate permutations.
x = 0, yz /= 0, a + y + z = 1 and coordinate permutations.
The case a = 1 needs a closer look.
Comment: But $(x,y,z)=(0,0,0) $ is trivial steady state solution. I don't need this.


How to add char to unknown string length?

Question: I have a string and I know it includes the word "python" but I don't know how many characters the string has.
I want to add "." before "python"
for example:
     str = input("enter string")
     #Here I need help
     print(str)#The output will be the user's input and "." before the word "python" let say str = "I love python" the output will be "I love .python"

Comment: What code have you tried to solve it? @VictorHanukayev
Comment: You can also use `if` condition to check if `python` is in the user's input, then replace `python` with `.python`
Comment: I have no idea to solve it
Comment: Look at `string.split` and `string.join` methods! They will help guide you to the solution!
Comment: Possible duplicate of [How to find index of an exact word in a string in Python](https://stackoverflow.com/questions/38956274/how-to-find-index-of-an-exact-word-in-a-string-in-python)
Comment: `find`and `replace` string methods can be useful too.
Answer: I didn't exactly get your question but look at this, maybe it'll help.
inp=input('enter input ::')  # taking user input

new_str=inp.replace('python','.python') #just replace python will .python in user input

print(new_str)

The output will be like :
enter input ::i love python
i love .python


Statistical significance in mutations in two groups

Question: I'm doing an analysis examining the mutations of a set of ~3 genes in 4 different populations. For Gene 1: In Group A 33/540 have that mutation, Group B 66/100, Group C 15/213, and Group D 20/32. And so on for each of the three genes. What is the appropriate statistical test to determine the pairwise differences in the groups mutation rates?
I am included to use R's chisq.test() assuming a chi-square test will work. However, I'm curious as to whether I'm missing something.
Comment: You have a binary variable, with multiple genes across several populations. You probably need something like `lme4::glmer(cbind(mutated, total) ~ Group + (Group | gene))`, although the random effect is hard to estimate for just three genes. (I've also voted to migrate.)
Answer: From what you've told us, this sounds a lot like a heirarchical binomial model.
I'm going to assume that there is some population level mutation rate $\mu$.  Your sub-populations are thus samples from this larger population.  Each group will have a slightly different mutation rate $\theta_i$, but the expectation of the $\theta_i$ should be $\mu$.
Here is my stan model:
data{
 int num_groups;
 int y[num_groups];
 int N[num_groups];
}
parameters{

  real<lower=0, upper=1> mu;
  real<lower=0> kappa;
  real<lower=0,upper=1> theta[num_groups];
}
model{
 theta ~ beta(mu*kappa,(1-mu)*kappa);
 y~binomial(N,theta);
}

And here is my sampling call
library(rstan)
options(mc.cores = parallel::detectCores())

y = c(33,66,15,20)
N = c(540,100,213,32)
num_groups = length(N)
d = list(y = y, N = N, num_groups = num_groups)

fit = sampling(model,
               data = d)

bayesplot::mcmc_areas(as.matrix(fit), regex_pars = 'theta', prob = 0.8, prob_outer = 0.95)

This results in the following plot:

From this plot, we can tell that populations A and C are quite similar and populations B and D are quite similar (though we should be careful since there is still a lot of posterior variance).
Overall, we estimate a 71% probability that the $\theta_D < \theta_B$, but again we can't say for sure because there is a ton of posterior variance.  One this is for sure, populations A and C are different than B and D.


Windows Update Error Code 80248014?

Question: Windows Update says:

Windows could not search for new updates.

Error code is 80248014. What this error code means and how to resolve this issue?
Answer: In the wuerror.h I can find that 80248014 means WU_E_DS_UNKNOWNSERVICE:
//
// MessageId: WU_E_DS_UNKNOWNSERVICE
//
// MessageText:
//
// An operation did not complete because the service is not in the data store.
//
#define WU_E_DS_UNKNOWNSERVICE           _HRESULT_TYPEDEF_(0x80248014L)

stop the Windows Update service, rename the folder C:\Windows\SoftwareDistribution to C:\Windows\SoftwareDistribution.old, now check for Updates again. This sometime solves such strange errors.
Comment: wuerror.h? What is this?
Comment: @RichM this is a file from Windows SDK which includes includes windows update error codes
Answer: I recently ran into a similar problem. After employing a similar fix to the one mentioned by magicandre with no success, I discovered that something was amiss with DNS. I was trying to browse a website from the affected machine and the default IIS entry kept coming up. So, I changed my DNS servers in my network adapter to use Google's public DNS servers, cleared my DNS cache, and was able to check for updates.
Short version, if it's still a problem, it could be DNS related.
Comment: Does it display the **same** (not similar!) error code?
Comment: No, it was not the same, but my point is that Windows error reporting can be vague or inconclusive at best. I am merely suggesting that DNS could be an issue as it was with me, even though I could find no documentation on the Microsoft site or any other site to point me that direction.
Answer:
IN THE RUN BOX, I TYPED SERVICES.MSC
I RIGHT CLICKED IN WINDOWS UPDATE SERVICES AND STOP THE SERVICE
I RIGHT CLICKED THE FOLDER C:\WINDOWS\SOFTWAREDISTRIBUTION AND SELECTED RENAME
4  I ADDED JUST .OLD TO THE ORIGINAL NAME OF THE FOLDER.

Windows Update Error Code 80248014?


Proof of the intersection of 2 coprime order cyclic subgroups of G is the set e

Question:
Let $G$ be an abelian group. Suppose that $a$ is in $G$ and has order $m$ (such that $m$ is finite) and that the positive integer $k$ divides and $b$ has order $n$ with $\gcd(m,n)$=1. Prove that $\langle a\rangle \cap \langle b\rangle = \{e\}$.

since m and n are relatively prime this should be easy we know  $a^{m}  =e=b^{n}$
we know $\langle a\rangle$ is a cyclic subgroup of g and that $\langle b\rangle$ is a cyclic subgroup of g so $\langle a\rangle \cup \langle b\rangle $ is a subset of G. since G is abelian this must a cyclic group or its not a subgroup of G so $\langle b\rangle$ must be a subset of $\langle a\rangle$ or $\langle a\rangle$ must be a subset of $\langle b\rangle$ since the element $a^{m-1}$ cannot equal $b^{n-1}$ and both are generations for a and b respectively we have reached a contradiction.
Answer: The order of $\langle a\rangle$ is $n$, the order of  $\langle b\rangle$ is $m$. Now if $x$ belongs to the former, its order divides $n$. And if it belongs to the latter, its order divides $m$. So if it belongs to both, its order divides $\gcd(n,m)=1$. So $x=e$.
Comment: Both are great but i really like this answer =)
Comment: Nicely done +10
Answer: Note that if $x\in H$, then the order of $x$ divides the order of $H$.
if $x\in \langle a\rangle\cap\langle b\rangle$, then, the order of $x$ divides both order of $a$ and order of $b$, which must be $1$.
Therefore $x$ can only be the identity $e$.


Slicing Variable in Parfor loop

Question: Hi I want to run the code as below using PARFOR.
When I try it says that :

Valid indices for 'A_x' and 'A_y' are restricted in PARFOR loops.
  Explanation  For MATLAB to execute parfor loops efficiently, the
  amount of data sent to the MATLAB workers must be minimal. One of the
  ways MATLAB achieves this is by restricting the way variables can be
  indexed in parfor iterations. The indicated variable is indexed in a
  way that is incompatible with parfor.  Suggested Action
Fix the indexing. For a description of the indexing restrictions, see "Sliced Variables" in the >Parallel Computing Toolbox documentation:

 N=eveninteger;
 H=zeros(N);
 V=zeros(N);
 A_x=zeros(N);
 A_y=zeros(N);
    parfor i=1:N;
      for j=1:N;
        if H(i,j)==-2;
          t=0.3;
          As_x=t*(j-i)/a;
          As_y=t*(j-i)/a;

       elseif H(i,j)==-3;
           t=0.8;
          As_x=t*(j-i)/(a*sqrt3);
          As_y=t*(j-i)/(a*sqrt3);

      elseif i==j

               As_x=i;
               As_y=i;
      else
          t=0;
          As_x=0;
          As_y=0;

        end
      for p=1:N/2
        for q=N/2+1:N

             A_x(p,q)=A_x(p,q)+As_x*(V(i,p)*V(j,q));
             A_y(p,q)=A_y(p,q)+As_y*(V(i,p)*V(j,q));

        end
      end
end

end
I could not find solution. Could you offer me a solution.
Thanks in advance.
Erico
Comment: Your code is incomplete, at least an "end" is missing. Please indent your code properly, use rightlick->"Smart Indent" in the editor.
Comment: never tried it but having a bunch of `for` loops nested within a `parfor` loop seems awkward. And it seems some of them (nested `for` loops) could be replaced by vectorized expressions.
Answer: It looks like you're trying to perform a "reduction" on A_x and A_y using +. You might be able to work around this by doing something like the following:
parfor i = 1:N
  A_x_tmp = zeros(N);
  A_y_tmp = zeros(N);
  for p=1:N/2
    for q=N/2+1:N
      A_x_tmp(p,q) = A_x_tmp(p,q) + ...
      A_y_tmp(p,q) = A_y_tmp(p,q) + ...
    end
  end
  A_x = A_x + A_x_tmp;
  A_y = A_y + A_y_tmp;
end

In that way, PARFOR will understand the reduction operations on A_x and A_y.

Slicing Variable in Parfor loop


Assembler warning with gcc warning when placing data in .text

Question: When I compile
__attribute__((section(".text"))) const int x = 42;
int main(){ return x; }

with gcc (works with tinycc and clang), I get
Warning: ignoring changed section attributes for .text.
What is the cause of the warning and how can it be eliminated while still keeping the (always readonly) data in .text?
Comment: Apparently gcc emits a `.section .text,"a",@progbits` directive instead of just `.section .text`. I don't see any way to avoid it.
Comment: Always a good idea to [Google the error message](https://gcc.gnu.org/ml/gcc-help/2010-09/msg00088.html)
Comment: A better answer to this question is probably - "use clang then".  I can think of few reasons not to prefer clang over gcc.
Answer: Apparently:
__attribute__((section(".text#"))) const int x = 42;

Ref: https://gcc.gnu.org/ml/gcc-help/2010-09/msg00088.html  where the answerer explains:

__attribute__ ((section(".text"))) will make gcc emits
  ,"aw",@progbits after the .text to alter the section attributes.
  If you use: __attribute__ ((section(".text#"))) (notice the extra
  '#') this suffix will be commented in the assembly and the warning
  will disappear

In that case the variable concerned was not const, so it was especially ill-advised (as stated by another responder) to the same question.  In your case it is a const, so the access is "a" rather than "aw" - still probably ill-advised however.
Comment: Yes, here OP already has `const` though. I would assume the intent is locality of the data to the code (probably not relevant to split D/I L1 cache but would affect L2, L3 usage) not just a wrong hack in place of `const` for making the data read-only.
Comment: Not mine.  Another responder in the same thread does indeed give more sage advice:  https://gcc.gnu.org/ml/gcc-help/2010-09/msg00098.html
Comment: Yes, I am not responsible for any use this information may be put to!  I just google'd it for him - a tart for rep that's me!
Comment: Nice trick, unfortunately doesn't work for me using GCC 6.3. The '#' at the end is interpreted as part of the section name, and causes this error when I try using `__attribute__((section(".data#")))`:

`/usr/lib/gcc/m68k-elf/6.3.0/../../../../m68k-elf/bin/ld: section .data# LMA [000000000000a390,000000000000a40d] overlaps section .data LMA [000000000000a390,000000000000a3db]`
Answer: Apparently gcc emits a .section .text,"a",@progbits directive instead of just .section .text. I don't see any way to avoid it. However the default linker script usually merges all sections named .text.* so you can do something like __attribute__((section(".text.consts"))) and in the final binary it will be in the .text section.
@Clifford found a hackish workaround which involves putting a # after the section name so that the assembler considers the rest of the line a comment.
Comment: Right. However if OP is trying to put constants in `.text`, the most likely plausible reason is for locality with the code.
Comment: I think it merges them *after* assembling them individually, so this will change the final output order (moving the consts away from their functions)
Comment: That is true, but was not a requirement in the question :)
Comment: @Clifford: Don't! It's a classic one and somewhat blessed in the sense that gcc has never offered up a preferred alternative to it.
Comment: @R.. Won't a literal constant do that?  `#define x 42`. Not pretty, or type aware, but conventional in C.
Comment: @R.. I changed my mind and deleted my comment - now everyone will wonder what I said!
Comment: @Clifford The code in the question is dumbified. `#define x 42` wouldn't work for a nontrivial structure whose address matters (which motivated the question).
Comment: @PSkocik Fair enough.


Can't click on a button using Selenium (web scrape)

Question: I am trying to click on this button so that I can proceed to the next page but doesn't seem to be working for me. I am trying to click on the 'Search for an inspection report' button.
This is the xpath for this source. //[@id="btnOK"] . And so I was trying to use driver.find_element_by_xpath('//[@id="btnOK"]').click() and it gives me an error saying unable to locate element.
Here is the link to the site.
https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise
Any help would be great.
Comment: Pls check whether my code works for u.
Answer: It is because the button is present within a different iframe. In order to click that button, u have to switch focus to that iframe. This is how u do it:
iframe = driver.find_element_by_id("iframe-form")

driver.switch_to.frame(iframe)

btn = driver.find_element_by_xpath('//*[@id="btnOK"]')

btn.click()

Plus, another thing to note is that the xpath u have provided is wrong. U have missed a * in the xpath. The right xpath is '//*[@id="btnOK"]'.
Complete code:
from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise')

iframe = driver.find_element_by_id("iframe-form")

driver.switch_to.frame(iframe)

btn = driver.find_element_by_xpath('//*[@id="btnOK"]')

btn.click()

Hope that this helps.
Answer: Alternative solution using webdriver wait:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('<PATH_TO_CHROMEDRIVER>', options=chrome_options)

# load page via selenium
wd.get("https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise")
# wait for iframe, switch to it
frame = WebDriverWait(wd, 30).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"iframe-form")))
# wait for button, scroll to it, click it
btn = WebDriverWait(wd, 30).until(EC.presence_of_element_located((By.ID, 'btnOK')))
wd.execute_script("arguments[0].scrollIntoView();", btn)
wd.execute_script("arguments[0].click();", btn)


deadlock and synchronization in java

Question: I have a question, I am always asked this in the interviews multiple times--
How is synchronization  implemented in java..
I have answered--
using trylock() mechanism
using wait, notify ,and notifyAll() methods in java
using synchronized blocks
using synchronized for class and object level
using mutexes for synchronization
using re-entrant locks
Are there any better answers to this?/
Comment: Are you talking about how synchronization is implemented by JVM implementors, or how synchronization is used by developers?
Answer: If you care about gaining a deep insight on concurrency then a great source is the http://www.javaconcurrencyinpractice.com/ book.
If you simply care about "passing" this question in interview(s?) then http://download.oracle.com/javase/tutorial/essential/concurrency/index.html may do, but still you generally need to practice a bit to understand synchronization so you are in a position where you'll sufficiently answer questions following the extremely vague "How is synchronization implemented in java".
Comment: +1 - Buy the book and read it, and you'll be able to do more than answer interview questions.
Answer: Why not read up on Sun's/Oracle's tutorial on Java synchronization? That's the official view.
Answer: I'd probably go with something along the lines of what is found here: http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html

deadlock and synchronization in java


How to add Hamcrest to XCODE?

Question: I cannot find the actual hamcrest.framework - only the source code. What steps are to take to actually include into xcode ?
I tried to compile the source code but do not get it connected to a new project I want to create.
Answer: It's actually quite easy. And there is a really great tutorial at Ray Wenderlich's web page ! So check out: http://www.raywenderlich.com/97014/use-cocoapods-with-swift
1) Create an XCode Project (where you want to use Hamcrest)
2) close Xcode
3) Open Terminal-Window and goto path of Xcode Project File
4) (if not already installed) install cocoapods: (this takes quite a while, so don't panic)
sudo gem install cocoapods
pod setup --verbose // for verbose output
pod init  // if it fails with error message you might not be in the correct path)

5) Open Pod-File
open -a Xcode Podfile

6) Edit Pod-File
platform :ios, "8.0"
use_frameworks!

7) integrate hamcrest as described in github (swifthamcrest)
target 'HamcrestDemoTests' do  // name of your File
  pod 'SwiftHamcrest'
end

8) Safe File and start installation
pod install

9) Open your Project using the .xcworkspace file
10) import Hamcrest in your TestSuite
import XCTest
import Hamcrest

@testable import test

class testTests: XCTestCase {

Don't worry about initial errors that it cannot find the module. They will go away after first building the project.
Answer: i would suggest using cocoapods. It makes adding third-party libraries to your project so much more easy. If you check the OCHamcrest page here: https://github.com/hamcrest/OCHamcrest
they even provide you with instructions on how to set it up.

How to add Hamcrest to XCODE?


Where does Virtualbox store its data for writethrough disks?

Question: I've got Virutalbox 1.6.2 on Ubuntu 8.04.
I've got an XP virtual machine with a single write through disk image.  The image file (WinXP.vmdk) itself is only 744B in size.  Somewhere there's several gigs worth of data for this machine, but I don't know where it is.  I've searched through my .VirtualBox folder and can find nothing.
Answer: Due to the fact that you have a vmdk, but are talking about VirtualBox, it must be assumed that the virtual disk was created by one of VMware's products, then imported into VirtualBox.  VirtualBox has been able to read VMware's vmdk format since, at least, version 1.6.2 (see: changlog), including the rawdisk/partition formats.
Do you have more than one partition on this machine?  Could the VMware XinXP-pt.vmdk be pointing to an actual physical partition on the HDD?
For example, there is documentation about how to set up raw virtual disks in WMware Workstation:
http://www.vmware.com/support/ws55/doc/ws_disk_raw_install_linux.html
I'd run gparted, parted, or fdisk to look for additional partitions on the host drive.  Also, it might help you post the contents of the vmdk file.
Comment: Doh!  I set this thing up a year ago and completely forgot....  I do have a dedicated partition that had/has Windows XP on it, and I "virtualized" it.  Good call!
Answer: .vmdk is a VMware disk. Unless you imported a VMware disk not sure what that is. Do you have any .vdi files those would the disk images created by VirtualBox.
You should be able to find it using the Virtual Disk Manager
Comment: No .vdi files anywhere.  In the Virtual Media Manager it lists the WinXP.vmdk file, and it's only a few bytes.  I just upgraded to 3.0.4 and the results are the same.
Comment: This is driving me nuts.  I'm trying to convert the vmdk to vdi, and basically can't because I can't find the actual data file.  The WinXP.vmdk file is text and points to a file called WinXP-pt.vmdk which is binary, but only 1MB in size.  This virtual disk should be at least 5GB.  I did a search for large files on the machine and turned up nothing.


std::string constructor with lvalue throws with clang

Question: I am making use of Matei David's handy C++ wrapper for zlib, but I get an error when compiling on macOs (clang-1100.0.33.
 include/strict_fstream.hpp:39:37: error: cannot initialize a parameter of type 'const char *' with an lvalue of type 'int'

The problem is here:
/// Overload of error-reporting function, to enable use with VS.
/// Ref: http://stackoverflow.com/a/901316/717706
static std::string strerror()
{
    std::string buff(80, '\0');

    // options for other environments omitted, where error message is set
    // if not Win32 or _POSIX_C_SOURCE >= 200112L, error message is left empty.

    auto p = strerror_r(errno, &buff[0], buff.size());

    // error next line
    std::string tmp(p,  std::strlen(p));
    std::swap(buff, tmp);
    buff.resize(buff.find('\0'));
    return buff;
}

(Which IIUC has nothing to do with zlib, just trying to report errors in a thread safe manner).
If I change to this:
static std::string strerror()
{
    std::string buff(80, '\0');

    auto p = strerror_r(errno, &buff[0], buff.size());

    // "fix" below
    size_t length = buff.size();
    std::string tmp(p,  length);
    std::swap(buff, tmp);

    buff.resize(buff.find('\0'));
    return buff;
}

My program compiles and runs fine.
I have two questions:

Why does clang not like the constructor std::string tmp(p,  std::strlen(p));?
The buffer was declared at the beginning of the function as length 80. Why are we even bothering to look up the length?
The answer to 2 may answer this, but is there something wrong with my version?

Thanks.
Comment: Check the documentation for `strerror_r`. There are two completely different versions of it floating around, with different return values. You have the one that returns an `int`. That's what your `strerror_r` obviously returns, and constructing a `std::string` from an int, as the error message clearly complains about, very clearly, is not going to end well.
Comment: There is an ISO C (and ISO C++ by inclusion) function called `strerror`; to avoid confusion it might be good to rename this function something else
Comment: Yes, thanks @M.M, it is actually in a namespace in the original code. Got a little aggressive with my code trimming.
Answer: If you use int strerror_r(int errnum, char *buf, size_t buflen);, then there is no appropriate string constructor and the program is ill formed.
If you use char *strerror_r(int errnum, char *buf, size_t buflen);, then the program is well-formed.
The standard C/POSIX library implementation influences which function you get. Compiler is only involved as much as influencing what system library may be used by default.
Former function is extension to POSIX specified in XSI (which is essentially an optional part of POSIX) and latter is a GNU extension.
In case you use glibc (I don't know if that is an option on MacOS), you can control which version you get with macros, although the XSI compliant version is not available in older versions. Its documentation says:

The XSI-compliant version of strerror_r() is provided if:
  (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE

The buffer was declared at the beginning of the function as length 80. Why are we even bothering to look up the length?

In the construction std::string tmp(p,  std::strlen(p));, strlen seems entirely unnecessary to me. std::string tmp(p); is equivalent.

If you don't need thread safety, then the most portable solution is to use std::strerror which is in standard C++:
return std::strerror(errno); // yes, it's this simple

If you do need thread safety, then you could wrap this in a critical section using a mutex.

Note that strerror, the name of your function, is reserved to the language implementation in the global namespace when the standard library is used. The function should be in a namespace, or be renamed.
Comment: I guess one could make "portable" code based on overloading or whatever that works for both versions of `p`
Comment: Got it. The original code referenced in my question does have a couple versions, one for POSIX compliant strerror and one for the GCC strerror. It seems I need to tweak the compiler directives to catch the fact that clang wants the POSIX one.
Comment: Or, rather, not that clang wants the POSIX one, but that the version of libc I have is the POSIX compliant one.
Answer: There are two different versions of the strerror_r that you'll commonly see:

A POSIX-compliant version that always stores the error message in the provided buffer (if it succeeds) and returns an int (0 for success, non-zero for error)
A GNU version that may store the error message in the provided buffer, or maybe not.  It returns a char* pointing to the error message, which may point to the user-supplied buffer or may point to some other global static storage.

That strerror function is clearly written to work with the GNU version of strerror_r.

As for your second question, you need the strlen.  buff is 80 characters long, but the actual error message may be shorter and only partially fill the buffer.  That strlen is being used to trim off any extra nul characters from the end.


Explanation on examples of non-divisible module

Question: So the multiplicative group of complex numbers, $\mathbb{C}^*$, is divisible as an abelian group.
Why is the multiplicative group of real numbers, $\mathbb{R}^*$, not divisible as an abelian group?
What is the difference?
My lecturer remarked this as an explanation : "$\mathbb{R}^*$ contains $-1$ which is not divisible by $2$".
I don't really understand this, because you can clearly write $-1 = 2(-\frac{1}{2})$
Answer: "Divisible" means with respect to the $\Bbb Z$-module structure of the abelian group $(G,*)$, id est the action $$n\odot z=\begin{cases}\underbrace{z*z*\cdots*z}_{n\text{ times}}&\text{if }n\ge 0\\ \underbrace{z^{-1}*z^{-1}*\cdots*z^{-1}}_{(-n)\text{ times}}&\text{if }n< 0\end{cases}$$ Since the operation, in this cases, is multiplication, the action of $\Bbb Z$ is $n\odot z:=z^n$.
Concretely, here being divisible by $2$ means having a square root.
Comment: Thank you! I was thinking this clearly. It was such an obvious mistake.


pyTesseract not outputing text from image

Question: maybe someone could help me! When I run the following code
import pytesseract
from pytesseract import image_to_string
from PIL import Image
import PIL
file = Image.open('/usr/local/Cellar/tesseract/4.1.0/share/tessdata/cap.png')
we_will = pytesseract.image_to_string(file)
print(we_will)

all that gets outputed is:
Process finished with exit code 0

which is no help. What am I doing wrong?
Answer: Sounds like we_will is the empty string. Try printing repr(we_will) to understand this idea more clearly.
IIRC, PyTesseract does this when it can't figure out what the text is inside the image. You can get the best results for a cropped image with a single-color background.
Comment: Thank you, i was attempting to use pyTesseract to break a captcha but that was pointless!


Creating a responsive menu system for a site with a lot of content

Question: I am currently creating a website which has a lot of content - text. For this I need a serious menu structure with 5-10 menu items per menu and at least 15 menu-blocks per main menu item.
Further it has to be accessible via mobile.
Till now I have used panels and added menus inside the panels. But mobile isn't to happy about that and the list-names in the menus overlap the content.
How would you go about solving this issue? I trust you experts here! :-)
Answer: for creating responsive menu you have lots of projects
below are some
https://www.drupal.org/project/responsive_menus
https://www.drupal.org/project/responsive_navigation
https://www.drupal.org/project/responsive_dropdown_menus
https://www.drupal.org/project/responsive_menu
try any one will help you out.
Answer: I recommend looking into a couple of third-party javascript and/or jquery plugins you can integrate with Drupal to provide a more unified menu experience for both desktop and mobile users.
Big Slide Menu - Mobile Push Menu
The first, more tested option is to utilize the Big Slide Menu plugin, which creates a mobile push-menu, which can account for several layers of depth, without demanding too much screen real-estate.
https://github.com/adgsm/multi-level-push-menu
This option may be difficult to integrate the with Drupal Menu system, but it would certainly give you a robust solution, which can accomodate you needs for a large more complex menu system.
Snap.js -  Mobile Shelf Menu
The second, but perhaps more complicated option is to integrate Snap.js, which provides a mobile-shelf "type" menu.
https://github.com/jakiestfu/Snap.js/
To my knowledge it's not a module for Drupal, but that being said you don't have to do much to combine the plugin with drupal.
First, you have to be able to edit the page.tpl.php, which is where you want to add the snap-content selector to page container.
Second, you have to add the Snap content container, which will contain the responsive-ready menu system. I recommend adding this below the page container. You will either want to add a new region in this location ( so you can add blocks from admin/structure/blocks) or create a function to add the appropriate menu to the location. I definitely don't recommend hard-coding the menu in, but it may be a consideration in your case if the menu is static and you want to make the design process a little easier.
Comment: Thanks a bunch! However this is a bit to custom for my taste :-)


On using one distribution to approximate another

Question: Every basic text about different statistical distributions make notions about when one distribution can be approximated using another one. For example, we are told that the binomial distribution with sufficiently large n and sufficiently small p can be approximated using Poisson distribution. My question is why? Why is this interesting? What do we gain by knowing that a certain process that is binomial in theory can be approximated by Poisson?
Comment: Quick, what's the chance that a Binomial$(10^{1000}, 10^{-999})$ variate will be less than $10$? (Try that one out on any floating-point platform such as `R`!)
Comment: @whuber your comments are sometimes too insightful to be left as comments...
Answer: Here's a couple of situations:
1) A problem I have had recently: I have a sum of many (several dozen) binomial$(n_i,p_i)$, with large $n_i$ (hundreds to thousands) and very small $p_i$ (in the general ballpark of $1/n_i$, perhaps typically between $0.1n_i$ and $10n_i$). The answers you get using the Poisson approximation to the binomial typically have a good deal more accuracy than required, so computing the convolution numerically is fortunately unnecessary (it's not particularly onerous, but less convenient, and not as easy to explain to people already aware of the existence of the Poisson approximation, but who have no experience of numerical convolution).
2) I saw this one come up as a real problem quite recently: I have an average of $k$ independent variates, each hypergeometric. What's the probability that the average is less than $c$? If I already know that in some situations the normal is a reasonable approximation to the hypergeometric, I can exploit that immediately to answer the question (and for the values involved, the approximation is excellent).


Detectar URL WebView

Question: Estou com um probleminha, preciso saber a URL toda vez que a página é mudada.
o meu código funciona perfeitamente abre normalmente o youtube que seria o exemplo :
  WebView wv;

    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.wv);
        //Enable Javascript
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusableInTouchMode(true);
        // set Render Priority to high
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // Load url
        wv.loadUrl("https://www.youtube.com/");
        wv.setWebViewClient(new WebViewClient());
    }

Procurei soluções em sites gringos para o meu problema e descobri essa aqui
WebView wv;

public void onBackPressed(){
    if(wv.canGoBack()){
        wv.goBack();
    }else{
        super.onBackPressed();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    wv = (WebView) findViewById(R.id.wv);
    //Enable Javascript
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setFocusableInTouchMode(true);
    // set Render Priority to high
    wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setAppCacheEnabled(true);
    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    // Load url
    wv.loadUrl("https://www.youtube.com/");
    wv.setWebViewClient(new myWebViewClient());
}

String currentUrl;

private class myWebViewClient extends WebViewClient{
    @Override
    public boolean shouldOverrideUrlLoading (WebView view, String url){
        Log.e("URL Now",url);
        currentUrl=url;
        view.loadUrl(url); // se eu usar isso, já não fica em branco a inicial, mas msm assim não alerta qndo muda de URL
        return true;
    }
}

Verifiquei os logs e vi que apareceu a URL assim que abriu o APP, porem não abriu o youtube, a tela fica toda branca.
Meu primeiro exemplo funciona perfeitamente, mas não atende minhas necessidades.
O meu objetivo é saber é detectar quando clico em um vídeo, para isso preciso saber.
Existe alguma outra forma mais elegante de fazer esse feito ?
Answer: Boa noite Bruno, creio que descobri + ou - o que você deseja, os dados que é pego você precisa filtrar com regex, vai depender muito do que você deseja, porque aparece todas as resource, mas de forma precisa, mudar a página, muda no log.
package com.example.offboard.youtubedownload;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView wv;

    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.wv);
        //Enable Javascript
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusableInTouchMode(true);
        // set Render Priority to high
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // Load url
        wv.loadUrl("https://www.youtube.com/");
        wv.setWebViewClient(new myWebViewClient());
    }

     String currentUrl;

    private class myWebViewClient extends WebViewClient{

        @Override
        public void onLoadResource(WebView view, String url) {
            Log.e("Resource ",url); // talvez você precise usar regex para filtrar a URL, mas foi o único jeito que achei
        }

    }

}

Comment: Vou abrir aqui o projeto e testar agora antes de ir pra academia.
Comment: Poxa cara funcionou perfeitamente, obrigado, mas pega tudo mesmo kkkk, eu me viro com as regex para filtrar a página, obrigado mesmo.
Answer: Essa pergunta já foi aceita mas vou colocar aqui algumas opções de métodos da WebViewClient que podem ser uteis.

onPageStarted - É chamada para informar que uma pagina começou a carregar.
void onPageStarted(WebView view, String url, Bitmap favicon);

onPageFinished - É chamada para informar que uma pagina terminou de carregar.
void onPageFinished(WebView view, String url);

onLoadResource - É chamada toda vez que um recurso vai começar a carregar.
void onLoadResource(WebView view, String url);

shouldOverrideUrlLoading-(Deprecado, Novo) - Chamada antes do carregamento de uma pagina, dá ao programador chance de controlar sé a pagina pode carregar.
  Ao retornar true você aborta o carregamento, retornando false o carregamento e permitido.
boolean shouldOverrideUrlLoading(WebView view, String url);*
boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request);

*Esse método foi deprecado na API level 24

shouldInterceptRequest-(Deprecado, Novo) - Intercepta o carregamento de um recurso, dando ao programador a chance de trocar o recurso, se retornar null o carregamento do recurso vai continuar normal.
WebResourceResponse shouldInterceptRequest (WebView view, String url)*
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request);

*Esse método foi deprecado na API level 21

Exemplo de implementação:
WebViewClient mWebViewClient = new WebViewClient(){

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon); /// executa o padrão
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url); /// executa o padrão
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url); /// executa o padrão
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        return super.shouldOverrideUrlLoading(view, request); /// executa o padrão
    }

    @Nullable
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request); /// executa o padrão
    }
};

Detectar URL WebView


Set command line parameter in build.gradle

Question: One of the gradle tasks I'm running is doing too many printouts and since I can't adjust its inner log level I'm trying to run it with the -q command line option to restrict the printout to error level only. That works fine but I also need to run the task when I don't have access to the command line (like from inside IntelliJ and when running other tasks that are depending on it.)
Is there a way that I can specify in build.gradle that this task should always be run with -q?
Answer: It seems, that it's not possible to do it now for a single task - there is an open issue for supporting such a case, which is still open.
Answer: You can set a global log level in gradle.properties

org.gradle.logging.level=(quiet,warn,lifecycle,info,debug)
When set to quiet, warn, lifecycle, info, or debug, Gradle will use this log level. The values are not case sensitive. The lifecycle
  level is the default. See Choosing a log level.

It's not possible to reduce the scope to the task level but at least for test purpose, it will work.


how to clear all non-jpg img tags from a string

Question: How to clear all  tags from an HTML string from files that do not have a jpg or gif extension in PHP
I have to remove all img tags from a string, where the extension of the src is not jpg or gif.
So far I tried:
<code>$dom=new domDocument;
$dom->loadHTML($content);
$dom->preserveWhiteSpace=false;
$images=$dom->getElementsByTagName('img');
foreach($images as $image)
{
    $ea=array('gif','png','bmp','jpg','jpeg');
    $ext=pathinfo($image->getAttribute('src'), PATHINFO_EXTENSION);
    if(!in_array(strtolower($ext),$ea))
    {
        $image->removeAttribute('src');
    }
}
$cleanc=$dom->saveHTML();
</code>
but this is slow and it only removes the source.
Comment: Stack Overflow is not a code-writing service. What have you tried so far? If nothing, then have a look at http://php.net/manual/en/class.domdocument.php
Answer: Well, DOMDocument is not going to be particularly fast. If you want to remove the image and not just its src, try:
<code>if(!in_array(strtolower($ext),$ea))
{
    $parent = $image->->parentNode;
    $parent->removeChild($image);
}
</code>


create list by groups and create json

Question: Ok I had this problem that has been solved
combine data in depending on the value of one column
I have been trying to adapt the solution for a more complicated problem but i have not been able to come with the solution instead of 2 columns i have 3
df <- structure(list(year = c(2000L, 2001L, 2002L, 2003L, 2001L, 2002L), group = c(1L, 1L, 1L, 1L, 2L, 2L), sales = c(20L, 25L, 23L, 30L, 50L, 55L), expenses = c(19L, 19L, 20L, 15L, 27L, 30L)), .Names = c("year", "group", "sales", "expenses"), class = "data.frame", row.names = c(NA, -6L))

    year   group sales  expenses
1   2000     1    20     19
2   2001     1    25     19
3   2002     1    23     20
4   2003     1    30     15
5   2001     2    50     27
6   2002     2    55     30

And I need the same output as in the first problem but instead of just the sales I also need to include the expenses in the json file
[{"group": 1, "sales":[[2000,20],[2001, 25], [2002,23], [2003, 30]], "expenses":[[2000,19],[2001, 19], [2002,20], [2003, 15]]},
{"group": 2, "sales":[[2001, 50], [2002,55]], "expenses":[[2001, 27], [2002,30]]}]

Comment: could you do `deparse(your_data)` and paste it for reproducibility?
Comment: @timelyportfolio `dput()`? (or `cat(deparse())`, mebbe?)
Comment: It should be pretty clear from the previous answer how to do this - reread the answer and try and figure it out.
Answer: toJSON(setDT(df1)[, list(sales= paste0('[',toString(sprintf('[%d,%d]',year, sales)),']'),
                     expenses= paste0('[',toString(sprintf('[%d,%d]', year, expenses)),']')), by = group])

Try this. Its not different than akrun's answer.combine data in depending on the value of one column
Comment: added a `dplyr` solution to the "replicated" question; can't add here since voted down

create list by groups and create json