Exchange 2013, partnerships, domains, & out of office

Question: Background: I work at a company with several confidential business partnerships that require employees to appear as though they work for another company/brand and use multiple domains via email in accordance with whatever brand they happen to be representing at the time.  We've had moderate success with most of this requirement so far.  (I have an Exchange 2013 on-premises DAG environment in a one forest, one domain architecture, but multiple SMTP domains)
Problem: When a user sets up an out-of-office to reply externally, Exchange auto-replies only from the primary SMTP address of the user.
Example: John Doe emails a customer from firstname.lastname@example.com and goes out of office.  The customer replies to the email and receives an out-of-office reply from email@example.com instead; breaking our contractual obligation of maintaining the confidential partnerships.
Question: Does anyone know how/if this can be fixed so the out-of-office sends from the address that was originally sent to instead of only sending from the primary SMTP alias of the user?
Restrictions: I'm hoping to avoid configuring multiple mailboxes or 1-to-1 shared mailboxes for my 500+ users, and also hopefully avoiding creating a second domain or standing up more servers for this fairly trivial (from a technology standpoint) issue.
Comment: With SOX404 rule I use to make the technician use an email hosted on the remote business. So that the data is all for the customer site. Thus it's 100% transparent.
Comment: In this case our business partners have actually transferred the email domains in question to our direct ownership/stewardship, so I don't believe they would be willing to renegotiate such a thing at this point.  Part of the agreement was to offload a lot of their own IT responsibilities.  It would have been easier if IT had been involved in the planning of this contract up front to provide commentary, but as usual, IT is the last department to know about such things...
Comment: New server :| or call Microsoft or such business to be able to set office365 look-like domain/hosting for each domain
Answer: No, and I'm not aware of any third-party software that can accomplish this either.


Branches of $\sqrt{z}$ when removing the negative real axis

Question: In Complex Analysis by Ahlfors, he defines the complex square root $w(z)=\sqrt{z}$ on the complement of the negative axis $\Re(z)\leqslant 0$ to be the square root with positive real part. He then shows that this is continuous as follows:
$$|z-a|=|w^2(z)-w^2(a)|=|w(z)-w(a)||w(z)+w(a)| \geqslant |w(z)-w(a)|\cdot\Re(w(a))$$ which implies that given $\epsilon>0$ we can see that letting $\delta=\epsilon \cdot \Re(w(a))$ we have
$$|z-a|<\delta \implies |w(z)-w(a)|\leqslant\frac{|z-a|}{\Re(w(a))}<\epsilon.$$
I can see that he used the fact that we cut out the negative real axis when dividing by $\Re(w(a))$ as the square roots of negative reals are purely complex. But, why did he decide the square root to be the one with positive real value? I believe that the same computation shows that if we define
\begin{cases}
        0\leqslant \text{Arg}(w)\leqslant \pi/2 & \text{if } 0\leqslant \theta \leqslant \pi/2\\
        \pi\leqslant \text{Arg}(w)\leqslant 3\pi/2 & \text{if } \pi/2\leqslant \theta<\pi\\
\pi/2\leqslant \text{Arg}(w)\leqslant\pi & \text{if } \pi<\theta\leqslant 3\pi/2\\
3\pi/2\leqslant \text{Arg}(w)\leqslant 2\pi & \text{if } 3\pi/2\leqslant\theta\leqslant2\pi
    \end{cases}
then we can replace $\Re(w(a))$ with $|\Re(w(a))|$ and then $w$ is continuous. But we would have 16 choices for a continuous square root on $\mathbb{C}-\mathbb{R}^{\leqslant0}$ which seems untrue. Is there an error in my understanding here?
Comment: Only two branches exist (the proof is easy since the branch is uniquely defined by the value at a point and there are just two possible values; here since cutting the negative reals means polar representation $re^{it}, -\pi<t<\pi$, the branches are $\sqrt r e^{it/2}$ and its negative - the first one which is positive on the reals (and more generally has positive real part for all numbers in the domain) is the principal one by convention
Comment: First, you can choose a branch cut wherever you want. Any line (or even any simple curve) from the branch point at $0$ to the branch point at $\infty$. Second, your proposal has two different arguments for $w$ at $\pi/2$ and $3\pi/2$ which is definitely... Not well defined, unless you mean you want to add more than one branch cut (which is fine; you just have to make sure things glue together nicely afterward into the correct Riemann Surface)
Comment: I'm only wondering about cutting the negative real axis. Sure I agree, the first case can be modified to make the upper bound  for $\theta$ strict and the fourth can be modified to make the lower bound strict. I'm wondering if it really is possible to get $16$ distinct continuous square roots from a single branch.
Answer: Let $D$ denote the complex plane with the non-positive real axis removed. There are precisely two branches of square root on $D$, each the negative of the other. (A branch of square root in $D$ is a holomorphic function $f$ in $D$ satisfying $f(z)^{2} = z$ for all $z$ in $D$.) The diagram shows the real parts of the two branches, whose graphs are mirror images across the $z$-plane:

One branch, the so-called principal branch (gray), is positive on the positive reals, and extends the real square root (yellow) to $D$. The other branch (green mesh) is negative on the positive reals. That's about as close as one can get to answering "Why did [Ahlfors] decide the square root to be the one with positive real value?"
As for what appears to be wrong with the "sixteen branches" argument, in the "piecewise" formulas of the original question there are discontinuities in $\operatorname{Arg}(w)$ on the ray where $\theta = \pi/2$ (the stated value jumps from $\pi/2$ to $\pi$), and similarly discontinuities where $\theta = 3\pi/2$ and where $\theta = 0$ (a.k.a., $2\pi$). If we could independently select branches on each quarter plane, there would be $2^{4} = 16$ branches of square root. Continuity, however, reduces our freedom to just two choices.


Show that if $x$ is a limit point of $A\subset X$ and $f:X \rightarrow Y$ is continuous then $f(x)$ is a limit point of $f(A)$

Question: Suppose $f:X\rightarrow Y$ is a continuous function between the topological spaces $X$ and $Y$. Suppose that: $A \subset X$ and that  $x$ is a limit point of $A$.
Show that $f(x)$ is a limit point of $f(A)$
By a limit point $c$ of $B$ I mean that every neighborhood of $c$ intersects $B$ in a point $d$ such that $c\not = d$
What I have done is that: I supposed that $x$ is a limit point of $A$ but $x\not\in A$ and showed the required. but in the case when $x \in A$. My trial goes as follows:
Suppose $W$ was a neighborhood of $f(x)$ so $f^{-1}(W) \text{is a neighborhood of } x$. So $ f^{-1}(W) \cap A \not=\emptyset$ because $x$ is a limit point of $A$. Say $y\in f^{-1}(W) \cap A$. So $f(y)\in A$ and $f(y)\in W$. Now, if  $x\not\in A$ then $f(x) \not\in f(A)$ but $f(y)\in A$ so $f(y)\not = f(x)$. So $W$ intersects $f(A)$ in a point $f(y)$ which is different of $f(x)$
If $x\in A$, it may happen that $f$ is not injective and happen that  $f(x)=f(y)$ in which case I can't show that f(x) is a limit point of $f(A)$.
I've tried to came with a counter-example using constant functions on real functions. but it didn't works
What to do? any hints?
Comment: What if $f$ is a constant function? Would $f(A)$ have any limit points? What kind of set is $f(A)$?
Comment: @Andrew, hmmm, No! it will not have any limit points! I have already mentioned constant function in the question but while thinking I thought that the limit points of {$x$} are $x$ ! but I was wrong. So the constant function counts as a counter-example.
Answer: As the question was answered in comments and there is no one who added a correct answer to close the question. I'm adding this answer (I got the idea of the  answer from This comment)
The statement is false, here is a concrete example:
Let $f:\mathbb{R}\rightarrow \mathbb{R}$ where, $f(x)=2$ for all $x\in \mathbb{R}$. So $f$ is a constant function.
Note that we denote the set of limit points of $H$ by $H'$.
Let $A = [0,1]$.
So, $A' = \{0,1\}$.
$f(A)=f([0,1])=\{2\}$, but $f(A)'=\emptyset$ because {$2$} has no limit points as if $x\not = 2$  is a real number then there is always an interval $C$ containing $x$ but not contaning $2$.
So Although $1$ is a limit point of $A$, $f(1)=2$ is not a limit point of $f(A)=\{2\}$.
As the question was answered in comments and there is no one who added a correct answer to close the question. I'm adding this answer (I got the idea of the  answer from comments).
Comment: how A ' ={1,2} ? i thinks its should be {0,1,2}
Answer: $f(x)$ is a limit point of $f(A)$ if and only if every open neighborhood $V\subseteq Y$ of $x$ intersects $f(A)$.
We show the contrapositive. Assume that $f(x)$ is not a limit point of $f(A)$. Then there is an open neighborhood $V_0$ of $f(x)$ such that $V_0\cap f(A) = \emptyset$. Since $f:X\to Y$ is continuous, the preimage $f^{-1}(V_0)$ is an open neighborhood of $x$.
Claim:  $A \cap f^{-1}(V_0) = \emptyset$. Proof of claim: Suppose $z \in A \cap f^{-1}(V_0)$, then $f(z) \in f(A) \cap V_0$ contrary to assumption.
Now the claim implies that $x$ is not a limit point of $A$ and we're done.
Comment: Sorry, but limitpoint needs more: $y$ is limitpoint of $B$ if and only if every open neighborhood $V$ of $y$ contains an element $z$ with $z\neq y$. See http://en.wikipedia.org/wiki/Limit_point. Also look at Andrews comment.
Comment: $t$ is a limit point of $H$ iff every neighborhood $W$ of $t$ intersects $H$ in some point $y$ such that $x\not = y$. A counter example as mentioned in comments is the function $f:[1,2]\rightarrow \mathbb{R} $ where for every $x$, $f(x)=4$. here $1$ is a limit point of the domain $[1,2]$ but $f(1)=2$ is not a limit point of $f([1,2])=\text{{$2$}}$ since {$2$} has No limit points. You're using a different definition of a limit point different of the standard one. Thanx any way of the trial :)


Write to a CD from Delphi

Question:
Possible Duplicate:
How can I burn CD/DVD from delphi2007 win32

I am looking for a free and open source component or source code to write to a CD from Delphi 2007. Do you know any?
Comment: The image mastering api is the win32 native way; try googling for delphi +imapi
Comment: Do you need this tightly integrated in a Delphi app? The reason I ask is that IMAPI may be easier to drive from Python or vbscript than Delphi.
Comment: [JEDI Windows API blog](http://blog.delphi-jedi.net/2009/07/18/im-burning-baby/) with some interesting links and comments.
Comment: @TOndrej put that as an answer and you will surely accrue significant upvotes
Comment: @David Heffernan: Yes I have finished writing a project with Delphi 2007 and now I need to Write some data to a CD.
Answer: A quick search on Google reveals this JEDI Windows API blog post with some interesting links and comments. Perhaps it's an option to start with.
Comment: @mtoloo My experience with IMAPI is that it is very brittle and often hardware dependent. My IMAPI scripts work on only around 50% of the machines in the office. The problem may not be with the JEDI component and may in fact occur with anything that uses IMAPI.
Comment: It seems TDiscMaster from the above blog is a good class to work with writer, but the demo does not work for me!
**A generic error occurred.** error raises when trying to burn with the original demo! Has anyone worked with it?

Write to a CD from Delphi


Restify & Bluebird - how to pass an error from a catch block to restify error handler?

Question: I am working on a node js server, and using bluebird for promise implementation. I understand how to use promises, but my problem is what to do with the error returned from a promise. I tried the simple solution - just trowing the error again - but bluebird catch it, and the client never receive a response. Bellow is a demo code, to illustrate my question:
var restify = require('restify');
var Promise = require('bluebird');

var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});

server.get('/', function (req, res, next) {
    new Promise(function(resolve, reject){
        reject(new Error());
    }).then(function(res){
        res.send('hello');
    }).catch(function(e){
        throw e;
    });
});

server.on('uncaughtException', function (req, res, route, error) {
    console.log('error');
});

server.listen(7070, function () {
  console.log('%s listening at %s', server.name, server.url);
});

I am looking for a way to somehow pass the error to restify, so it will raise the uncaughtException event and I could handle it like any other uncaught exception. After searching this a bit, I found that I can simply do something like next(new InternalServerError()) and restify will raise an event for this specific error, but this is look a bit weird to me, so I am looking for a better way.
Answer: Here's a PoC that will rethrow any "possibly unhandled rejections". These will subsequently trigger Restify's uncaughtException event:
var Promise = require('bluebird');
var restify = require('restify');
var server  = restify.createServer();

server.listen(3000);

Promise.onPossiblyUnhandledRejection(function(err) {
  throw err;
});

server.get('/', function (req, res, next) {
  Promise.reject(new Error('xxx')); // no `.catch()` needed
});

server.on('uncaughtException', function (req, res, route, err) {
  console.log('uncaught error', err);
  return res.send(500, 'foo');
});

Comment: Thank you! this is look like what I wanted.
Comment: ok, this is only working if the error has no message in it - as restify render the response (using the error message) and then call the after event handler. This make all this solution a bit irrelevant for me...
Comment: I tried to run it on my machine, and it seems like the exception is not caught by restify domain. I add `process.on('uncaughtException',` and it caught the exception, but this is not much of help as I can't return something to the client. I will try to look later if I can find a way to use restify domain.
Comment: @omer fwiw, I'm using `email@example.com`, `firstname.lastname@example.com` and `firstname.lastname@example.com`
Comment: So it might be my restify version, I just now noticed I am using outdated restify (3.0.3). I will check latter, but if it work for you, this is probably the solution.


Prove convexity with hessian matrix

Question: I've got a function
$$f(x)=(x_1-1)^2+\sum_{i=2}^n (x_i-x_{i-1})^2\quad \text{with $x\in \mathbb{R}^n$}$$
I want to show that this is (strictly) convex, so I thought the best approach might be to look at $\nabla f^2(x)$ because $\nabla f^2(x)$ positive semidefinite/pos. def. iif $f(x)$ is convex/strictly convex.
It's pretty clear that the Hessian must be like this:
\begin{align*}
H_f = \begin{pmatrix}
4 & -2 & 0 & 0 &... & 0&0 &0\\
-2 & 4 & -2 & 0 &... & 0&0&0\\
0 & -2 & 4 & -2 &... & 0&0&0\\
...&...&...&...&...&...&...&...\\
0 & 0 & 0 & 0 &... & -2&4&-2\\
0 & 0 & 0 & 0 &... & 0&-2&4\\
\end{pmatrix}
\end{align*}
I can prove fast that this matrix is pos. semidef. (Using diagonal dominance). But I suspect that it's also pos. def..
My "slow" way would be to look at the minors and prove by induction.
Is there a fast way to prove it? Or should I use another method to prove convexity of $f$?
Comment: This is a duplicate of https://math.stackexchange.com/questions/3903369/prove-that-this-block-matrix-is-positive-definite/  though it takes some consideration to recognize that instead of $-2$ in one location, it has been shifted into two $-1$' in each case
Answer: Actually, for the Hessian matrix $H_f$ that you defined, the principal minors form a monotone increasing sequence.. If we denote them as $\Delta_1$, $\Delta_2$, $\ldots$, etc., then
$0 < \Delta_1 < \Delta_2 < \Delta_3 < \cdots < \Delta_k$ $\cdots$
As a consequence, it follows that
$\Delta_k > 0$ for all values of $k$.
Hence, by Sylvester's test for positive definiteness (a sufficient condition), we conclude that the Hessian matrix $H_f$ is strictly positive definite. $\blacksquare$
Comment: If my answer is satisfactory, you may kindly accept it, thanks!

Prove convexity with hessian matrix


how to extract parametres used by PCA in a first dataset and apply them to another one using Python

Question: I'm trying to verify if the transformation done by PCA is the same for 2 datasets, so I applied PCA for the training dataset and I want to extract parameters in order to apply them to a test dataset given that we are in unsupervised case (no labels)
Comment: If you want some help, show some code...
Answer: Use sklearn.decomposition.PCA.transform. This works just like any other fit-transform procedure in scikit-learn.


How do i disable data from select option on vue

Question: If the customer's status is dead, I want to disable the "healthy, little healthy and unhealthy" options. How should I write the checkHealth method?
<template v-for= "customer in customers">
  <select v-model="selected" @change="checkHealthy(customer.statu)">
    <option v-for="statu in status" :value="statu.id" >{{statu.name}}</option>
  </select>
</template>

Answer: If I understood you correctly, take a look at following snippet:

new Vue({
  el: '#demo',
  data(){
    return{
      status:[
          {id:1,name:'healthy'},
          {id:2,name:'little healthy'},
          {id:3,name:'unhealthy'},
          {id:4,name:'unknown'},
      ],
      selected:[],
      customers:[
        {name:'John', statu: "healthy"},
        {name:'Adam', statu: "unhealthy"},
        {name:'Cristiano', statu: "dead"},
        {name:'Alberto', statu: "little healthy"},
        {name:'Kevin', statu: "healthy"},
      ]
    }
  },
})

  <template v-for= "customer in customers">
    {{ customer.name }}
    <select v-model="customer.statu">
      <option v-for="statu in status"
              :value="statu.name"
              :disabled="customer.statu === 'dead' && statu.name !== 'unknown'">
        {{statu.name}}
      </option>
    </select>
  </template>

Comment: How can I do it without changing the data?
Comment: Your action is correct. This is exactly what i want. But how can I do it without adding a "dis" field inside the data?
Comment: you mean without using the `disable` attribute?
Comment: without using it in status array
Comment: did you check the answer, I updated it?


Incorrect syntax near the keyword 'group'

Question: Below is the update query which I am using for which I am receiving "Incorrect syntax near the keyword 'group'" error message.
update PORTFOLIO set p.PF_F_FREE4 = sum(CASE
WHEN c.FIXING_EXPR = 1  THEN
i.AMT_AFTER_XACT_DAT/(q.CUR_RATE)
ELSE
i.AMT_AFTER_XACT_DAT*(q.CUR_RATE)
END)
from PORTFOLIO p, ID_POS_CASH i, CURRENCY c, ID_CUR_QUOTE q
where p.PF_COD = i.PF_COD and   i.CUR_COD = c.CUR_COD
and c.CUR_COD = q.CUR_COD and p.PF_C_FREE20 NOT IN ( 'NO ACI PARTICIPATION', NULL)
and i.SETTLE_DAT = (select POS_MODIFIED_TO from ID_BAT_DAT)
and (i.AMT_AFTER_XACT_DAT <> 0 or i.AMT_CURRENT<>0)
group by i.CUR_COD having count(i.CUR_COD) >= 1

Can someone help me with the above?
Answer: If I'm not mistaken, your problem is having both the GROUP BY and the HAVING clauses in an UPDATE statement.
I believe the answer is to use an inline Select statement or to use CTE to solve your problem.
Here is a link to a similar issue (and solution):
Update with a Join, Group By, and Having


Vowpal Wabbit: best strategy for short text data like titles & kewords

Question: I am using Vowpal Wabbit 7.10.0 (VW) to learn and predict categories on text data. However, my text data for each record is not like an article or another decent-size text document, but rather a couple of sentences, like a title and subtitle and keywords.
I have around 10,000 labeled records I can use for validation, training, and testing, and around 1-2 millions unlabeled records. Its a multi-class problem with around 100 class labels, also imbalanced.
What would be the best pre-processing and input format to get the most of such data with VW?
My experience tells me that VW models should be sensitive to class imbalance problem. Here is another source that confirms it. Is that right?
As for choosing a model, I decided that I would rather take into account word combinations through n-grams then discover latent variables based on frequency counts (because texts are too short.) Besides, some texts tend to list a word for 100s of times (for SEO) in my data. Hence, I don't go TF-IDF. Is that right or not?
I guess, I can combine both n-grams and bag-of-words as different namespaces. But what classifier with what params to start with?
So far I tried it in three different ways of data pre-processing: (1) unprocessed text with only punctuation removed, (2) tokenization, lemmatization (not stemming), removed stopwords, (3) in addition to (2), bag of words, i.e. word:word_count format.
The results are not satisfactory with a very basic setting (this example used 16 classes, not 100):
  vw input.vw -c -k --passes 300 -b 24 --ect 16 -f model.vw
  vw input.vw -t -i model.vw -p preds.txt

Error rate is about 0.68 even on the training set.
I have some time limits to explore deeply all kind of setting, and really need quick and informative advise: what is the best pre-processing technique in my case, and what model implemented in the latest VW should I use. These two issues are related.
Comment: What are the "priority rule based" classifiers? Instance-based lazy learners, you mean, like k-NN?
Comment: @stats101 Could you elaborate, perhaps with an example of how to apply this algorithm to text data?
Comment: i am talking about rule  based approach
Comment: for very short texts priority rule based  classification works the best, short texts generally can be classified using a  very few rules hence quicker and have better error rate then going through all the rigorous ML tasks.
Answer: Here are some tips for enhancing the performance of VW models:

Shuffle the data prior to training.  Having a non-random ordering of your dataset can really mess VW up.
You're already using multiple passes, which is good.  Try also decaying the learning rate between passes, with --decay_learning_rate=.95.
Play around with the learning rate.  I've had cases where --learning_rate=10 was great and other cases where --learning_rate-0.001 was great.
Try  --oaa 16 or --log_multi 16 rather than --ect 16.  I usually find ect to be less accurate.  However, oaa is pretty slow.  I've found --log_multi to be a good compromise between speed and accuracy.  On 10,000 training examples, --oaa 16 should be fine.
Play with the loss function.  --loss_function=hinge can sometimes yield large improvements in classification models.
Play with the --l1 and --l2 parameters, which regularize your model.  --l2 in particular is useful with text data.  Try something like --l2=1e-6.
For text data, try --ngram=2 and --skips=2 to add n-gram and skip grams to your models.  This can help a lot.
Try --autolink=2 or --autolink=3 to fit a quadratic or cubic spline model.
Try ftrl optimization with --ftrl.  This can be useful with text data or datasets with some extremely rare and some extremely common features.
Try some learning reductions:

Try a shallow neural network with --nn=1 or --nn=10.
Try a radial kernel svm with --ksvm --kernel=rbf --bandwidth=1. (This can be very slow).
Try a polynomial kernel svm with  --ksvm --kernel=poly --degree=3. (This can be very slow).
Try a gbm with --boosting=25.  This can be a little slow.

VW is extremely flexible, so it often takes a lot of fine tuning to get a good model on a given dataset. You can get a lot more tuning ideas here: https://github.com/JohnLangford/vowpal_wabbit/wiki/Command-line-arguments
Regarding the post you linked to: that person used vw with squared loss on an unbalanced classification problem.  That's a silly thing to do, and pretty much guarantees that any linear model will always predict the dominant class.  If you're worried about class balance, VW supports weights, so you can over-weight the rarer classes.
Edit: You have 100 classes and 10,000 training examples?  That's an average of 100 observations per class, which isn't that many to learn from, no matter what model you use.
Comment: so how many observations required per class
Comment: @stats101 I would want 1000 observations at least for the rarest class.
Comment: see: vowpal wabbit's hyperopt: https://github.com/VowpalWabbit/vowpal_wabbit/pull/867


Como "Zipar" arquivos ou diretórios no codeigniter

Question: Eu já vi na documentação, mas eles falam de maneira muito rasa, e o entendimento não fica bom. Então, alguém pode me explicar de uma forma mais prática de como eu posso zipar arquivos no codeigniter? obrigado.
Link para a documentação: https://www.codeigniter.com/user_guide/libraries/zip.html
Eu não entendi quase nada, a respeito do processo de zipagem.
Comment: Será interessante você [edit] a pergunta e adicionar o link para a documentação, colocando os exemplos de código que ela apresenta aqui, descrevendo o que você não estendeu.
Answer: Vou tentar explicar o que tem na documentação:
1 - Você deve carregar a lib zip no seu controller.
<code>$this->load->library('zip');
</code>
2 - Você declara os valores que vai utilizar
<code>$filepath = 'mydata1.txt'; // Diretório do Arquivo
$data = 'A Data String!'; // Conteúdo do Arquivo
</code>
3 - Você vai utilizar o método: add_data
<code>$this->zip->add_data( $filepath, $data ); // Essa função vai receber 2 parâmetros, o primeiro é o caminho do arquivo e o segundo é o conteúdo desse arquivo.
</code>
Agora se você já tem o arquivo em algum lugar no seu servidor, você vai utilizar a função abaixo:
<code>$this->zip->archive( $path, $archive_filepath ); // Primeiro parâmetro você vai passar o caminho do arquivo, o segundo é opcional caso queira que o zip tenha outro nome ou salvar em outro local.
</code>


Maximum likelihood estimation using R

Question: I have a multiple linear regression, that I want to estimate using a MLE approach. I would like to make the fit using a Beta distribution, with parameters u and v. How can I do this using R?
Answer: Beta regression is implemented in betareg CRAN package, see [1], and also CRAN webpage.
[1] https://cran.r-project.org/web/packages/betareg/vignettes/betareg.pdf

Maximum likelihood estimation using R


Is multicollinearity implicit in categorical variables?

Question: I noticed while tinkering with a multivariate regression model there was a small but noticeable multicollinearity effect, as measured by variance inflation factors, within the categories of a categorical variable (after excluding the reference category, of course).
For example, say we have a dataset with continuous variable y and one nominal categorical variable x which has k possible mutually exclusive values. We code those $k$ possible values as 0/1 dummy variables $x_1, x_2,\dots ,x_k$. Then we run a regression model $y = b_0 + b_1x_1 + b_2x_2 + \dots + b_{k-1}x_{k-1}$. The VIF scores for the $k-1$ dummy variables turn out to be non-zero. In fact, as the number of categories increases, the VIFs increase. Centering the dummy variables doesn't appear to change the VIFs.
The intuitive explanation seems to be that the mutually exclusive condition of the categories within the categorical variable causes this slight multicollinearity. Is this a trivial finding or is it an issue to consider when building regression models with categorical variables?
Answer: I cannot reproduce exactly this phenomenon, but I can demonstrate that VIF does not necessarily increase as the number of categories increases.
The intuition is simple: categorical variables can be made orthogonal by suitable experimental designs.  Therefore, there should in general be no relationship between numbers of categories and multicollinearity.
Here is an R function to create categorical datasets with specifiable numbers of categories (for two independent variables) and specifiable amount of replication for each category.  It represents a balanced study in which every combination of category is observed an equal number of times, $n$:
trial <- function(n, k1=2, k2=2) {
  df <- expand.grid(1:k1, 1:k2)
  df <- do.call(rbind, lapply(1:n, function(i) df))
  df$y <- rnorm(k1*k2*n)
  fit <- lm(y ~ Var1+Var2, data=df)
  vif(fit)
}

Applying it, I find the VIFs are always at their lowest possible values, $1$, reflecting the balancing (which translates to orthogonal columns in the design matrix).  Some examples:
sapply(1:5, trial) # Two binary categories, 1-5 replicates per combination
sapply(1:5, function(i) trial(i, 10, 3)) # 30 categories, 1-5 replicates

This suggests the multicollinearity may be growing due to a growing imbalance in the design.  To test this, insert the line
  df <- subset(df, subset=(y < 0))

before the fit line in trial.  This removes half the data at random.  Re-running
sapply(1:5, function(i) trial(i, 10, 3))

shows that the VIFs are no longer equal to $1$ (but they remain close to it, randomly). They still do not increase with more categories: sapply(1:5, function(i) trial(i, 10, 10)) produces comparable values.
Answer: You have the constraint that you can see is inherent in multinomial distributions, namely that one and only one of the $x_i$s will be 1 and all the rest will be 0.  So you have the linear constraint $\sum x_i =1$.  That means say $x_1 =1 - \sum x_i$  where the sum is taken over $i \neq 1$.  This is the collinearity effect that you are noticing.  There is nothing unusual or disturbing about it.
Comment: I do not understand what multinomial distributions have to do with this situation. Could you explain?


How to set the state of a useState hook on page load?

Question: I am trying to create a responsive nav. It has a _ functions:

Display nav links on screen widths > 768px on page load
Not display nav links on screen widths < 768px on page load
Close the nav if left unopened on smaller screen when switched to larger screens (put simply, if a user opens the nav links on mobile, switches to a larger screen size, and then back to mobile, the nav links should be hidden again)

I got 99% of this accomplished, but I think I'm doing it in a hacky way because when I am on smaller screens, the nav links flash for a brief moment, then dissapear. This is obviously not what I am looking for.
Below is a condensed, not styled snippet for easier debugging:
export const Nav = () => {
  const [showNavOnClick, setShowNavOnClick] = useState(false)
  const [hamburgerOpen, setHamburgerOpen] = useState(false)
  const [showNavOnScreenSize, setShowNavOnScreenSize] = useState(true)

  const toggleMenu = () => {
    setShowNavOnClick(!showNavOnClick)
    setHamburgerOpen(!hamburgerOpen)
  }

  useEffect(() => {
    // This line solves all 3 goals, but on page load, the nav links appear, then dissapear in a split moment.
    if (window.innerWidth < 768) setShowNavOnScreenSize(false)

    const handleResize = () => {
      if (window.innerWidth > 768) {
        setShowNavOnScreenSize(true)
        setShowNavOnClick(false)
      } else if (window.innerWidth < 768) {
        setShowNavOnScreenSize(false)
      }
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  return (

      Home
      <button onClick={toggleMenu}>*</button>

        About

  )
}

Below is a video that shows the glitch:

When I add const [showNavOnScreenSize, setShowNavOnScreenSize] = useState(window.innerWidth >= 768), I get an error of window is not defined
Answer: You can fix this by changing the default value of the state to be calculated from the width, instead of a hardcoded true:
const [showNavOnScreenSize, setShowNavOnScreenSize] = useState(window.innerWidth >= 768)

If necessary, you can set the default values for your other states in a similar way.
EDIT: Alternatively, try using a layout effect instead so that the rerender is synchronous:
const [showNavOnScreenSize, setShowNavOnScreenSize] = useState(true)

useLayoutEffect(() => {
    if (window.innerWidth < 768) setShowNavOnScreenSize(false)
    // ...

Comment: I get an error of `window is not defined`. I updated my post to show a picture with that error message.
Comment: Are you using server side rendering?
Comment: I am using Next.js, but everything is being rendered client side
Comment: Looks like that worked, but I'm not sure why.


How to compute the following limit: $L= \lim\limits_{ x\to + \infty} \left[ (x+4)^{1+\frac{1}{x}} - x^{1+\frac{1}{x+\cos x}} \right]$

Question: I'm wondering how to compute the following limit: $$\begin{align*}
L= \lim\limits_{ x\to + \infty} \left[ (x+4)^{1+\frac{1}{x}}  - x^{1+\frac{1}{x+\cos x}} \right]
\end{align*}$$
I know that if a limit$\lim\limits_{x\to + \infty} f(x)-g(x)=A$ exists, then $x\to +\infty \implies f(x) \sim g(x)$ .
Here I suppose $(x+4)^{1+\frac{1}{x}}=f(x),x^{1+\frac{1}{x+\cos x}}=g(x)$ , we  have $$\begin{align*}
\lim\limits_{x\to + \infty} \exp\left( \ln \frac{f(x)}{g(x)} \right) &=\exp\left(\frac{ x\ln\left( 1+\frac{4}{x} \right)+\cos x \ln (x+4)}{x(x+\cos x)} \right) \\ &= \exp\left( \frac{\frac{\ln\left( 1+\frac{4}{x} \right)}{x}+ \frac{\cos x \ln(x+4)}{x^{2}}}{\left( 1+\frac{\cos x}{x} \right)} \right) \\ &= \exp(0)=1
\end{align*}$$
Thus I can't say $L$ doesn't exist. That is,  $L$ can exist, and it can also not exist.
Then I know that if $\lim\limits_{x\to +\infty}f(x)=1$ ,and $f(x)$ is differentiable, then $x\to +\infty \implies f(x)-1 \sim \ln(f(x))$ so I change the original limit to be $$\begin{align*}
L=\lim\limits_{x\to +\infty} x^{1+\frac{1}{x+\cos s}} \left( \frac{(x+4)^{1+\frac{1}{x}}}{x^{1+\frac{1}{x+\cos x}}}-1 \right) \sim \lim\limits_{ x\to + \infty} \left( x^{1+\frac{1}{x+\cos x}} \right) \ln\left( \cfrac{(x+4)^{1+\frac{1}{x}}}{x^{1+\frac{1}{x+\cos x}}} \right)
\end{align*}$$
Then I got stuck here. Any help with this? Thank you.
Answer: As $x\to+\infty,$
$$f(x)=x^{1+\frac1x}e^{\left(1+\frac1x\right)\ln\left(1+\frac4x\right)}=x^{1+\frac1x}e^{\frac4x+o\left(\frac1x\right)}=x^{1+\frac1x}\left(1+\frac4x+o\left(\frac1x\right)\right)$$
and
$$g(x)=x^{1+\frac1x}e^{\frac{\ln x}x\left(\frac1{1+\frac{\cos x}x}-1\right)}=x^{1+\frac1x}e^{o\left(\frac1x\right)}=x^{1+\frac1x}\left(1+o\left(\frac1x\right)\right)$$
hence
$$f(x)-g(x)\sim4x^{\frac1x}\to4.$$
Answer: A much simpler approach is to trust the usual laws of algebra of limits and use them with a combination of standard limits.
Let us divide and multiply the given expression by $x$ to get $$x\left[\left(\frac{x+4}{x}\right)^{1+1/x}x^{1/x}-x^{1/(x+\cos x)} \right] $$ This is of the form $x(A-B) $ where both $A, B$ tend to $1$. And therefore the limit of the expression is same as that of $$x(\log A-\log B) $$ The above expression is $$x\left[\frac{\log x} {x} +\left(1+\frac{1}{x}\right)(\log (x+4)-\log x) - \frac{\log x} {x+\cos x} \right] $$ or $$\cos x\cdot\frac{\log x}{x+\cos x}+4\cdot\frac{x+1}{x}\cdot \frac{x}{4}\log\left(1+\frac{4}{x}\right) $$ The first term tends to $0$ and second term tends to $4$ so that the desired limit is $4$.
In the last step we used the following standard limits $$\lim_{x\to\infty} \frac{\log x} {x} =0,\lim_{t\to 0}\frac{\log (1+t)}{t}=1$$ The reduction from $x(A-B) $ to $x(\log A-\log B) $ is based on the limit $$\lim_{t\to 0}\frac{e^t-1}{t}=1$$ (prove this).
Answer: (A) Calculus Way :
Take $y=1/x$.
$L = \lim\limits_{ x\to + \infty} \left[ (x+4)^{1+\frac{1}{x}} - x^{1+\frac{1}{x+\cos x}} \right] = \lim\limits_{ y \to 0} \left[ (1+4y)^{1+y}/(y)^{1+y} - 1/(y)^{1+\frac{1}{x+\cos x}} \right]$
$L = \lim\limits_{ y \to 0} \left[ \frac { (1+4y)^{1+y}(y)^{1+\frac{1}{x+\cos x}} - (y)^{1+y} } { (y)^{1+y}y^{1+\frac{1}{x+\cos x}} } \right]$
This is $0/0$ , hence use LH rule to Differentiate the terms & get the Answer. Numerator will give $4$ when Differentiating $4y$ , which will be missing from Denominator. Hence Answer "should" be $4$.
It looks very cumbersome to use LH rule. Though it "should" give the Answer $4$ , it will take time & effort to make the necessary Calculations. I will give the alternate Intuitive Way which "should" give Equivalent Answer.
(B) Intuitive Way :
When $x \rightarrow \infty$ , $x+\cos(x) \approx x$ , hence $1+1/(x+\cos(x)) \approx 1+1/x \approx 1$
Both Exponents are $1$ , hence $L=(x+4)^1-(x)^1=4$
No other value will be Consistent.
(C) Puisuex Series :
It seems that the Series Expansion (where we are allowing terms with $1/x$ & other Negative Powers) is given by the Puisuex Series :
$4+\frac{4\log(x)+1}{x}+O((\frac{1}{x})^2)$
[[ according to wolfram ]]
Substituting $y=1/x$ & Plugging in $y=0$ , we will get $L=4$
Comment: @Prem Note I said neither that the limiting value of $4$ is incorrect nor that there was an issue of rigor.  The issue is that the method _you seem to be implying in (B)_ is itself invalid and a common error among students.  There is a value to non-rigorous "intuitive" solutions, but we need to draw the line when the most likely _intuition_ you might be imparting is incorrect.
Comment: @user2661923 The simplest example I can think of is that for any real $c$, $$\lim_{x\to\infty} \left(x^{1+c/(x\ln x)} - x^1\right)=c$$
Comment: The method in (B) smells of $f \sim g \implies f-g\to 0$ which is well-known to be false.  In particular, the method cannot show "if the limit exists, it is $4$" which is how I interpret the claim "no other value will be consistent."
Comment: [1] I verified that the Answer is $4$ via wolfram & other tools , @BrianMoehring , thus my usage of quotes for all instances of "should" , & then the cumbersome calculations were left over to OP , once it was made $0/0$ format. [2] I am not claiming (B) is rigorous , hence the Descriptive Title "Intuitive Way" !!
Comment: @BrianMoehring I find your comment very interesting, especially as I am generally ignorant in this area.  If it isn't too much trouble, could you provide a *similar* counter example, where intuition would suggest that the limit is some value $~A,~$ and where the limit does exist, but actually equals some value $~B \neq A~?$


Como inserir um else para exibir mensagem no caso de não ter arquivos para upload

Question: Código
<?php
$files = $obj->field('upload');

foreach ($files as $file)
  {
    $file_url = get_attached_file($file['id']);
    echo '' . $file["post_title"] . '';
    echo '
';
  }
?>

Mensagem de erro quando não tem anexo:

Warning: Invalid argument
  supplied for foreach() in
  /var/www/html/wp-content/plugins/pods/components/Templates/Templates.php(500)
  : eval()'d code on line 8
Comment: A variável `$obj` é uma instância de que classe? Poste um pouco mais do código.
Comment: Verifique se `$files` tem algum elemento, pode usar o `count()` ;)
Comment: Esse é a parte do codigo que chamo dentro do template do pods
Comment:

field('upload');

  foreach ( $files as $file ) {
    $file_url = get_attached_file($file['id']);
    echo '' . $file["post_title"] . '';
    echo '';
  }
  ?>

{@objeto}
{@abertura}
{@valor_da_gru}
{@fase}
Comment: eu nao saco muito por isso tenho dificuldades ate de explicar.
Comment: @Rodrigo, o que a função emtpy faz é verificar se uma variável está vazia, literalmente - [empty](http://php.net/manual/en/function.empty.php)
Answer: Para o seu caso, acredito que é bem simples:
<?php

$files = $obj->field('upload');
if (!empty($files)) {
    foreach ( $files as $file ) {
             $file_url = get_attached_file($file['id']);
             echo ''
                  . $file["post_title"]
                  . '';
                  . '
';
    }
} else {
   echo "Não há arquivos enviados!";  die();
}

Mas eu sugiro fazer algo mais bem trabalhado, usando exceção:
function listFiles()
{
  $file = func_get_args(0);
  try {

      if (empty($file)) {
         throw new Exception("Não há arquivo(s) enviado(s)!");
      }
       $content = '';
      foreach ( $files as $file ) {
         $file_url = get_attached_file($file['id']);
         $content.= ''
                    . $file["post_title"]
                    . '';
                    . '
';
      }
      return $content;

  } catch (Exception $e)  {
     return $e->getMessage();
  }
}

echo listFiles($obj->field('upload'));

Comment: Obrigado do seu Código eu cheguei ao empty.
Answer: Utilize um isset ou empty para verificar que essa variável/array possui valores.
<?php
$files = $obj->field('upload');

if(!empty($files)){
foreach ($files as $file)
  {
    $file_url = get_attached_file($file['id']);
    echo '' . $file["post_title"] . '';
    echo '
';
  }
} else {
 print "Nenhum ficheiro selecionado";
}
?>

Answer: Você pode fazer uma verificação simples em $files:
<?php

$files = $obj->field('upload');
if (count($files)) {
    foreach ( $files as $file ) {
    $file_url = get_attached_file($file['id']);
    echo '' . $file["post_title"] . '';
       echo '
';
    }
}

Comment: Ainda em tempos falei disso, um isset/empty seria mais proveitoso.
Comment: Eu testei e apresentou um erro:
Parse error: syntax error, unexpected '<' in /var/www/html/wp-content/plugins/pods/components/Templates/Templates.php(500) : eval()'d code on line 15
Comment: Só deixe claro para o Rodrigo, que usando `count()`, ele não eximirá os arquivos, mas irá listar todos os arquivos quando tiver pelo menos um na coleção.
Comment: Bem galera eu resolvi com ( empty ) Ela serve para saber se uma variável existe

field('upload');
  if(!empty($files)):

 foreach ( $files as $file ) {
  $file_url = get_attached_file($file['id']);
  echo '' . $file["post_title"] . '';
  echo '';
  }

else:

    echo "No content found.";

endif;
  ?>


Can i install Vmware ESX 3.5 on Dell Inspiron 560s Desktop - S241203IN8 - with Intel E7500 Processor

Question: I am about to purchase DELL Inspiron 560s Desktop - S241203IN8. My purpose of buying this machine is to be able to install and learn VMware ESX 3.5 (VMware Infrastructure).
Here is the two links, one gives you the configuration details of the hardware, and the other gives you the details about the Intel Processor inside the machine.
Dell Hardware link - Inspiron 560s Desktop
Intel link for processor specification
Only concern I have is regarding Intel VT-x availability. It says 'See SPEC Detais" under Advanced Technology category.
There are three types in this, so how can I be sure that the processor in that Dell configuration is VT-x capable?
Is there a way to check the "SPEC code" in Dell configuration ?
Answer: It's not exactly built for ESX and it's not on the HCL but it should be fine, to find out if it's VT-X capable contact Dell first and ask then if it's 'Windows 7 Virtual XP mode compatible' (which is the same thing but is less likely to confuse them) - get their any response in writing.
Comment: First, I am a very happy Dell customer and nothing more: My personal experience with Dell Sales is that they *do not know* processor specs at this level.  I would not trust them, as I did once when I purchased the only Core 2 Quad Intel makes that doesn't support VT - and, yes, the sales guy said that it did.  Buyer beware.
Comment: I agree, so long as you get it in writing you're covered.
Answer: the SPEC code warning means thhat there are motherboards that will not support VT even though the chip will.  It would not in the least bit suprise me if dell's motherboard does not support VT.  Dell is notrious for disabling parts they don't deem required by a desktop OS. (the disabling of core i7 turbo mode on the studio XPS line is the latest example that comes to mind).  If you're set on dell make sure you can return it without paying a fee if it's not up to spec.  Chopper suggestes getting their response in writing which might help but with dell is no guarantee of their compliance,
Comment: wow, didn't know that about the xps's
Answer: I use wikipedia to check processor specs.
See page here: List of Intel Core 2 Processors
Search for:Core 2 E7500 and you will find the processor.
However, there are 2 different processors, one with VT one without.
You need the one with the part number ending in ML (See note above the table there).
I would do my best to try to cross reference whatever numbers you can find and/or some feature that Dell lists (perhaps a CPU speed or something).
It's a bit of a gamble.
On the bright side, if you have the time etc (and please confirm with Dell yourself) - they usually have a 21-day return for full refund policy, where they pay the shipping.
I've done that in the past with no problems at all.  So, you could get the machine and check the BIOS when you boot it - if no VT, then return it.
Comment: See Jim B's answer below also: great information.  Again, I have found the most important assurance is that you can return without having to pay shipping, etc. as Jim below said.


Creating Javascript Object without explicitly defining the keys?

Question: Today I saw a piece of code which I have never seen before:
var a = 1;
var b = 2;
var c = { a, b };

This creates an object (assigned to c) which contains two keys, those are the names of the variables, and the values are the variable's values, like this:
{
    a: 1,
    b: 2
}

Is this something normal? I couldn't find anything related to this or creating objects this way. I tested it on chrome and it worked fined, but I am not sure if this will work in every browser.
I would expect to create the object this way:
var c = { a: a, b: b };

Comment: Yes, I did that! :D
Comment: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring has some examples
Comment: I'm sure this question has already been asked. Who finds the original one?
Comment: @nicael what about you? :D
Answer: This is part of the ES6 object shorthand, where you may use variables from the current scope to declare a property within an object (literal) with the same name and value as that variable.
That is, c = {a, b} expands to c = {a: a, b: b} so long as a and b are both in the current scope.
The MDN documentation goes into more detail here.


Set PW never expire for a list of server

Question: I am looking to set "password never expires" for a local Windows user account, for a list of servers in a text file. So far, I found this command line below, but it only works local on single computer. How can I incorporate this into a VBscript, PowerShell, or batch file to apply on a list of servers in a text file?
WMIC USERACCOUNT WHERE "Name='accountname'" SET PasswordExpires=FALSE

Answer: This code should do it:
# 1. Define in-line array of servers
$ServerList = @('localhost', 'localhost', 'localhost');
# 2. Define account name
$AccountName = 'test';

# 3. For each server, set the account to expire
foreach ($Server in $ServerList) {
    $Account = Get-WmiObject -ComputerName $Server -Class Win32_UserAccount -Filter "Name = '$AccountName'";
    $Account.PasswordExpires = $false;
    [void] $Account.Put();
}

If you want to import a text file that contains the server names, you can simply change the first line to this:
$ServerList = Get-Content -Path c:\path\to\text\file.txt;

An alternative method would be to use Invoke-Command, however this requires that you first configure PowerShell Remoting in your environment.
# 1. Define in-line array of servers
$ServerList = @('localhost', 'localhost', 'localhost');
# 2. Define the block of code to deploy (a PowerShell ScriptBlock)
$ScriptBlock = {
    $AccountName = 'test';
    $Account = Get-WmiObject -Class Win32_UserAccount -Filter "Name = '$AccountName'";
    $Account.PasswordExpires = $false;
    [void] $Account.Put();
};

# 3. Deploy the ScriptBlock to the array of servers
Invoke-Command -ComputerName $ServerList -ScriptBlock $ScriptBlock;

To configure PowerShell Remoting, run the Enable-PSRemoting -Force command on each computer. You can also use Active Directory Group Policy to enable PowerShell Remoting / Windows Remote Management (WinRM).
Answer: wmic can be run against remote hosts via the /node parameter:
wmic /node:HostA,HostB useraccount where "Name='accountname'" ...


Playing both the pc sound and mic playback through headphones

Question: I have downloaded this marvelous program called "Effectogram" in order to easily and rapidly (performance-wise) control:

microphone input volume
microphone output volume
playback reverberation
playback dry sound

I have a wide list of drivers to choose from, but all of them seem'd to playback with a delay. All of them except for the "ASIO" driver.
I could literally play with a flute, but instead of hearing the original physical flute's sound, hearing amplified and enhanced sounds from my DJ headphones ("Numark Red Wave"). And this is only possible by virtue of the ASIO driver.

The problem is that I cannot hear other sounds from the PC, while using ASIO as it seems that it roots it through my laptop speakers instead.
If I could just somehow manage to play beats and bgm(s) my life would suddenly become happier.

Using "JACK" didn't help regarding the delay. So.. the enigma is how can I achieve this, playing sounds form my PC and the ASIO Mic-in / Mic-out both through my headphones?
Comment: This seems pretty specific to the program and may be out-of-scope for this stack. The problem is with Effectogram right?

Someone may be able to point you in the right direction if you give a bit more info about your machine though - are you Win10? OSX? Vivid Vervet?
Comment: The program is clearly not in Effectogram O_O That happens if I attend to use ASIO from FL Studio as well. It is the driver that doesn't roots the pc stream.
Comment: The problem is called "latency". Supposedly ASIO drivers have lower latency than other drivers but they still create a problem.
Comment: However, it is not necessarily to be due to high latency as some drivers just have bigger buffer in order to process the sound qualitatively.
Answer: You need an audio interface (hardware device with mic/line inputs/output and a USB or FireWire computer connection) that allows both "direct monitoring" (Focusrite's description), and has a software mixer that lets you listen to both the input AND other audio from your computer.
I think most interfaces these days have direct monitoring, but I'm not sure how common the mixing feature is.  I used to use a TASCAM US-144, and I don't think it allowed you to monitor external input, AND an arbitrary audio source from your computer at the same time.  Currently, I use a Focusrite Pro-40 which definitely does allow what you want.
Comment: I've advanced in this area of expertise. Can say that Virtual Audio Cable, The newest version of ASIO (with some unneeded modules turned off) and a recording software such as Voxengo and a mixer is an interface capable of mixing ASIO stream with directX rec. playback driver (stereo mix for other computers).


How are Field API fields transfered from config entities to content entities?

Question: So I am creating a content and config entities - exactly like node and node type.
After I've created them I've noticed that I can add fields to the config entities, which is ok but then I've realised that I'm working with two separate entity types, so I wonder how re Field API fields "transferred" from the config entity to the content entity?
Comment: What do you mean by transferred? What exactly happens and what you expected?
Answer: This works essentially the same way as in Drupal 7.
Config entities like node types, custom block types, vocabularies and so on are used as storage and are then exposed as bundles of nodes, custom blocks, taxonomy terms, ...
There's not much magic involved, you can see what happens in e.g. node_entity_bundle_info() and taxonomy_entity_bundle_info(), so the modules have to do that part themself, you'll notice small differences there e.g. how they handle the bundle label.
The bundle_of annotation key was added recently that allows to explicitly define that relationship between two entity types, but it's currently only used by field_ui_entity_operation_alter() to automatically add operation links to the listings of node types, vocabularies and so on.
While it looks like you add the fields to config entities, you really add the field to the corresponding content entity for the given bundle. Just like it already was in 7.x, the only thing that really changed is all those different things now use the same API for storage, in 7.x, they were stored in separate tables and didn't have anything in common.


need to optimize specific function in order to have best fitted curve

Question: I'm looking for best fitted curve that will match with a specific formula. The parameters A and B need to be optimize
# X and Y are my datasets Y depend of X
X=c(73,33,201,90,1513,1312,1044,929,836,657,104,22)
Y=c(2.89,6.11,3.57,4.03,0.16,0.00,1.41,0.00,2.13,6.16,2.85,5.08)

# X and Y plot give us
plot(X,Y, main="Y function of X",pch=6,xlab="X", ylab="Y",col='black')

#Type of curve that I need
curve(0.07*90*(1-(x/(x+exp(5-0.001*x)))), add = T,col="blue",lw=3,lty=2)

#I want therefore to optimize the parameters A and B in order to have the best fitted curve according to this formula that fit better with my data
curve(0.07*90*(1-(x/(x+exp(B+A*x)))), add = T, col="blue",lw=3,lty=2)

# Please help `enter code here`

Comment: See for example: https://datascienceplus.com/first-steps-with-non-linear-regression-in-r/
Comment: have you tried playing around with the `optimize()` and `optim()` functions?
Answer: You can use nls() to optimize the function using non-linear least squares. For example
nls(Y~0.07*90*(1-(X/(X+exp(B+A*X)))), data.frame(X,Y), start=list(A=.001,B=5))

returns
Nonlinear regression model
  model: Y ~ 0.07 * 90 * (1 - (X/(X + exp(B + A * X))))
   data: data.frame(X, Y)
        A         B
0.0004154 5.1653460
 residual sum-of-squares: 30.27

Number of iterations to convergence: 8
Achieved convergence tolerance: 8.472e-06


dúvida com abrir e fechar conexão

Question: gostaria da ajuda de vocês com a conexão abaixo, quando fecho tenho o seguinte erro abaixo, estou fazendo da forma correta? com relação a abertura e fechamento da conexão?
minha pool
public class MysqlConnectionPool {
private final DataSource dataSource;

public MysqlConnectionPool() {
    MysqlConnectionPoolDataSource pool = new MysqlConnectionPoolDataSource();
    pool.setUrl("jdbc:mysql://*********.sa-east-1.rds.amazonaws.com:3306/*********?autoReconnect=true&useSSL=false");
    pool.setUser("*********");
    pool.setPassword("*********");

    this.dataSource = pool;
}
public Connection getConnection() throws SQLException {
    Connection connection = dataSource.getConnection();
    return connection;
}}

Exemplo de um DAO que tenho, todo os outros seguem o mesmo padrão
public class UsuarioDAO {
ExceptionHandling capturaException = new ExceptionHandling();
GeradorURL geradorURL = new GeradorURL();
MysqlConnectionPool mysqlConnectionPool;
private final Connection connection;

public UsuarioDAO() throws SQLException {
    this.connection = new MysqlConnectionPool().getConnection();
}

public List<UsuarioDTO> seleciona() throws SQLException {
    List<UsuarioDTO> results = new ArrayList<>();
    String sql = "select aqui";
    try (PreparedStatement stmt = connection.prepareStatement(sql);
            ResultSet resultSet = stmt.executeQuery()) {

        while (resultSet.next()) {
            results.add(populaConta(resultSet));
        }
        resultSet.close();
        stmt.close();
    } catch (SQLException e) {
        capturaException.ExceptionHandlerController(e);
        throw new RuntimeException(e);
    } finally {
         connection.close();
    }
    return results;
}}

erro

02-Jan-2018 15:49:16.027 SEVERE [http-nio-8084-exec-5]
  org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service()
  for servlet [dispatcher] in context with path [/Head2Head] threw
  exception [Request processing failed; nested exception is
  java.lang.RuntimeException:
  com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
  No operations allowed after connection closed.] with root cause
  com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
  No operations allowed after connection closed.
Answer: Provavelmente você fechou a conexão e depois tentou usa-la. Por isso do error !
Fecha todas as conexão dentro finally  isso pode ajudar.
  finally {
     connection.close();
     resultSet.close();
     stmt.close();
  }

Onde você está chamando ou usando a sua classe UsuarioDAO.java?

dúvida com abrir e fechar conexão


Data transparency in a meta-analysis

Question: In a meta-analysis project, we extracted data from published papers. Now, we are going to submit it in a journal. But, in the Declarations section, the journal requires a statement for "Availability of data and material (data transparency)". What will be the availability of data for a meta-analysis manuscript?
Also, another requirement in the Declarations section is Code availability (software application or custom code). We used Stata version 14.1. But we wrote our own codes. What will be the code availability in our case?
Answer: If you are presenting the data in a forest plot then everything you used is visible in that plot since it is conventional to include the effect size and confidence interval for each study in that plot. So I would just state that all the data is included in the paper. You will also presumably have a list of the papers which you extracted the data from so readers can check it really is the data from the primary studies.
If your journal has supplementary material for papers then put the do files there. If they do not then either (a) do not include them and wait to be asked (b) provide a link to your GitHub repository or wherever they can find the code.

Data transparency in a meta-analysis


While porting project from 64bit to 32 bit : float changed to long double gives error for %f

Question: As while porting 64 bit project to 32 bit project for making range compatible changed:
typedef float float_t;

to
typedef long double float_t;

All goes perfect but error is coming in all printf specifier for %f. I don't want to change to %Le in whole code.
Please suggest any generic solution so it is campatible to both 32 bit and 64 bit system in c language.
Comment: Why are you changing from float to long double anyway ? This is not necessary or meaningful when porting between 32 and 64 bit architectures.
Comment: Please tag your question with C or C++ depending on what language you're working with.
Answer: You are going to have to use a #define for the format string for the float / long double, or use a special formatting function
Comment: Following the lead of `inttypes.h`, you could define `PRIf64` to either `"f"` or `"Lf"`.  Usage: `printf( "value=%9.2" PRIf64 "\n");`
Answer: You did not sepcify what language you are using.  In C++ std::cout is preferred over printf and it will give you type-correct formatting.
If you are using C, you could define a macro based on the platform for both the type of the floating point variables and the formatting string for printf


Is there a way to add a youtube playlist instead of youtube video in header of twenty seventeen template?

Question: The option of adding a youtube video is possible as the background video of the header in the twenty seventeen template on wordpress. I know that simply by pasting the URL of the playlist it will not load but I was wondering if anyone has found a way to load a playlist or random videos through the header?
Answer: You can edit the files
wp-includes\js\wp-custom-header.js
wp-includes\js\wp-custom-header.min.js
and add the listtype and list to the playerVars.
<code>            playerVars: {
                autoplay: 1,
                controls: 0,
                disablekb: 1,
                fs: 0,
                iv_load_policy: 3,
                loop: 1,
                modestbranding: 1,
                playsinline: 1,
                rel: 0,
                listType: 'playlist',
                list: 'youlistID',
                showinfo: 0
            }
</code>


What is a quick proof that $f \in \mathbb{C}[X_1,\dotsc,X_n]$ is determined by its induced function on $\mathbb{C}^n$?

Question: For $f \in \mathbb{C}[X_1, \dotsc, X_n]$, we have the induced function $\bar{f}: \mathbb{C}^n \to \mathbb{C}$ given by evaluation. The association $f \mapsto \bar{f}$ is injective.
Is there a quick proof of this? Please give me some hints.
Note: Please close/delete this question if it has been asked before. Thanks.
My proof:
Induct on $n$. For $n=1$: If $\bar{f} = 0$ then for all $x \in \mathbb{C}$, the polynomial $X- x$ divides $f$. Since $\mathbb{C}$ is infinite, the only way this can hold is $f = 0$.
Now assume true for $n$ and consider $n+1$. Suppose $\bar{f} = 0$. For all $x \in \mathbb{C}$, let $g_x := f|_{X_{n+1} = x} \in \mathbb{C} [X_1, \dotsc, X_n]$. Then $\overline{g_x} = 0$. The induction hypothesis implies $g_x = 0$ for all $x \in \mathbb{C}$.
Write $f = f_0 + f_1 X_{n+1} + \dotsb + f_k X_{n+1}^k$ for $f_0, \dotsc, f_k \in \mathbb{C} [X_1, \dotsc, X_n]$. Since $\mathbb{C}$ is infinite, we can pick distinct $x_0, \dotsc, x_k \in \mathbb{C}$. Then the result that $g_{x_j} = 0$ for each $j$ implies that the matrix $M_{ij} := f_{i} x_j^i$ has linearly dependent rows, so that $
\det{M} = 0$. But by the vandermonde determinant formula, $\det{M} = \prod_i f_{i} \prod_{i < j} (x_j - x_i)$, implying that all $f_i = 0$.
(This proof works when $\mathbb{C}$ is replaced with any infinite integral domain $R$, I think.)
Clarification: A quick proof means deducing the result as an easy consequence, even special case, of some general theorem.
Comment: Maybe you can decide: are you asking for a "quick proof" or for a proof verification?
Comment: The proof seems sound to me, and I agree that it works for infinite integral domains R.
Answer: Hint : Use induction on n and $C[X_1,...,X_n,X_{n+1}]=C[X_1,...,X_n][X_{n+1}]$
Comment: I'm about to edit this question so that it reflects better what I'm looking for. Obviously I knew that induction is involved---it doesn't make the proof quicker. I'd appreciate it if you could help me after my edit. Thanks


Async Recursive Readdir in Node

Question: I'm trying to scan a large directory of files and sub-directories with a recursive function that I've written. It's very similar to the parallel loop given in this answer.
var fs = require('fs');
var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = dir + '/' + file;
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

This issue is that it isn't really asynchronous. The whole thing processes and returns a giant array of files.  Is there a way to recursively scan a directory asynchronously?
Something more like:
walk(path,function(files) {
  // do stuff with each file as its found
});

EDIT: once I start getting the files, I plan to access them and use the async module to process them and prevent using up file descriptors. So something like this:
walk(path,function(files) {
    async.each(files,function() {
        // do more stuff
    }
});

Will that work okay with an asynchronous scan?
Comment: Your code is already asynchronous.  I think what your'e after is creating your code in a module such that you can extend the event emitter object and then register to be notified when each file has been read.  http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941
Answer: yes   HeadCode
 already explained it in a comment above. You can use eventEmitter to do this kind of Asynchronous recursive stuff.   For your code you can put the walk function as an event callback.
var EventEmitter = require("events").EventEmitter;

var ee = new EventEmitter();
ee.on("walk", YourWalkFunction);

ee.emit("walk",YourParams);

Async Recursive Readdir in Node


Como posso copiar uma maquina do android studio para outra maquina, sem precisar instalar o android studio?

Question: Instalei o android studio em minha maquina e criei uma maquina com android para emular as aplicações, mas agora eu quero pegar somente esta maquina que criei e colocar em outro computador, estou tentando, mas quando tento executar acontece isso:
C:\Users\usuario\Desktop\Sdk\emulator>emulator.exe -avd whatsapp
PANIC: Unknown AVD name [whatsapp], use -list-avds to see valid list.
ANDROID_SDK_HOME is defined but there is no file whatsapp.ini in $ANDROID_SDK_HOME\avd
(Note: Directories are searched in the order $ANDROID_AVD_HOME, $ANDROID_SDK_HOME\avd and $HOME\.android\avd)

Se executo:
C:\Users\usuario\Desktop\Sdk\emulator>emulator.exe -list-avds

Não retorna nada.
Adicionei nas variáveis de ambiente ANDROID_SDK_HOME com o caminho novo onde esta a maquina, mas apresenta o mesmo erro acima.

Se eu executar este mesmo comando na pasta default do android studio que esta instalado na minha maquina, funciona normalmente.
Como posso copiar uma maquina do android studio para outra maquina, sem precisar instalar o android studio?
Eu estou procurando algo do tipo:
emulator.exe -avd <caminho_da_maquina>

Answer: Por padrão os AVDs são criados em $HOME/.android/avd. No Windows provavelmente é algo como C:\Users\MeuUsuario\.android\avd.
É possível criar a variável de ambiente $ANDROID_AVD_HOME para alterar o caminho padrão.

Os AVDs salvos são compostos por um diretório e um arquivo .ini. Se você tiver um AVD chamado whatsapp, existirá:

um diretório $HOME/.android/avd/whatsapp.avd
um arquivo $HOME/.android/avd/whatsapp.ini

Para mover o AVD entre máquinas, basta copiar estes dois itens.
Para rodar o AVD em outra máquina, deverá ser instalada nela a mesma imagem de sistema que foi usada para criar o AVD.
Comment: Vou testar na outra maquina.


Specify top-left corner position for QMenu

Question: I have QPoint pos after clicking mouse and what to show at this point QMenu. But I what menu to appear that this pos will be left top corner of QMenu. And
<code>menu.exec(pos);
</code>
shows menu such that pos is it's left edge middle point
Comment: maybe OS handle this left right corner ...
Answer: Try to use mapToGlobal like this:
<code>//menu.exec(pos);
menu.exec(mapToGlobal(pos));
</code>
Comment: Yes, I do so, 'cos I have widgets in widgets. Is seems that it's possible to do what I what only by changing pos coordinates.


Listing issue, GROUP mysql

Question: Here is a mock-up example of Mysql table:
| ID  |  Country  |  City      |
________________________________

| 1   | Sweden    | Stockholm  |
| 2   | Sweden    | Stockholm  |
| 3   | Sweden    | Lund       |
| 4   | Sweden    | Lund       |
| 5   | Germany   | Berlin     |
| 6   | Germany   | Berlin     |
| 7   | Germany   | Hamburg    |
| 8   | Germany   | Hamburg    |

Notice how both rows Country and city have repeated values inside them.
Using GROUP BY country, city in my PDO query, the values will not repeat while in loop. Here is PDO for this:
$query = "SELECT id, city, country FROM table GROUP BY country, city";
$stmt = $db->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :

The above code will result in an output like this (some editing in-between). GROUP BY works but the country repeats:
Sweden - Stockholm
Sweden - Lund
Germany - Berlin
Germany - Hamburg

Using bootstrap collapse and above code, I separate the country from the city with a simple drop down collopase. Here is code:

<a data-toggle="collapse" data-target="#<?= $row['id']; ?>"
href="search.php?country=<?= $row['country']; ?>">
<?= $row['country']; ?>

<div id ="<?= $row['id']; ?>" class="collapse in"> //collapse div here
<a href="search.php?city=<?= $row['city']; ?>">
<?= $row['city']; ?>

 //end

It then looks something like this (once collapse is initiated):
Sweden
> Stockholm
Sweden
> Lund
Germany
>Berlin
Germany
>Hamburg

Here is where I face the problem. The above lists the values Sweden and Germany 2 times. I want Sweden and Germany to only list one time, and the cities listed below, so the desired look is to be this:
Sweden // Lists one time
> Stockholm
> Lund
Germany // Lists one time
>Berlin
>Hamburg

I have tried using DISTINCT, GROUP_CONTACT and other methods, yet none get my desired output (above). Suggestions? Below is my current full code in action:
<?
$query = "SELECT id, city, country FROM table GROUP BY country, city";
$stmt = $db->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :

?>

    <a data-toggle="collapse" data-target="#<?= $row['id']; ?>"
    href="search.php?country=<?= $row['country']; ?>">
    <?= $row['country']; ?>

    <div id ="<?= $row['id']; ?>" class="collapse in"> //collapse div here
    <a href="search.php?city=<?= $row['city']; ?>">
    <?= $row['city']; ?>

 //end

        <?  endwhile ?>

Comment: That is propably because you are using `$row['id'];` as Id and it is not grouped in your query. and every id you have is diferent one from another one. You should use `` instead.
Comment: Try using something to the affect of `$stmt = $db->prepare("SELECT DISTINCT ".$id.", ".$city.", ".$country." FROM table GROUP BY country, city WHERE country = :id");` @SethCodes
Comment: @jorge `` still repeats.
Comment: @Fred-ii- Can you example this for me?
Comment: @SethCodes That would be the line of code to use, can you try it out and see? Just replace it with your existing `$query = "SELECT id, city, country FROM table GROUP BY country, city";` and `$stmt = $db->query($query);`
Comment: @Fred-ii- Fetches nill.
Comment: Then try `$stmt = $db->prepare("SELECT DISTINCT id, city, country FROM table GROUP BY country, city WHERE country = :id");` also replace the word `table` with your own table name, unless if your table name is called `table` then you will need to put it in backticks, since it's a reserved word. Or `WHERE country = :country");` @SethCodes
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/40083/discussion-between-sethcodes-and-fred-ii)
Comment: I still think that you dont have problem with your data result since you are getting countrys and cities, so, your collapse code should be the catch
Comment: @JorgeCampos Mysql is doing it's job, it's in listing, I can't seem to find a method to limit it's echo on every city record.
Comment: OOOh man.. I understand what is wrong. You have to have a variable that stores current country and check with the next country in the loop if it is the same you wont print the `<a` tag just the div for the citie
Comment: @SethCodes Just a quick note/question in wondering why you already have duplicate entries in your table. It's rather quite easy to implement a duplicate check before inserting into DB, which I suggest you use ASAP.
Comment: @fred -ii It's a mock example, the database has more columns, these duplicate entries hold addresses.
Answer: So, as discussed your mysql result isn't the problem. you have some logic to change.
I don't have a enviroment to check, please let me know if it wont owrk.
$currCountry = "";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
?>

    <?if ( $currCountry != $row['country'] ) {?>
        <a data-toggle="collapse" data-target="#<?= $row['id']; ?>"
         href="search.php?country=<?= $row['country']; ?>">
         <?= $row['country']; ?>

    <?
    }
    $currCountry = $row['country'];
    ?>

<div id ="<?= $row['id']; ?>" class="collapse in"> //collapse div here
<a href="search.php?city=<?= $row['city']; ?>">
<?= $row['city']; ?>

 //end

<?  endwhile ?>

Comment: Closer, however collapse breaks things. collapse lists wrong. Any more help would be great...
Comment: Any more help? I am really stuck here,
Comment: Sorry man it was very late yestarday here in my time zone. So try to change in my code that: `data-target="#"` on the `<a` tag for this: `data-target="#<?= $row['country']; ?>"` and on the div tag, this `<div id ="<?= $row['id']; ?>"` for this `<div id ="<?= $row['country']; ?>"` and give it a test
Comment: thanks for your time, really want to try and get to a solution with this one, but nothing seems to work... I tried above, but still face some error, maybe a complete alternative would be the way to go? Maybe load results via ajax in collapse?
Comment: Can you pastebin your generated html ?
Comment: Using this method: `SELECT id, country, group_concat(city) AS city, country FROM retailers GROUP BY country` has gotten me closer, the only issue with this is now my city links to generate correctly. Any soultions?

Listing issue, GROUP mysql


the group user can not write to file

Question: i used tomcat+cpanel in linux os . i set the tomcat group of a file but tomcat can not write to my file . the permission my file is 664 .
the os setting is :
root@panther [/home/domain/public_html]# ls -la
total 36
drwxr-x--- 4 domain nobody 4096 Oct 9 15:18 ./
drwx--x--x 11 domain domain 4096 Oct 9 15:17 ../
drwxr-xr-x 5 tomcat nobody 4096 Oct 8 19:26 ROOT/
drwxr-xr-x 5 jbeanir jbeanir 4096 Oct 17 2011 TEST/

the url of page is domain/TEST/newjsp2.jsp
please help me
Comment: Make sure that TEST folder is also writeable to the group.
Answer: If you are attempting to create a file in the TEST directory, please remember that you must have permissions in the directory to "write" to the directory.
In other words, if this file doesn't exist, change the directory permissions of TEST to rwxrwxr-x and you should be able to create it.
Note that you haven't checked to see which owner the tomcat web server is running as, odds are it is tomcat.  If that is so, then you might want to make TEST owned (or at least group owned) by tomcat.
Finally, Tomcat is a bit of an environment in itself.  In order for this to have much of a chance of working correctly, you need to read up on the layout of a WAR file, and how Tomcat unpacks that into the applications directory, and odds are that's where you really want to be dropping your file (if you have configured tomcat to allow such activities).
Answer: The permission of /home/domain/public_html is 750, which means that only the owner and group can use it.  If tomcat is not a member of the "nobody" group, then tomcat won't be able to access any files in that directory or its subdirectories.  You should change /home/domain/public_html to mode 751 or 755.
And, as others have said, if you're trying to create a file in the TEST directory, then tomcat must have write permissions in that directory.

the group user can not write to file


Como colocar os estados tirados do site do ibge em ordem alfabética?

Question:  fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
    .then( res => res.json() )
    .then( states => {

    for( const state of states ) {
        ufSelect.innerHTML += `<option value="${state.sigla}">${state.sigla}</option>`
    }

    })
}

populateUFs()

function getCities(event) {
    const citySelect = document.querySelector("[name=city]")
    const stateInput = document.querySelector("[name=state]")

    const ufValue = event.target.value

    const indexOfSelectedState = event.target.selectedIndex
    stateInput.value = event.target.options[indexOfSelectedState].text

    const url = `https://servicodados.ibge.gov.br/api/v1/localidades/estados/${ufValue}/municipios`

    citySelect.innerHTML = "<option value>Selecione a cidade</option>"
    citySelect.disabled = true

    fetch(url)
    .then( res => res.json() )
    .then( cities => {

    for( const city of cities ) {
        citySelect.innerHTML += `<option value="${city.nome}">${city.nome}</option>`
    }

    citySelect.disabled = false

    })

}

document
   .querySelector("select[name=uf]")
    .addEventListener("change", getCities)

Comment: Inseriu na pergunta muito código sem necessidade, bastaria mostrar o formato que está recebendo os estados da Api e o que tentou fazer para ordenar!
Answer: Para organizar um determinado array, o JavaScript disponibiliza uma função chamada sort.
De acordo com a documentação, você pode passar uma função para ter critérios personalizados. Esta função deve retornar um dos valores possíveis, que são: -1, 0 ou 1.
Exemplo:
arr.sort((a, b) => a > b ? 1 : -1)

Se a for menor que b, deve retornar -1
Se a for maior que b, deve retornar 1
Se a for igual a b, deve retornar 0

const ufSelect = document.querySelector('#ufSelect');

fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados")
    .then( res => res.json() )
    .then( res => {
      return res.sort((a, b) => a.sigla > b.sigla ? 1 : -1)
    })
    .then( states => {
      for( const state of states ) {
          ufSelect.innerHTML += `<option value="${state.sigla}">${state.sigla}</option>`
      }
    })
<select id="ufSelect" name="state"></select>
Comment: Muito obrigado meu amigo! Deu certinho aqui.


Can time signatures be written in the form of a fraction?

Question: Is it OK to write time signatures as fractions like this:
4
-
4

instead of
4
4

? Is it allowed? If yes, could you show me proof?
Comment: What reason would you have for this? In print, it usually looks like 4/4, but on a stave, the '-' will be on the centre line, and probably not seen anyway.
Comment: It's important to realise that a time signature is not a fraction, but rather two separate numbers which are quoted together: the lower number gives the note duration (minim, crotchet, quaver) and the upper number says how many notes there are in a bar.
Comment: In 20th-century pieces you'll occasionally see time signatures like 1½/4 or 2½/4, which reinforces @No'amNewman's point about the time signature being better thought of as two numbers rather than as a fraction.
Comment: It's not that far removed from a fraction, particularly if you think in American note-names -  3/4 is Three Quarters (of a Whole Note), 6/8 is Six Eighths (of a Whole Note).    But we still don't use the fraction line.
Comment: @LaurencePayne It's very far removed. A measure of 3/4, 4/4, 5/4, ect. are equally whole, they just don't add up to  what we call a whole notes.  So the fraction comparison only makes sense when you have a measure that equates to a whole note and any other measure the comparison is nonsensical.
Comment: @Dom, You might as well say the whole 'quarter note', 'half note' etc. naming system is invalid, because it refers to fractions of a whole note, not of a bar.   A 5/4 bar contains five quarter notes.  Nothing wrong with explaining that as adding up to... well... five quarters of a whole note.
Answer: You'll occasionally find key signatures like this in music written in and after the twentieth century.
I'm not sure I've ever seen it for a single-staff instrument, but I have seen it for piano music and in full scores. When it's done, the time signature is either written between staves (e.g., in piano music) or stretched across several grouped staves (e.g., the woodwinds in an orchestral setting).
Edit: I thought I had seen slashes in time signatures before, but I'm having trouble finding an example in my own library. Nevertheless, here is an image from the Prelude to Schoenberg's Op. 25, which shows the between-staff time signature I mentioned.

See also this terrific answer that elucidates some "hidden" time signatures in a score much like what I mentioned in my second paragraph. But, again, there is no fraction bar.
Answer: In music notation, time signatures are written without the fraction line.   Apart from anything else, it would get muddled up with the lines of the stave. In text, such as this reply, we write them with a slash, 4/4, 6/8 etc.


how to improve doc2vec model

Question: I would like to do some sentence embedding on around 500 sentences. The purpose is to find for new sentences, the most similar ones within the 500 sentences. Unfortunately, for now its definitely not working. Indeed, to test my model I simply looked at the 10 most similar sentences for a sentence which was used for training, hopping that the most similar one will be itself. But its not the case. Hence, I am wondering how to improve such models (e.g. the only way I know is shuffling the data)? Also, is there other ways to test a doc2vec model?
I dont know how to share the data, knowing that I dont have dropbox or similar, perhaps by email...
Thank you very much for any suggestion.
Here is my code:
import numpy as np
import re as re
import gensim
from gensim.models import doc2vec
from collections import namedtuple
#for stopwords
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
from random import shuffle

#import data
li_doc = list(np.load('/home/camille/vm_exchange/li_doc.npy'))

def text_cleaning_for_embeding(x):
    #remove ponctuation
    x = ' '.join(re.split('[?.,:/>!;]', x))
    #remove entre parenthèse
    x = x.replace('(','')
    x = x.replace(')','')
    #remove digits
    x = ''.join([l.lower() for l in x if not l.isdigit()])
    #remove stopwords and tokenize
    x = ' '.join([w for w in x.split() if w not in cachedStopWords])
    return(x)

#Transform data to 'TaggedDocument'
docs = []
analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')
cachedStopWords = stopwords.words("english")

for i, text in enumerate(li_doc):
    text_ = text_cleaning_for_embeding(text)
    #list of words
    words = text_.split()
    #small cleaning
    words = [i.lower().strip() for i in words]
    #register as namedtuple: analyzedDocument
    tags = [i]
    docs.append(analyzedDocument(words, tags))

docs_train = docs[0:500]
docs_test = docs[500:len(docs)]

model = gensim.models.Doc2Vec(vector_size=100, window=10, min_count=1, workers=8, alpha=0.025, min_alpha=0.015,
                              epochs=20)
#sample=1e-4, negative=5,
#shuffling is better (ot needed at each trianing epoch
shuffle(docs_train)
#Build vocabulary from a sequence of sentences
model.build_vocab(docs_train)
#Update the model's neural weights from a sequence of sentences
model.train(docs_train, epochs=model.epochs, total_examples=model.corpus_count)

#testing on 2 training sentences:
for i in range(0,2):
    t = docs_train[i].tags[0]
    new_vector = model.infer_vector(docs_train[i].words,steps=50, alpha=0.025)
    sims = model.docvecs.most_similar([new_vector]) #gives you top 10 document tags and their cosine similarity
    #model.docvecs.most_similar(): get similarity between word vector
    #model.most_similar(): get similarity between document
    print('--------------------------------------------------------------------------------------------------------')
    print('------------- %s'%li_doc[t])
    print('--------------------------------------------------------------------------------------------------------')
    for t,sim in sims:
        print('\n', sim, li_doc[t])

the output:

------------- Apple cider (also called sweet cider or soft cider or simply cider) is the name used in the United States and parts of Canada for an unfiltered, unsweetened, non-alcoholic beverage made from apples.

0.9132258296012878 Chocolate ice cream is ice cream with natural or artificial chocolate flavoring. Chocolate is the second most common
  flavor of ice cream in the United States, after vanilla.
0.9112349152565002 Spice cake is traditionally flavored with a mixture of spices. The cake can be prepared in many varieties.
0.9098634719848633 Vanilla is frequently used to flavor ice cream, especially in North America and Europe. Vanilla ice cream, like other
  flavors of ice cream, was originally created by cooling a mixture made
  of cream, sugar, and vanilla above a container of ice and salt.
0.9087004661560059 Ice cream (derived from earlier iced cream or cream ice) is a sweetened frozen food typically eaten as a snack or
  dessert.
0.9066498279571533 Hot chocolate, also known as Chocolate tea, drinking chocolate or just cocoa is a heated beverage consisting of
  shaved chocolate, melted chocolate or cocoa powder, heated milk or
  water, and usually a sweetener.
0.906596839427948 Multigrain bread is a type of bread prepared with two or more types of grain. Grains used include barley, flax, millet,
  oats, wheat, and whole-wheat flour, among others.
0.9057920575141907 Cream of mushroom soup is a simple type of soup where a basic roux is thinned with cream or milk and then mushrooms
  and/or mushroom broth are added.
0.9056931138038635 A plum tomato, also known as a processing tomato or paste tomato, is a type of tomato bred for sauce and packing
  purposes.
0.9055744409561157 A meatball is ground meat rolled into a small ball, sometimes along with other ingredients, such as bread crumbs,
  minced onion, eggs, butter, and seasoning.
0.9055196642875671 Fermented milk products, also known as cultured dairy foods, cultured dairy products, or cultured milk products, are
  dairy foods that have been fermented with lactic acid bacteria such as
  Lactobacillus, Lactococcus, and Leuconostoc.

------------- Salami (singular salame) is a type of cured sausage consisting of fermented and air-dried meat, typically beef or pork.
0.873619556427002 A sausage is a cylindrical meat product usually made from ground meat, often pork, beef, or veal, along with salt,
  spices and other flavourings, and breadcrumbs, encased by a skin.
0.8629544973373413 Cornbread is any quick bread containing cornmeal. They are usually leavened by baking powder.
0.8617033958435059 Sauerkraut (; German: [ˈzaʊɐˌkʁaʊt] ( listen)) is finely cut cabbage that has been fermented by various lactic acid
  bacteria.
0.8616538643836975 Whisky or whiskey is a type of distilled alcoholic beverage made from fermented grain mash. Various grains (which may be
  malted) are used for different varieties, including barley, corn
  (maize), rye, and wheat.
0.8616343140602112 Almond butter is a food paste made from almonds. Almond butter may be crunchy or smooth, and is generally "stir"
  (susceptible to oil separation) or "no-stir" (emulsified).
0.8612356185913086 A flour tortilla (, ; or wheat tortilla to differentiate it from other uses of the word tortilla, which in
  Spanish means "small torta", or "small cake") is a type of soft, thin
  flatbread made from finely ground wheat flour from Mexico.
0.8611332178115845 Toffee is a confection made by caramelizing sugar or molasses (creating inverted sugar) along with butter, and
  occasionally flour.
0.8610053658485413 Semolina is the coarse, purified wheat middlings of durum wheat mainly used in making pasta and couscous.
0.8609529733657837 White chocolate is a chocolate derivative. It commonly consists of cocoa butter, sugar and milk solids and is
  characterized by a pale yellow or ivory appearance.
0.8609246611595154 A hamburger, beefburger or burger is a sandwich consisting of one or more cooked patties of ground meat, usually beef,
  placed inside a sliced bread roll or bun.
Answer: I can provide a few suggestions if you're still looking for help (as of this writing, the question is ≈1 year old)

First thing I noticed was the number of epochs you used while training epochs=20 could be a bit low, especially considering that your documents are shorter in length. This is a little bit trial-and-error as I'm not as familiar with training on shorter documents, but have you tried bumping up epochs higher, perhaps something within the 50-100 range? (maybe even 100+) This may perform better on shorter documents.
Your number of documents (500) is low in count - if possible, could you gather more examples for training?

As a side note. I've noticed that you perform the document list slicing first, then shuffle docs_train for training. Not sure if that's intended: Try shuffling first and then slice. Also, it depends on why exactly you'd want to arbitrarily train on a portion of your documents - If the goal is to find similar documents going forward, I'd also try training your doc2vec model on the entire set, to find similar documents within the training set.
  Then, when you have an out-of-sample document, you can infer the vector to find most similar sentences within what the model knows and trained on previously.
In practice, I've done a "similarity search" by inferring all new documents (out-of-sample) and performing a cross join to surface up documents that are most similar, where my training was the entire set.

During the call to model.infer_vector(), you could also try bumping up steps=50 (btw, steps arg is deprecated, you could switch to use epochs=N) I've found the optimal number under my use cases was 99-250 range, but this requires some tuning and testing on your end, as that number may not be the same for you. How I've tackled this was to perform iterative inference (for epochs=10, 20, 30... 300+) and chart the performance of cosine similarity between the model-known vector vs the inferred vector.
You could try tweaking the vector_size from 100 to something smaller or larger. If you think the set of vocabulary is limited, perhaps condensing vectors to smaller size may achieve better results because you are representing vocab by mapping to smaller vector size.
for short corpuses, you could try word stemming, as this may help the model. Likewise, try options for keeping stopwords and punctuation.
If you are inclined, you can try more hyperparam tuning/testing: set dm=0, window={3-10}, min_count={1-5}, etc... if you package up your testing code you try "grid search" by testing various doc2vec configurations and see which one comes out with the best accuracy.

Anyway, I hope this helps to at least get you started on right path on what to experiment with and tweak in your code! I've had to learn a bunch just via  testing and lots of reading other posts/questions&answers - In reality, the one big takeaway I've found is that your doc2vec implementation greatly depends on your use-case.
For more reading, I've found this paper very useful to understand underlying mechanics for doc2vec: An Empirical Evaluation of doc2vec with
Practical Insights into Document Embedding Generation

how to improve doc2vec model


What does calling self within a class do?

Question: I noticed in the documentation for Pytorch Lightning, it was mentioned you can call the forward method from another method in the same class just by calling self(x). I haven't been able to find any info about how this works. I always thought you would call the method using self.forward
Evidently, it calls the forward method but how? Is there any python documentation about what's going on?
I found this at the following URL:
https://pytorch-lightning.readthedocs.io/en/stable/new-project.html
The specific code fragment is this:
def training_step(self, batch, batch_idx):
    ...
    z = self(x)

Comment: It's just calling the `__call__` method of an object
Comment: You should realize that ```f(*args, **kwargs)``` is the same as ```f.__call__(*args, **kwargs)``` :)
Answer: Generally speaking, in python, when "calling" an object, you are invoking its __call__ method. That is,
  self(x)

is equivalent to
  self.__call__(x)

For pytorch nn.Module (and all derivative classes) __call__ wraps around the module's forward function, therefore, from your perspective self(x) is basically forwarding x through the module self.


I've solved it by finding the value of Z first. So is there any other ways that can solve it without having to find the value of Z?

Question: Given the $z+ \frac{ 1  }{ z  }  =i$
Calculate the $z  ^ { n  }  + \frac{ 1  }{ z  ^ { n  }    }$
Comment: You could write it as a recurrence then solve it. Technically that doesn't involve finding $\,z\,$ explicitly, though the actual calculations are quite similar nevertheless.
Comment: See sections 4.1 & 4.2 of https://en.wikipedia.org/wiki/Linear_recurrence_with_constant_coefficients   to elucidate my A.
Answer: Let $f(n)=z^n+1/z^n.$
We have $f(n+1)=f(n)f(1)-f(n-1)=if(n)-f(n-1).$
The set of roots of $x^2-ix+1=0$ is $\{ip,-i/p\}$ where $p=(1+\sqrt 5)/2.$
From the theory of linear homogeneous recursions, there are unique $A,B$ such that $f(n) =A(ip)^n +B(-i/p)^n$ for all $n$. We can find $A,B$ from the pair of equations $2=f(0)=A+B$ and $i=f(1)=A(ip)+B(-i/p).$ After the calculations we see that $A=B=1.$
If $n$ is even then $f(n)=L(n)(-1)^{n/2},$ and  if $n$ is odd then $f(n)=i\cdot L(n)(-1)^{(n-1)/2}$ where $L(n)$ is the $n$th Lucas number: $L(0)=2$ and $L(1)=1$ and $L(n+1)=L(n)+L(n-1)$ and also  $L(n)=p^n+(-1/p)^n.$


Python: Unexpected regex behaviour for {n} match

Question: I have tested the following code on http://regexpal.com/ and it correctly matches the string I want. I want to find 16 digit numbers which occur in blocks of 4 with a space in the middle, so I wrote the following regex:
\d{4}(\s\d{4}){3}

i.e. match 4 numbers, then match three repeating sets of a space followed by four numbers. On regexpal, this correctly matches:

test1234 message1234 5678 1234 5678

In Python, however, I run the following code:
>>> import re
>>> p = re.compile('\d{4}(\s\d{4}){3}')
>>> p.findall('test1234 message1234 5678 1234 5678')
[' 5678']
>>>

I don't understand why it is matching the second instance of '5678' and why it is not matching the block of numbers as I would expect.
Answer: raw string is the recommended way to define  regex but the problem here is mainly because of the implementation of findall method. You need to  turn capturing group present in your regex to non-capturing group. Because re.findall function gives the first preference to captures and then the matches. Your regex \d{4}(\s\d{4}){3} matches the 16 digit number but captures only the last four plus the preceding space.
p = re.compile(r'\d{4}(?:\s\d{4}){3}')

Example:
>>> import re
>>> p = re.compile(r'\d{4}(\s\d{4}){3}')
>>> p.findall('test1234 message1234 5678 1234 5678')
[' 5678']
>>> p = re.compile(r'\d{4}(?:\s\d{4}){3}')
>>> p.findall('test1234 message1234 5678 1234 5678')
['1234 5678 1234 5678']

Comment: I think you should mention that raw string is recommended way to write regex, but in this case, the problem comes from the implementation of `findall`, which switches to use content from capturing group if there is any in the regex.
Answer: You need to either prefix your string with an r or escape your backslashes:
p = re.compile(r'\d{4}(\s\d{4}){3}')

or
p = re.compile('\\d{4}(\\s\\d{4}){3}')

Comment: Raw string is not the issue here, though it is recommended practice. Python preserves the ``\`` for unrecognized escape sequences.


use python to run commands in batch file

Question: I want to use python to run commands in a batch file. The screen capture below shows the batch file and commands in Windows cmd.

I tried to use python to open the batch file.
import os
os.system('C:/Program Files/MetroCon-3.2/RepSend/RepSendQXGA64.bat')

This returns '1' which means failed.
import subprocess
filepath="C:/Program Files/MetroCon-3.2/RepSend/RepSendQXGA64.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print (p.returncode)

This return '0'. And the list of commands are in stdout and can be shown in python.
The question is how to run the specific command in the batch file as it runs in Windows cmd.
Answer: If you want to run specific commands from the bat file, you could open the bat file as a txt file (Or use the stdout output), read it line by line and then communicate with the cmd via the winpexpect module.
import winpexpect
import subprocess
import multiprocessing
cmd = winpexpect.winspawn("cmd")
# Create read write buffers
cmd.logfile_read = read_buffer
cmd.logfile_write = write_buffer
cmd.sendline("insert whatever command line you want")

edit : If I understood you correctly, I could add the read/write buffer implemntation
Answer: Do you mean something like this?
import os
os.chdir("C:/Program Files/MetroCon-3.2/RepSend/")
os.startfile("RepSendQXGA64.bat")

or  this?
os.system("start /wait cmd /c RepSendQXGA64.bat")

Comment: I cannot use `os.system` to open this bat file. `subprocess` works.


Checking whether or not an unpublished comment exists on node for current user

Question: I'd like to be able to let a user know that their comment has been submitted and is awaiting approval on every view of that particular node, not just a notification printed in the message region immediately after a submission.  I assume there's a way to cross-check the current node's unpublished comments and print something in the comment area if the user shows up as an author of an unpublished comment.  I have a feeling I can write a simple function, something like below, but I'm missing something and I'm not sure where to run it (ie, in the .tpl or in an .inc):
function find_unpublished_comments_of_current_user(&$comment, &$user) {
    if ($comment->status == 0 && $user->id == $comment->uid){
      //something here
      }
}

Thanks for any help.
Comment: After exploring what's available in `node.tpl.php` and `comment.tpl.php` it appears that I can access all comments from the `$content['comments']` array and `$comment` array respectively, but neither hold unpublished comments.

So I'm thinking that this does indeed need to be a [preprocessor](http://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/template_preprocess_comment/7)
Answer: You can achieve this in either of the following way,
1) If you are writing custom function as described in question,
   a) Write your function in a block by selecting text format as PHP code, and display the   block in desired region.
   b) Otherwise define the function in your module and call it in your node template file node--type.tpl.php
2) Through view: Create a view to show un published comments of a node as follows,
View
Create a view:
Settings:
  Show: Comments
  Create block: select
  Click save & continue
Filter criteria
 Comment: Approved (No)
Advanced->Add
 Contextual filters

Content: Nid
Under When the filter value is NOT available
Provide default value : Content ID from URL
Comment: Author uid
  Provide default value ->choose user id from logged in user

Now assign your block to a region on the node display page, you will get unpublished comments of the particular user for that node,
Comment: Thanks for the ideas.  I tried option 2, but couldn't seem to get it to work.  Passed the nid and uid as contextual filters and placed a block for the view in the content area of nodes and nothing showed up.  Tried adding a filter of "Current user logged in" and that didn't work either.
Comment: I edited answer for view part, i tried this and got work so please check your views settings with answer
Answer: I got around to doing this finally:
function comment_detection_node_view($node, $view_mode, $langcode) {

  $current_user_id = $GLOBALS['user']->uid;
  $node_id = $node->vid;

  $query = "SELECT COUNT(c.cid) FROM {comment} c WHERE c.uid = $current_user_id AND c.status = 0 AND c.nid = $node_id";
  $result = db_query($query);

  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $comment_detector = $row['COUNT(c.cid)'];
    }
  }
  // $comment_detector is the number of comments on the current node by the user
  // logged in that are unpublished, i.e. 0 or 1.

}