How to use weight variables within aggregated results, for group proportions

Question: If I have the following data, where each row represents and individual
response, how would I go about reporting the proportions of different groups?
(here the groups are paper, door, and not sure)
Columns:

question_response - the response to the survey question "do you prefer doors or paper"
weighting_variable - a weighting adjustment, an adjustment weight to each survey respondent

Rows :

individual responses

   question_response  weighting_variable
0               door                0.51
1               door                0.49
2               door                1.05
3               door                1.36
4               door                2.24
5               door                0.34
6               door                0.75
7               door                1.95
8               door                3.26
9               door                0.52
10              door                1.99
11          not sure                0.38
12             paper                0.94
13             paper                0.41
14             paper                1.29
15             paper                0.18
16             paper                1.03
17             paper                0.58
18             paper                0.07
19             paper                0.65

Just looking at the group counts, before considering the weights there are:

40% prefer paper
5% are not sure
55% prefer doors

My question is how to consider the weights, my intuition is that they should
be considered as follows.
First for door, the average weight is
0.51 + 0.49 + 1.05 + 1.36 + 2.24 + 0.34 + 0.75 + 1.95 + 3.26 + 0.52 + 1.99 = 14.46

14.46 / 11 = 1.314545

Then paper is 0.643750, and not sure is just 0.380000
Based on this I would instead say that

40% * 0.643750 = 25.7% prefer paper
5% * 0.38 = 1.9% are not sure
55% * 1.31 = 72.3% prefer doors

This makes sense as the percentages are still summing to 100 (within some rounding), but I wanted to double check that this was correct .
Comment: @whuber they're survey weights
Comment: What is the meaning of the "adjustment weights"?  Plausible interpretations include sampling weights, variance weights, frequency weights, local regression weights, etc.  The difficulty in answering is that how you incorporate the weights depends on what they mean.
Answer: More details on the actual problem could be of help in arriving at perhaps a more meaningful solution as to "how to employ weight variables within aggregated results, for group proportions".
For example, assume your data represents a buyer's product preference (product here I would presume to be the 'door', 'paper' , and if no preference,'not sure').
The weight represents the certainty of the responder's answer based on a survey scale (say 1 to 5).
What one could do with this data is, for example, assume that the scale translates into a probability 'p', whereupon with repeated occurrences of the buying decision, the sales selection could go to another item.
In this context, I would recommend a Monte Carlo simulation approach where the sales selections are probabilistic observed and proportions recorded over a large number of iterations.
This results in an average product selection proportion for each product,  a confidence interval from repeated runs, and even a possible plot of the observed probability selection distribution around the observed product averages.
Also, one could assess the sensitivity of the results as to how the buyer's preference scale is translated into probabilities. There is also a question as to how accurate a responder's hypothetical answer is compared to actual buying behavior, all of which could be transparently addressed in a simulation approach.
Comment: _"The weight represents the certainty of the responder's answer based on a survey scale (say 1 to 5)."_, sorry - the weight here is a survey weighting which suggests how representative that observation is of the population. So, your statement "the weight represents..." is, as far as I can tell, completely wrong.
Comment: I've added some additional context, perhaps that's of use
Comment: Baxx: Actually, your comment: "the weight here is a survey weighting which suggests how representative that observation is of the population" is more closely linked to my probabilistic assignment step than being able to link an arbitrary rating scale.
Comment: sorry, I don't follow why you're using probabilistic assignment here... The data is given, there are weights, I want to use them in aggregated statistics. What you're writing seems very separate from the actual problem. Can you provide some concrete calculations of what you're talking about?


Include third party JS library into my drupal module

Question: I want to include this library into my drupal module. Now I have two problems.

I wanted to use composer manager to get this library, but it's not available on packagist.org. So, I've tried to put it there manually to do not stuck on it. Path is MY_DRUPAL/vendor/malsup/jQuery.blockUI/jquery.blockUI.js
I want to attach this library via hook_page_attachments, but seems I don't know how to define this library in libraries.yml. The problem is that I cannot specify path to folder vendor/ from my_module.libraries.yml, because vendor/ located in root of drupal.

Could somebody give me an advice?
Thanks in advance.
Comment: At the moment there is no right solution: https://www.drupal.org/node/2605130
Comment: This is JS library, not PHP library. There is no reason to get /vendor directory or composer involved. Just put the js into your module's directory(or subdirectory) and define entry in libraries file of your module.
Comment: But it's third party library. In D7 I put libraries like this, into sites/all/libraries. What the right solution for D8?
Answer: You still put them in the libraries folder (now you can also use a top-level <code>/libraries</code>folder).
You need the libraries module, just like in 7.x. I'm also not 100% sure how well it works now in 8.x, in the JW Player module, I'm just using it to detect the location of the files: http://cgit.drupalcode.org/jw_player/tree/jw_player.module?h=8.x-1.x#n206
Comment: It doesn't looks like a final solution but seems you're right. I have found that https://www.drupal.org/project/codesnippet is doing the same.


Python - filtrando dados em arquivos de texto

Question: Estou tentando escrever um código para ler um arquivo .txt e extrair coordenadas numéricas, só que este arquivo contém linhas com textos também. Não estou conseguindo fazer o filtro. veja uma parte do arquivo.

Até agora eu consegui escrever o seguinte:
filename = 'arquivo.txt'
with open(file_name) as f:
    lines = f.readlines()

for line in lines:
values = line.split()

agora eu tento filtrar somente os valores das coordenadas das linhas 236, 244, 250, 256... poderia usar o valor da primeira coluna para filtrar pois é padrão, por exemplo: 110 na linha 236 e 105, 100, 35 das demais linhas.
Como são coordenadas x y z o próximo passo seria subtrair a quinta coluna da segunda - a sexta da terceira - e a sétima da quarta.
Comment: Blz, mas faltou explicar a sua dúvida, onde precisa de ajuda, o que não conseguiu fazer e tem dúvida. Tente colocar entrada e saída esperada, isso ajuda muito. Se quiser filtrar só os valores das coordenadas nas linhas 236, 244, 250 e 256 é bem simples. Mas imagino q não seja isso
Answer: Para filtrar esses valores observe os padrões do seu arquivo, uma rápida olhada me deu alguns padrões que parecem satisfazer suas necessidades, a primeira coluna deve ser sempre maior que zero e os valores contidos entre a coluna dois até a nove não deve possuir zero, podemos então multiplicar todos os valores da coluna dois até a nona, se o resultado for maior que zero a linha vai satisfazer suas necessidades, se essas duas condições forem atendidas guarde a linha inteira para posterior uso, segue código contendo a lógica explicada acima:
filename = 'arquivo.txt'

resultado=[]

with open(filename) as f:
    lines = f.readlines()

for line in lines:
    values = line.split()

    try:
        inteiros = map(int, values[0:9])

    except ValueError:
        continue

    try:

        if inteiros[0] > 0:
            multiplica = reduce(lambda x, y: x*y, inteiros[1:8])
            if multiplica > 0:
                resultado.append(values)

    except:
        continue

print resultado

Ajudaria muito se você tivesse colocado junto a sua pergunta o arquivo de entrada ao invés de colocar somente a imagem dela...
Comment: humm também funfou no `python27`, interessante huahua, coloquei pra deixar o mais usável possível para ambas as versões...
Comment: Sobre as exceções esperadas, acho que esse outro [comentário do @jsbueno](https://pt.stackoverflow.com/questions/210010/como-verificar-se-o-valor-de-vari%c3%a1vel-string-%c3%a9-numero/210012#comment429365_210012) é relevante para sua resposta
Comment: no meu código observe a linha `map(int, values[0:9])` ele converte pra inteiro
Comment: Sim, o problema é só o `expect` vazio, que em Python 3 seria erro de sintaxe
Comment: não tenho como testar no `python3`, só tenho o `python27` and run like a charm lol, quer dizer que `python3` não deixaria o meu `except` seguido de um `continue` passar?
Comment: Sim. Creio que `expect ValueError` resolveria tudo
Comment: http://ideone.com/, tem interpretador para Python3


Pseudo-fields and custom entity properties from additional schema

Question: I'm trying to add property information to an entity which uses the entity API. Working from the commerce_product module I am trying to manage additional information outside of fields and in my own database that ends up attributed with the resulting product object when the entity is loaded. I've been looking into the hook_entity_property_info_alter and hook_entity_load functions to get the additional custom or "pseudo-fields" loaded. I'm having issues when saving/creating the new entity (product) and information submitted from the form is not accessible. Am I supposed to alter the form and tack on an additional form submit handler? During a call to hook_commerce_product_insert I was expecting the $product object to have form field values included that I could work with. What would be the recommended way to approach this? I want to end up with data from my own database schema added to the entity and be editable through the entity's creation/edit forms.
I found this relevant solution but that approach deals with editing the original schema which is definitely something I want to avoid.
Answer: You may have to override the form submit handler, or at a minimum add you're own submit handler in addition to the default. As long as the submit handler starts with an entity passed through the $form_state, you could add your own handler to fire before the final handler that saves the entity and set your properties there.
While I don't have a ton of experience working with entities and hook_entity_load etc, you may get more milage from extending and overriding the default entity controller for product and overriding the load, save, and delete methods.
Answer: There is some kind of field other than usual CCK fields: extra fields.
hook_field_extra_field
I'm going to use it to add additional information to entity (Parent NID, Parent UID) some stuff that entity-reference can't and shouldn't handle. You have said it must not be field, I don't know if you don't want to use this kind of field also, But you might overlook some issues.
I'm not 100 percent sure if it's the solution but for people looking for an answer it's good to look at it.


How can I output a field as link?

Question: I have a title field and some date fields in my view in the following order
1.title
2.from_date
3.to_date
Since the title is long, I have trimmed and it is a known bug that the links don't work after trimming.
So how can I add a link to the title so that when I click on it, gets redirected? Please help somebody.
Comment: If it is a node, you can add the nid field, hide it and override the title field like `[title]`
Comment: Thanks. I have find a solution myself. Added a filed 'NID' above title and made it invisible. Also set custom path to the /node/{{nid}}. And it worked.
Answer: I have found a solution for the problem. Follow the steps.

Add a field 'Path' above the 'Title' field.
Exclude 'Path' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as {{ path }}.

OR

Add a field 'ID' above the 'Title' field.
Exclude 'ID' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as /node/{{ nid }}.

It both works.
Comment: You should add `Path` as a field, and then use `{{ path }}` instead of `/node/{{ nid }}` as the latter will never use your node's alias.

How can I output a field as link?


Possible to place two workspaces on one screen in X Window?

Question: Sometimes I'd like to copy write something from one window to my editor or compare something.
So if I can put two workspace2 in one screen, so I can easily drag two windows to different workspace and get both fullscreen, and then start work on one of them.
Also I can buy another monitor, but it seems to cost too much and as the screen is getting bigger, two windows in one screen is acceptable.
Does X support a solution for this?
EDIT:
I think what I want is related to this topic:
http://en.wikipedia.org/wiki/Tiling_window_manager
Answer: Or you can look at other windows managers, such as wmii, awesome or ratpoison changing the workspace paradigm and allow a better use of screen estate.
Comment: awesome seems support this feature.
Answer: If all you need it dragging wwindows from one Workspace to another, the Desktop Effects in Linux gives you exactly what you want with all your workspaces on a cube, which you can:

rootate with the mouse
drag windows across the workspaces.

For more Info: you may refer to this Google books Link

However, this is in no way comparable to a 2-monitor workstation. You may even consider an old CRT which are available for Dirt cheap prices now
Comment: Actually I mean two workspace in same screen at the same time. Maybe I should call this windows layout, automatically align different windows in the same screen.


Singing in a preferred key?

Question: Occasionally, when backing vocalists, I hear them say 'I sing in Bb', or I usually sing in my favourite key - G'. They sometimes proved themselves wrong, when I had to change key to one which fitted their range better - didn't tell them -but where did this concept come from, and is there actually any sense in a statement such as that? I don't mean they say they sing a particular song in a particular key - good vocalists do this - but they state that they sing everything in x key.
Answer: That's absolute non-sense if it's meant as a general (i.e., song-independent) statement. Of course every singer has a certain range, and also a comfort zone. But the range of a song, i.e., its lowest and highest note, is not determined by the key, but by the way the melody is written. Of course, chances are that in a certain key the lowest note is the root or the fifth, and that the highest note is the root, but there are too many exceptions to use this as a guideline.
Answer: The notion of a favorite key for someone's voice is not as far-fetched as you might think. Professional singers intimately know their voices and their "money notes", the exact spots where they can achieve the ideal sound. These spots can be as delicately placed as a semitone, so it does make sense that someone likes singing in E as opposed to E flat, since their high e sounds a lot better than their high e flat.
Comment: A favourite key for a specific song, I'll buy. I do it myself, as do so many far better vocalists. However, the blanket 'I sing in C'?
Comment: You're right, the preference makes a lot more sense for particular songs than for music generally. I assume the reason that specific preferences generalize somewhat to a general preference is that classical music follows predictable patterns - composers use in-scale notes much more often than foreign notes, melodies tend to climax on the tonic or the fifth, etc.
Comment: @SaggingRufus - I'm of the firm opinion that a vocalist should be more than aware of both the key he needs to sing a particular song in, and his tessitura. Love it when a singer says 'you find the key'. I generally do, about a tone too high. Well, we all make mistakes, and his was not being in control!
Comment: Ask a professional singer about *Bruchlage* (don't know the English term, sorry) and they'll bend your ear about how incredibly important it is that you accomodate their key. Gerald Moore used to claim that in any given recital, he'd have to transpose classical songs more often than not, on the singer's explicit wish.
Comment: Understood, and with you all the way. Often that extra semitone, either way, will stop success. But I'm asking about people who have said - quote - ' I always (or only) sing in x key'.
Comment: That sort of reasoning makes some sense, and may be the basis for the explanation.. I'm looking for evidence. But most of the people who've said this to me don't sing classical stuff.
Comment: The only people I have ever heard give this answer are untrained people who have a basic knowledge of how a capo works on a guitar. What they tend to do is shift the capo to the same fret every time and don't realise that capo on the 3rd fret is not always the same key.
Comment: @SaggingRufus - Never heard it from a guitar player, but I understand what you say. Always from a singer who has a little knowledge - or perhaps can remember the name of  one key.
Comment: @Tim just enough knowledge to be annoying. I remember playing in wind symphony and having someone ask the director to transpose the music (for all instruments) 3 times.
Answer: When a singer says that they sing in a certain key, it's just ridiculous.  They sing within a certain range. The vocal range of a specific song is the real issue, not the key.

Singing in a preferred key?


how to escape double quotes with formatting?

Question: i have a csv with columns,
Column_one | Column_two

 1         | apple
 2         | orange
...

import csv
import json

rows=[]
dataRow = {}
with open('input.csv', mode='r') as csvFile:
    csvReader = csv.DictReader(csvFile)
    for row in csvReader:
        rows.append('"{0}":"{1}"'.format(row["Column_one"], row["Column_two"]))
    with open('output.json', 'w') as output_file:
        output_file.write(json.dumps(rows))

I am formatting the output so that i can get output file as such
{"1" : "apple"}
{"2" : "orange"}

but i get results below  , i tried escaping the double quotes with add backlash in front of double quotes, but that just gives me double backlash infront of quotes
{\"1\": \"apple:\"},
{\"2\" : \"orange\"}

Comment: The problem seems to be that you're basically writing something that is supposed to look like JSON, and then using `json.dumps`, which encodes it as JSON again. If you want to write `{"1":"apple"}` with `json.dumps`, then you need to give it a dictionary `{"1":"apple"}`, not a string `'"1":"apple"'`.
Comment: @khelwood - the code i posted is exactly how i'm using it.
Comment: Worth pointing out that your file should also have `[]` since you are dumping a list
Answer: If you want individual objects on each line, then you cannot dump an entire list.
Separate your concerns - parse the file into dict rows, then write a new one.
import csv
def csv2dict(filename):
  with open(filename) as f:
    reader = csv.DictReader(f)
    h1, h2 = reader.fieldnames[:2]
    for r in reader:
      yield {r[h1]:r[h2]}
      # Or to get all column headers to their values
      # yield {f:r[f] for f in reader.fieldnames}

import json
with open('output.json', 'w') as f:
  for d in csv2dict('input.csv'):
    json.dump(d, f)
    f.write('\n')

Outputs
{"1": "apple"}
{"2": "orange"}

Note: You don't really need the DictReader; a regular csv.Reader has index access to the columns.
Answer: You could try like this
import csv
import json

rows=[]
dataRow = {}
with open('input.csv', mode='r') as csvFile:
    csvReader = csv.DictReader(csvFile)
    for row in csvReader:
        rows.append(dict(row["Column_one"]: row["Column_two"]))
    with open('output.json', 'w') as output_file:
        output_file.write(json.dumps(rows, indent=4))

Answer: You are manually creating a string that looks like JSON, and then encoding it again with json.dumps, so you get a JSONified version of a JSON string.
You can write JSON manually if you want:
>>> print('{{"{}":"{}"}}'.format('1', 'apple'))
{"1":"apple"}

or (preferably) you can using the json module to encode a dictionary as JSON:
>>> print(json.dumps({'1':'apple'}))
{"1": "apple"}

But if you do both, you get a JSON representation of an already JSONified string, which looks like this:
>>> print(json.dumps('{{"{}":"{}"}}'.format('1', 'apple')))
"{\"1\":\"apple\"}"


Life after the Box-Cox transformation

Question: Suppose, we have a set of measurements of some quantity in some units of measurement. We also have a nice model that heavily relies on the properties of the Gaussian distribution. The model is tailored for data in some specific units of measurement with some physical meaning behind (like watt, ohm, etc.). It turns out that the distribution of the data does not exactly follow the normal distribution and has some undesired features (like skewness). We apply the popular Box-Cox transformation and obtain a more or less normally distributed data set. The problem now is that we have logarithms, powers, etc. of the original measurements, which contradicts with our nice model.
The question is, what can one do in such a situation? I need to change the model such that it can handle the new data? And in general, if I got everything correctly, why do people what to study transformed data that have lost their physical meaning? Because, at the end of the day, one will, probably, have to return back to the original units of measurement.
Comment: Are you, for example, claiming that an ohm has a privileged physical meaning that, say, 1/ohm does not have?  (This is not true: 1/ohm has a physical meaning too, in terms of conductance instead of resistance.)  Often, a well-chosen Box-Cox parameter *reveals* a physical meaning that was not apparent in the original formulation.
Comment: The cube of the height will be closely related to weight; the square of the height, to skin surface area (and thence to risk associated with dermal contact to contaminants); etc.  Thus, it is not automatic that a Box-Cox parameter will be without physical meaning or completely lack interpretability.  Having said that, evidently it is wise--but not necessary--to limit choices of the parameter to values that might be amenable to interpretation.
Comment: If the model relies on physics and is meaningless after transformations, then you have to remove the normality assumption.
Comment: @whuber, yes, I absolutely agree with you, of course, 1/ohm does have its own physical meaning. What I was trying to say is that, for instance, if you are interested in the human height and you measure it directly, what can logarithm or some power of your measurements do good for you? You have substituted the subject of your research with something completely different.
Comment: @Aniko, yes, probably, the assumption about the normality of the date is incorrect in such a situation, and one should start looking into some other direction of solving the problem. I was actually trying to figure out whether there is a way of improving, justifying the existing model without changing it dramatically, with the only transformation of the input.
Comment: Another possibility is to use flexible distributions such as [this one](http://statistics.open.ac.uk/802576CB00593013/%28httpInfoFiles%29/6E87CF4E11C754A880257789004EEE9F/$file/sinhasinh.pdf) for modelling data presenting departure from normality. Of course, your model might be much more complicated, but C'est la vie. There is a funny 'psychological concept' [leptokurtophobia](http://www.qualitydigest.com/inside/quality-insider-column/do-you-have-leptokurtophobia.html) for the 'abnormal need for normal distributions'.
Answer: First of all, if you  mean a linear regression model, it does not assume the data are normally distributed, it assumes the error as estimated by the residuals is normally distributed (in fact, they should be iid $\mathcal{N}(0,\sigma)$).
Second, if that assumption is violated and you want to keep your original units, you  can use some other form of regression - there are a variety of robust regression models, loess models, spline models, etc.
Comment: @Peter, if the errors are not Normal the cures you suggest may not help, or may not be required. E.g. if the mean is specified correctly, and the errors have constant variance, Normality is a non-issue for inference on parameters in the mean. (See e.g. McCullagh and Nelder) Fitting a spline representation of a covariate helps the mean be "less wrong", but does nothing about non-constant variance. "Robust regression" (not use of robust standard errors) provides robustness to erroneous data, but can reduce the influence of the most informative good data points.
Comment: I am sorry, I should have explained the context better. By model I did not mean a linear regression model, I meant a mathematical formulation of a physical system. In other words, there is an equation $f(a, b, c, d)$ describing how the system evolves and one of the arguments is assumed to be uncertain, let say $a \sim \mathcal{N}(\mu, \sigma^2)$, so we have its nominal value, $\mu$, and some deviation, $\sigma$, from it.
Answer: It sounds like your model is of this form; $$Y_i|x_i = f(x_i, \beta) + \epsilon_i,$$ where $Y_i$ denotes the $i$th measured outcome, $x_i$ is a vector of covariates for that outcome (i.e. experimental circumstances), which with (unknown) parameters $\beta$ determines the expected value $f(x_i, \beta)$ for that observation. The $\epsilon_i$ are the error terms, which describe everything that affects $Y_i$ not captured by $f(x_i, \beta)$ - i.e. experimental errors.
Before getting into analysis, it's always good to ask "why do you want to do this analysis?". The answer to this question determines how much you should worry about Normality, or whether a transformation is needed. Suppose, as is common, you want inference on the value of $\beta$. If you believe that  $f(x_i, \beta)$ captures the mean value of $Y_i$ correctly, and you believe that $Var(\epsilon_i)$ is the same for every measurement, then classical linear regression can be used for inference about the value of $\beta$. Despite what many textbooks advise, you do not need Normality here; in reasonable sample sizes your confidence intervals and tests will be almost perfectly-accurately calibrated.
If you still want inference, but don't believe the constant variance, use robust standard error estimates. If you don't believe the mean follows $f(x_i, \beta)$ or that the variance is constant, robust standard error estimates still give you accurate inference on the best-fitting line of the form $f(x_i, \beta)$, where "best-fitting" means "least-squares". And if you don't believe the mean follows $f(x_i, \beta)$, or that the best-fitting line of this form is a useful thing to know, you can always fit a more flexible mean - spline representations of covariates $x_i$ are a good way to do this. Absolutely none of the methods listed require Normality - or transformations of the $Y_i$.
So when do we require Normality? If you want to do predictions, of new $Y_i$, for most methods you'll need a model (though it need not assume Normality). If you want to compare models, well, you'll need some models, but that's a tautology. If you have a tiny sample size, doing model-based inference on $\beta$ may be the only viable approach - but then you'd likely have no way of assessing whether your assumption of Normality (or whatever you assumed) was reasonable.
When do we need Box-Cox? If we have little idea about the form of $f(x_i, \beta)$, but believe that errors around $f(x_i, \beta)$ "should" be Normal, then Box-Cox may help find a better form for $f(x_i, \beta)$. But it relies on there being underlying Normality, at the "right" model, and this is hard to justify in many situations.
In short, rather than deal with hard-to-justify transformations, there is a lot you can do with just a mean model. If the original units of measurement help you (and your colleagues) think about what the data tells them, I recommend hanging on to those units, if possible.

Life after the Box-Cox transformation


Regression on means of log-transformed variables

Question: Suppose that I want to study the relationship between two variables $Y$ and $X$ using the linear model $Y \sim X$. Unfortunately, both $Y$ and $X$ are not normally distributed, say they are both skewed and have long right tails. So I'd do the trick of log-transforming both of them to make them look more like bell-shaped and do the regression.
Now I consider doing something quite different. Say I have $n$ independent observations of $(X, Y)$. Suppose that $n$ is a very large number. Now I'd do $k << n$ iterations of the following process to get $k$ independent observations whose both dependent and independent variables are guaranteed to be normally distributed: For each iteration $i$, I randomly sample  $m$ pairs of $(y_i, x_i)$, I then do the log-transformation on those $m$ pairs and take the average, call them $(\bar{y}_i, \bar{x}_i)$. I finally do the linear regression on those means of samples $(\bar{y}_i, \bar{x}_i)$ -- there are $k$ of them.
My question is: Will the two methods described above produce the same results? That is, are they equivalent? Or are they completely different from each other? Which one would you choose if you want to look at the relationship between $Y$ and $X$ using a linear model?
Comment: It is clear the two approaches are different, because your proposal fails to obtain (correct) information about the *uncertainty* in the estimates. So in what sense do you mean "equivalent"?
Comment: "equivalent" means the linear regression results of the two methods (coefficient estimates, etc.) will be more or less the same. In other words, they both arrive at the same relationship between X and Y.
Comment: Please explain how we are to construe "more or less": if that doesn't mean *exactly* the same, then how are we to determine how close is close enough?  (We would have a built-in way to do that if your procedure provided accurate error estimates, but it does not.)
Comment: It seems like you could simulate date under one "model" and then estimate the relationship with the other.
Comment: For intuition, suppose $Y = X$ up to a relatively small (independent, homoscedastic) random error and that the values of $X$ are skewed. Then the values of $Y$, looking like those of $X$, will also be skewed: but you would have no reason to, and gain no benefit from, taking logarithms. For intuition about your method, consider that most of the averages $\bar{x}_i$ will be close to the mean of all the $x$'s and most of the $\bar{y}_i$ will be close to the mean of all the $y$'s. Thus any regression based on them will grossly *extrapolate* to the full range of $x$'s and probably be wildly wrong.
Answer:
Suppose that I want to study the relationship between two variables Y and X using the linear model Y∼X. Unfortunately, both Y and X are not normally distributed,

There is no distributional assumption about the $X$'s in linear regression; they are simply conditioned on.
There is actually no distributional assumption about the $Y$'s either; they're only required to be conditionally normal (that is, the error term is assumed normal; the distribution of the $Y$'s will depend on the particular arrangement of the $X$'s). In any case it's only the distributional inferences that depend on the conditional distribution of the $Y$'s (and in large samples, perhaps not so much even then; prediction intervals would more strongly depend on normality of course).

So I'd do the trick of log-transforming both of them to make them look more like bell-shaped and do the regression.

Don't transform the $X$'s to make them bell shaped. Don't transform $Y$'s to make them bell-shaped. There may be a point to transforming the $Y$'s if it makes the residuals more normal but then you have to be very careful about what you're actually doing and why. (In any case, conditional heteroskedasticity may be more of an issue than nonnormality.) There can be a point to transforming the $X$'s but it isn't to make them normal - you might do it to make the regression more linear for example.

My question is: Will the two methods described above produce the same results? That is, are they equivalent?

No.

Or are they completely different from each other?

Completely? No. For example, they'd share a common mean point, I think.

Which one would you choose if you want to look at the relationship between Y and X using a linear model?

I'd think much more carefully about the point of what I was doing and the actual assumptions before attempting to solve a problem I don't necessarily have.


Possible to use cross validation for final evaluation?

Question: Can k-fold cross validation be used for a final evaluation of a model? I have highly imbalanced and small dataset, which would make it difficult to evaluate on a small test-sest. I know that k-fold cross validation is usually just used for model selection, but if i do not select a model and dont optimize any hyperparameters or choose a model by evaluating its results on the data, is it okay to use cross fold validation instead of hold out? If yes, does anyone have exmaples of research where this was done?
Answer: Yes, this would be fine as no information from the test set in each fold has "leaked" in to the design of the classifier, so it would give an unbiased performance estimate (of the performance of a classifier trained on 100*(k-1)/k percent of the available data).
However, if it is a small dataset, I would recommend using bootstrapping instead as this is likely to have a lower variance and gives an unbiased performance estimate.  I'd also used bagging (which you get for free) which is likely to give better performance, and the out-of-bag estimate can be used for evaluating the performance of the ensemble.
Comment: For bootstrap validation see e.g. [RMS](https://hbiostat.org/rms) - book, course notes, or live course.
Comment: I am not familiar with bootstrapping, I will look into it. Do you know of any research I could cite where it was done like this? I could not find any but i would really prefer to be able to cite some.
Comment: It is difficult to think of a specific paper as I mostly work on models which require hyper-parameter tuning, however I think k-fold cross-validation is sufficiently common as not to really need a reference to a previous study ( a reference to a good text book should be fine)


Binary division: 1/11

Question: The exercise in the book goes like this: In the decimal system the fraction 1/3 is written as 0.3333... (pure periodic number). What happens in the binary system?
So I've been practising with other divisions in binary and, comparing my result with an online calculator (https://ncalculators.com/digital-computation/binary-division-calculator.htm) everything seems to go smoothly. However, when it comes to this particular division the result differs greatly:
1/11 in binary-->

According to me = 0,01010...
This is the logic I follow: 1 divided by 11 is impossible, so I need to add a '0' to the one and a 0 to the quotient as well. Thus, 10/11. Still not possible to divide, hence I add another '0' which turns into 100/11; another 0 to the quotient. NOW I can divide.
According to the online calculator = 10101010,1

Why is that? Why does the comma come so further away from where I put it?
Comment: Your result looks correct to me.
Comment: You should give a link to the online calculator.  Put this link in your original post, rather than as a response to this comment.
Comment: Welcome to MSE! The calculator says the result is $1.01010101...$ (although 100/11 is not what you originally wanted to calculate), instead of what you wrote. Could you please edit your post and fix that? Thanks
Answer: Yes, in binary the fraction $\frac13$ is written as $0.01010101\ldots$ That's so because what $0.01010101\ldots$ means is$$\frac1{2^2}+\frac1{2^4}+\frac1{2^6}+\cdots$$and the sum of this series is$$\frac{\frac14}{1-\frac14}=\frac13.$$
Comment: I use the formula$$a+ar+ar^2+ar^3+\cdots=\frac a{1-r},$$with $a=r=\frac14$.
Comment: Thank you, it's a different way of seeing it.
Comment: Also, sorry for bothering you, but could you disclose a little bit the process that led you to that conclusion? For example, I don't know how a fraction ended up on top. (It's been very long since I went to school, please bear with me)
Answer: @LocoVoco Thanks for your discussion, the issue has been now fixed.
binary division calculator
Comment: Welcome to MSE. This should be a comment, not an answer.

Binary division: 1/11


Postgres createdb: command not found Mac OS Terminal

Question: After su postgres and typing of my password in my macOS terminal, it shows bash-3.2$
What when I type command like createdb, it says:

bash: createdb: command not found

I googled and it says "either PostgreSQL was not installed at all or your shell's search path was not set to include it."
How can I fix this?
Comment: The duplicate answer has been removed so should the duplicate flag be removed?
Comment: The answer below didn't help me but I did find the answer "brew install postgresql" here: http://stackoverflow.com/a/22285440/908677
Comment: https://web.archive.org/web/20140530110851/http://stackoverflow.com/questions/23261005/install-postgresql-in-mac-os
Answer: Before typing in su postgres type in which createdb which will tell you what the path is for createdb.  For example if which returns /usr/local/bin/createdb, you would add that path to your environmental variable $PATH by typing  export PATH=$PATH:/usr/local/bin in the command line once you type su postgres.  Then you can run createdb.
Alternatively, you can just specify the full path in the command line /usr/local/bin/createdb.  If you need to do this often, you can add the line to change the PATH variable in ~/.bash_profile.
Comment: Thx for the help but it says "createdb not found" after I typed "which createdb"
Comment: Try  (you should install homebrew first):```brew install postgresql```
Comment: @user3315620 Have you installed postgres?  How did you do it, and where was it installed?
Comment: I downloaded it from the website and put it(PostgreSQL 9.3) in /Applications
Comment: The PostgreSQL 9.3 file consists of Application Stack Builder, Documentation, pgAdmin III, Reload Configuration, SQL shell(psql)
Comment: I also had this sam headache when installing postgres from the official installer. DONT USE IT.


Calculating form values using jquery

Question: I have a php generated form code:
echo "<select id='num".$result['id']."' name='num".$result['id']."'>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
      <option value='5'>5</option>
      <option value='6'>6</option>
      <option value='7'>7</option>
      <option value='8'>8</option>
      <option value='9'>9</option>
      <option value='10'>10</option>
      </select>
      	";
echo "<input type='checkbox' value='".$result['sell_price']."'                    name='".$result['id']."' id='".$result['id']."' />	";

As you see the value of the select box is already defined and the value for the checkbox is obtained from the database.
I want to calculate the values of the checkbox and product the sum with the value of the selectbox using jquery.
I have this function to "onclick on any td the checkbox is selected" :
$(function () {
    $("td").on(\'click\', function (e) {
        if (! $(e.target).closest(\'select\').length ) {
           var tr  = $(this).closest("tr"),
               chk = tr.find("input[type=\'checkbox\']").get(0);
           if (e.target != chk) {
               chk.checked = !chk.checked;
           }
           if ( tr.find("input[type=\'checkbox\']").is(":checked")) {
               tr.css("font-weight", "bold");
           } else {
               tr.css("font-weight", "");
           }
        }
    });
});

Any help please?
Comment: Why are you escaping your single quotes? Besides that, what problem are you actually having?  Do you get errors in console? Are you getting unexpected values?  can you put your code into a fiddle for easier testing?
Comment: becuse i'm writing it on php echo command
Comment: It might help to show you actual javascript source output and your HTML source.
Answer: if you want to calculate the sum of all selected check box then
 function calculata() {
     var sum=0;
     $('#your_div_Id :checked').each(function() {
       sum=sum+($(this).val());
     });
  }

if you want an array of  values
var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["10", "11", "07"]

Comment: 1) changed #your_div_Id with yours ? 2)tried alert(sum); after sum=sum+($(this).val());   3)called calculata()?
Comment: yes ,,
bro just edit my js code to me ..
i have a table without id ,, and all information u need is here .
also i wanna product the sum on the select box value

Calculating form values using jquery


Problemas com encoding em página estática

Question: Eu tenho um arquivo html enviado de um servidor Node.js que pode ser acessado aqui que está com problemas com a acentuação.
Eles estava funcionando normalmente, porém, após uma pequena atualização, ele ficou com esse problema. Quando eu o abro com o localhost, funciona, mas pelo domínio, não. Alguém tem alguma solução?
Desde já, obrigado.
Comment: Na hora de salvar, ele não salvou o arquivo na codificação UTF-8. Por isso a acentuação ficou incorreta. No notepad++ é assim: "Settings -> Preferences -> New Document/Default Directory to automatically convert ANSI files to UTF-8 without BOM on open", no ATOM fica embaixo https://cdn-business.discourse.org/uploads/github_atom/original/3X/a/e/ae6b226e5f378682dd456cd4d0b11c78b8bc907d.PNG
Comment: Qual IDE você utilizou ao salvar o arquivo? (Notepad++, PHPDesigner, Brackets, Atom, etc)
Comment: Eu usei o atom.
Comment: @Everson, obrigado pela luz que me destes. Na resposta eu explico rsrs.
Answer: Problema resolvido, a hospedagem conta com um editor online de arquivos e como era uma pequena atualização, eu o utilizei. Porém ele salvou o arquivo em algum outro encode que não utf-8. Dessa vez, salvei no atom e subi, e agora está tudo certo.
Comment: Como suspeitei hehe


Can a function be analytic and satisfy $f\left(\frac 1 n\right) =\frac{1}{\log{n}}.$?

Question: Let $\Omega = \{z\in\mathbb{C}:\,|z|<2\}$. Prove or disprove that there exists an analytic function $f:\Omega\rightarrow\mathbb{C}$ such that for $n\geq2$:
$$f\left(\frac 1 n\right) =\frac{1}{\log{n}}.$$
Usually this question would fall under the uniqueness theorem for analytic functions; an example where the uniqueness theorem works is in disproving the existence of an analytic $f$ satisfying $$f\left(\frac 1 n\right) =\frac{(-1)^n}{n^2}.$$
But in the case of the $\log$, I think the issue of existence is more "substantial".
Is it true that if such $f$ were to exist, then $f(z) = -\frac{1}{\log z}$? And if so, what is the main reason this function cannot be analytic in $\Omega$?
Thanks in Advance!
Answer: Assume that such a function exists. Then (by continuity) $f(0) = 0$. Thus we can write
$$
f(z) = zg(z)
$$
for some holomorphic $g$. Plug in $z=1/n$ to get
$$
g(1/n) = nf(1/n) = \frac{n}{\log n}
$$
but if we let $n\to\infty$, it follows that $g$ is unbounded near $0$, which is a contradiction.
Comment: This is very Neat! Thanks!
Answer: If we require $f(z)$ to be analytic then $$f(z)=-\frac{1}{\log z}\tag1$$
is the only solution, because having a function defined at an accumulation point of its domain, we can expand it to its whole domain. The accumulation point in this case is $z=0$. Function $f$ cannot be analytic at $\Omega$ as $(1)$ isn't.
Comment: This needs some elaboration. You seem to be using the identity principle but $f$ is not analytic near the accumulation point in question.
Comment: I have to agree with @mrf. This seems like a circular argument.


MICE implementation in python

Question: I am trying to use MICE implementation using the following link:
Missing value imputation in python using KNN
from fancyimpute import MICE as MICE
df_complete=MICE().complete(df_train)

I am getting following error:

ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

On the link also, it says that they have replaced with NaN. I am not sure what does it mean? I have already tried: df_train.isnull(np.array([np.nan, 0], dtype=float)) but it is not helping either.
Answer: df_train_numeric = df_train[['Age']].select_dtypes(include=[np.float]).as_matrix()
df_complete=MICE().complete(df_train_numeric)

Thanks to Data imputation with fancyimpute and pandas
Answer: This error usually happens when you deal with None values. Have you tried:
df_train.fillna(value=np.nan, inplace=True)

instead?

MICE implementation in python


In which music should I add my own embellishments?

Question: I know that music from the baroque era was composed with the assumption that  performers would add their own embellishments (when viable, not for canons or fugues). I've also heard that Mozart didn't write out all details, but assumed that the performer would realize the music on his own.
I have two questions regarding this: For which music should I not do this? Does this practice end at Beethoven's era? I've heard that it was over by Wagner's time. I just want to know which music is considered incomplete without further creativity by the performer(s), and which is not.
My second question is: Do all roles get to do this, or only continuo? Because if all roles get to add stuff, then I, as a harpsichordist, have to be much more careful with what I add in addition to the written notes. If, however, I know exactly what every one else will be playing, then I can more confidently come up with my own parts, knowing that they will work harmonically and contrapuntally with the rest of the music.
If every role got to add, then I'd personally only do it to chord based music, while sticking to chord tones. If only I got to add, then I'd do it to any music in a way that maintains counterpoint, and which doesn't add dissonance.
Edit: Naturally, I will add what I think sounds good, or add naught at all if that's what I prefer. I am not asking for artistic guidance. What I wonder about is the intention of the composer. During which time period was the written score considered the complete and final music? When did the norm of realizing the music in one's own way end?
Comment: @Dekkadeci - yes, we can. Jazz existed in those early days - it just wasn't called 'jazz'.
Comment: Shoot, based on the tags, I don't think we can answer with jazz-based answers.
Answer: I once owned a little manual on ornamentation, written in the first half of the 20th century, that in the introductory remarks offered some horror stories of excessive ornamentation.  Mostly singers (and they still do it, listen to any pop diva) but I was struck by the Victorian trombonist who reportedly presented the majestic introduction to Mozart's 'Tuba Mirum' obscured by excessive rubato and melodic embellishment.
Yes, it's pretty accepted that a continuo player would do more than just strum out the chords.  And we're told that a repeated section in a baroque keyboard piece would have been considered incomplete without some extemporized variation or embellishment.  Although there's little room for variation in a Beethoven symphony,  I sometimes wonder whether, when performing his piano solo works, he like the jazzman 'never played it the same way once'.
Styles change.  We maybe worship the notation a little TOO much today. Although it irrites me, the audience seems to like what Whitney Houston did to 'I will always love you'.  Where there's room for embellishment (and ONLY where there's room) give it a try.  Be prepared for criticism if you do it in post-Baroque (and pre-jazz) music though :-)
Answer: First off, I think there is no should or shouldn't.
Also, I think pop and jazz musicians can inspire us to understand that it's lots of fun adding your own bit to the music.
I think most composers in those days did. If people complained about obscuring the music, it means it mist have happened enough to irritate this person enough to spend time and paper on it.
Ultimately, improvisation is fun and not playing things the same way is much more challenging then repeating the same interpretation all the time.
So experiment, I would say. Try what you like, and try it a few times because the first few ornamentations in Beethoven symphonies or Bach cantatas may feel sacrilegious, and the next few plain wrong, and then maybe just bad  etc.
You might be interested in my ensemble. We do lots of improvisation coming from the baroque corner, but also we have a few teaching videos.
Comment: Beethoven "(spent) time and paper on" writing out cadenzas for some of his concertos--something which was previously unheard of. He probably figured people had "(obscured his) music" often enough in that case.
Comment: Unless he did it to help some performer who couldn't figure out what to play. That's a possibility.
Answer: In my personal opinion you can feel good about embellishing any piece of music.  I think the situation is not one of does the style allow for it but whether your job allows for it.
What I mean by that is, it would not be advisable to improvise or embellish your lines if you are the 8th seat in the second violin section and you are performing Mahler's 4th (a personal favorite of mine).  But if you are a solo performer or soloist with a backing group the sky is the limit (tastefulness being a consideration).
I used to think that classical was meant to be played as written in a "strict" sense.  But that isn't really true.  In classical guitar music for example it is expected that one will add embellishments (and many instructors teach how to do this).
If you are asking what is allowed or not allowed there may not be an answer.  Music is art and in reality anything is allowed.  If you asking what is expected again this is somewhat subjective.  If you are asking how ti do it I'd say listen to recorded versions of music played by different soloists and follow the sheet music to see where embellishments are used and what type.


Proving uniform continuity of $f(x) = x \sin{\frac{1}{x}}$ on $(1,2)$ directly from the definition.

Question: Before this is marked as a duplicate, I have already looked at the answers here and here.
I believe my question is different because I want to do this proof directly from the definition. The proof given at the first link uses the property of compactness, Lipschitz continuity and derivatives to support the argument. However, my professor's real analysis approach has not been that of metric spaces and, additionally, Lipschitz continuity has not been discussed yet so I'd like to avoid them for now and attempt this proof directly from the definition. I'm interested in a proof similar to the second answer given on the first link but, unfortunately, there are no comments on whether or not it is correct.
The question is to determine whether or not $f(x) = x \sin{\frac{1}{x}}$ is uniform continuous on $(1,2)$.
I present my own attempt:
Given $\epsilon>0$, let $\delta= \frac{\epsilon-1}{2}$ Then $|x-y|<\delta \implies$ $$\left | f(x)-f(y)\right | =\left | x\sin \left(\frac{1}{x}\right)-y\sin \left(\frac{1}{y}\right) \right|=
\left |(x-y) \left( \sin \left(\frac{1}{x}\right)+\sin \left(\frac{1}{y}\right) \right) -x\sin \left(\frac{1}{y} \right)+y\sin \left(\frac{1}{x} \right)\right|
\leq \left |(x-y) \left( \sin \left(\frac{1}{x}\right)+\sin \left(\frac{1}{y}\right) \right)\right| + \left|-x\sin \left(\frac{1}{y} \right)+y\sin \left(\frac{1}{x} \right)\right|$$
$$\leq \left |x-y \right| \left |\left( \sin \left(\frac{1}{x}\right)+\sin \left(\frac{1}{y}\right) \right)\right| + \left|-x\sin \left(\frac{1}{y} \right)+y\sin \left(\frac{1}{x} \right)\right|$$
$$\leq 2\left |x-y \right|+1 < 2\cdot (\frac{\epsilon-1}{2})+1=\epsilon$$
Any help is appreciated.
Comment: @amWhy The answer has **3** upvotes, not 10. The one with 10 is the one that was accepted by the OP which is the one that uses the approach I'm trying to avoid.
3 is definitely not a very highly upvoted answer. It's possible that perhaps 3 other users that used a similar approach upvoted that answer to attract some attention.
Comment: @amWhy I hope that explains why I had to post a separate question. I really need input on this approach, but now that it has been marked as a duplicate how will I get any assistance on this approach? Again,  I'll add that that answer had no comments  and only 3 upvotes so surely one is not immediately expected to conclude that it was _very well received by the community_.
Comment: @amWhy I get you, but what if I need input on _this specific approach_? I did, after all, also add a tag of proof verification. And according to the guidelines, if a  question has been asked before and already has an answer but those answers do not _fully address your question_, you can ask a new question.
Comment: I did not see your proof-verification tag.  I will reopen, and perhaps emphasize that you are seeking feedback on your proof.
Comment: The answers at the duplicate link are both upvoted, one is accepted by the asker, and the other has 10 upvotes, hence *very well* received by the community.  The fact that a highly upvoted answer has no comments is not sufficient reason to ask the question again.
Comment: Yes, I see I got the descriptions mixed up.  But for an answer posted three years after the original question, the fact that it received 3 upvotes indicates it was very well received.  (Later posts, over time, are less visible, though they are always reviewed, and it is only the rare very good late answers that get more than an upvote or two.
Answer: The problem with your approach is that $\delta = \frac{\epsilon - 1}{2}$ is not a very good choice of $\delta$: what if $\epsilon-1<0$? Here is a correct solution.
We have that $|\sin(s) - \sin(t)| = \left|2\overbrace{\sin\left(\frac{s-t}{2}\right)}^{\leq \frac{s-t}{2}}\underbrace{\cos\left(\frac{s+t}{2}\right)}_{\leq 1}\right| \leq |s-t|$ for any real $s,t$.
This implies that $|\sin \frac{1}{x} - \sin \frac{1}{y}| \leq \left|\frac{1}{x} - \frac{1}{y}\right| = \left|\frac{x-y}{xy}\right| \leq |x-y|$ since $xy \geq 1$, since $x,y \in (1,2)$.
Consequently, observe that $$\left|x\sin \frac{1}{x} - y \sin \frac{1}{y}\right| = \left|x\left(\sin \left(\frac{1}{x}\right) - \sin\left(\frac{1}{y}\right)\right) + \sin\left(\frac{1}{y}\right)(x-y)\right| \leq \overbrace{|x|}^{\leq 2}\underbrace{\left|\sin \left(\frac{1}{x}\right) - \sin\left(\frac{1}{y}\right)\right|}_{\leq |x-y|}$$ $$+  \  \underbrace{\left|\sin\left(\frac{1}{y}\right)\right|}_{\leq 1}|x-y| \leq 3|x-y|
 < \epsilon$$ provided we choose $\delta = \frac{\epsilon}{3}$.
Comment: Thanks! Now I see why my delta isn't a good choice. I was thinking, what if, say, I took the absolute value instead? i.e $\delta =| \frac{\epsilon - 1}{2}|$? Then realised there'd be a problem if the numerator were $0$. So my question is that is it a general strategy to not have the choice of $\delta$ depend on a value that includes something like $\epsilon -a$ where $a>0$?


Has deconvolution been applied to nodes in a sensor network?

Question: Convolution, and blind deconvolution, is generally applicable where there is some "truth" function describing a physical process, and then some kind of distortion.
I have a bunch of sensors in a network that sense various parameters about the environment, and I'd like to see whether blind deconvolution could be used to deduce the most accurate point spread function.
Has anyone had experience with this, and would recommend the application of deconvolution to a sensor network?  Thanks, much appreciated.
Answer:
Has deconvolution been applied to nodes in a sensor network?

Probably yes, maybe not, the question in the title is too broad.

I have a bunch of sensors in a network that sense various parameters about the environment, and I'd like to see whether blind deconvolution could be used to deduce the most accurate point spread function.

You could always start with simulations and experiment what kind of noise levels the approach tolerates. If it does well in the simulations, and the results from a real environment appear to make sense too, you might have something there.

Has anyone had experience with this, and would recommend the application of deconvolution to a sensor network?

I can suggest something that I believe would be very novel in many fields of science regarding the use of deconvolution methods.
The convolution model is $h = f \star g$, where $h$ is an observed signal, $f$ is some source signal, and $g$ is the magic from the environment/point-spread function/filter depending on how you want to look at it. The $\star$ denotes convolution.
Now, it is known that convolution in the time-domain is equal to multiplication in the frequency-domain. That fact is known as the convolution theorem. So, suppose you transform the signals into frequency-domain. What happens for the mixing process? It becomes instantaneous, since you now multiply $f$ and $g$ instead of convolute.
So now what? If you have any instantaneous mixing model $\mathbf{x} = \mathbf{As}$ where only $\mathbf{x}$ is known, you can solve $\mathbf{A}$ and $\mathbf{s}$ with only few assumption (note that this applies to multivariate data too, as I indicate with the bold type face). The solution can be found with independent component analysis.
If you got interested, search for FastICA (an ICA algorithm developed by Aapo Hyvärinen) or InfomaxICA (an algorithm developed by Bell and Sejnowski). Don't miss a Matlab software package called 'Icasso', neither.
PS. If you do it I'd like to be a co-author :-)


Outlook 2007 does not refresh inbox upon receipt of new email

Question: We have a user in our office who recently reported that Outlook 2007 is having trouble displaying newly arrived messages.  If he changes to another folder and then comes back to the inbox, the messages show up immediately.
Environment

Windows XP SP3
Office 2007 build (12.0.4518.1014)
Pop3/SMTP account

His outlook.pst is large (~2.2GB), though we have many other users with .pst files bigger without this trouble.
Googleing suggests that an add-in like Google Desktop or MS Search could be causing the problem.  He has never had any extra add-ins installed...  Just in case, I have disabled all the build-in add-ins from the trust center, except for VBA, which is required for some auto-updating spreadsheets we use for contact management...
Any ideas would be appreciated.
Comment: Was the PST created in Outlook 2003+?
Comment: No, but it was imported from a 2003 .pst.  Why? Is there a known issue with a 2003 .pst file in 2007?
Answer: I've seen similar problems in the past arise from the use of the "Used Cached Exchange Mode" setting.  You can find the checkbox for that on the Account Settings/Microsoft Exchange Settings page in the Outlook config.
In the environment I was in, any user that had that setting turned on would have to manually check for new messages, via folder switching or "Send/Receive" whereas anyone without the setting saw mail the second it hit their inbox.
Comment: Ah, forgive me.  When I think "Outlook" I immediately think "Exchange."  Shouldn't have made that assumption!
Comment: Thanks for the suggestion, but...
We are not using exchange.  This is an Internet mail Pop3/SMTP setup.  I don't have a Microsoft Exchange Settings page.
Answer: 1) Does the user have Google Desktop Search installed?  If so, disable the outlook add-in and restart Outlook.
2) Can you do an update to Office 2007 SP2?
3) A farfetched answer I've heard is that the user must be a participant in the Customer Experience Improvement Program.  Close Outlook, open Word, click the office button, click Word Options, click Trust Center, click Trust Center Options, click Privacy Options, and select the option for the Customer Experience Improvement Program (4th option).  Then close Word and restart Outlook.
Comment: Good catch on #2.  He indeed did not have SP2 installed even though we are using WSUS, his machine apparently failed to install it or he canceled it.  Points are yours.
Comment: Who would have thought it? This worked for me: > 3) A farfetched answer I've heard is that the user must be a participant in the Customer Experience Improvement Program. Close Outlook, open Word, click the office button, click Word Options, click Trust Center, click Trust Center Options, click Privacy Options, and select the option for the Customer Experience Improvement Program (4th option). Then close Word and restart Outlook.
Answer: I had the same exact problem, My outlook inbox would not automatically update when someone would send me an email. I would have to manually update the folder via Send/Receive.
I unchecked the "Use Exchange Mode", shut outlook down, restarted, rechecked to "Use Exchange Mode" and everything is flowing in flawless!
Answer: Copy the PST as a backup.
Anytime things get flaky w/ Outlook it's a fast test to recreate the Outlook profile.  Set up the new profile with an incorrect pswd until you have connected the existing PST, otherwise you can end up with dupe msgs.
If this fixes it then rename the .NK2 file to the new profile name and you're done.
If it's still happening:
Confirm the drive hasn't been compressed or isn't running out of space.
Confirm only 1 AV/anti-malware/anti-spyware app is running.
Disable AV temporarily.
Test - if OK now then resolve AV issue or:
Close Outlook
Run ScanPst, fix errors.
Compress the PST.
Test.
Restart AV.
Test.
Clean up the backups, it's easy to end up with 8GB of PSTs laying around.
Answer: I was having this issue in outlook 2016.  My account would download the new email it seemed but it wouldn't show that I had anything until I clicked on the accounts.  I have about 10 IMAP accounts in outlook.
"3) A farfetched answer I've heard is that the user must be a participant in the Customer Experience Improvement Program. Close Outlook, open Word, click the office button, click Word Options, click Trust Center, click Trust Center Options, click Privacy Options, and select the option for the Customer Experience Improvement Program (4th option). Then close Word and restart Outlook."
I went into word and did this.  I opened outlook to verify this was the fix.  Then I went back into word and unchecked it.  Everything is still working now.  NOTE: in 2016 the line item is "Send personal information to Microsoft to make improvements."


Get the inner HTML of an  tag

Question: I am building a dynamic menu for a responsive page in which the left side menu hides and turns into a different menu using the slicknav solution.
Now, what I want to do is for the left menu's first link to become the title of the menu.
I can't give the  tag that I need an ID because the menu is hard coded, so I need a different solution to find the inner HTML of it.
This is the HTML that I have:

My List title

Item 2

Item 3

Item 4

And this is what I've been able to do with some programing to get the label of the menu to be the "My List Title" from the HTML above:

What am I missing?
Answer: getElementsByClassName is plural, it returns all the elements with the given class name, so it returns a NodeList not a single HTML Element.
You need to treat it like an array and either pull the first item off it or loop over it with for.
Alternatively, since you are using jQuery, just use jQuery. The html() method will give you the inner HTML of the first element in the jQuery object.
jQuery('.nav-title').html()

Answer: Since you're already using jQuery, use its selector to find the single element instead getElementsByClassName, which can return multiple elements.
$("#child_nav li.nav-title:first a").text();

Fiddle: http://jsfiddle.net/KrFs9/
Answer: This should accomplish it:
var myLabel = $('.nav-title:first').html()

Answer: try like
$(".child_nav li a:first").html()

Answer:

Get the inner HTML of an  tag


Product of Sets

Question: I have a quick question regarding the interpretation of notation in topology. My notes state:
Let $X:=\Pi_{\alpha \in A} X_\alpha$ where A is an indexed set.
My interpretation is that $X=X_{\alpha _1}\times X_{\alpha _2}\times...$ , which in a topological sense would imply what....
Thanks in advance for your help.
Comment: Are you sure that $A$ is specified to be a *directed* set and not simply an *index* set?
Comment: There's no reason for it to be a directed set, unless you're looking at direct or inverse limit systems.
Comment: @BrianM.Scott would it make more sense as an index set? The letter A has not been specified directly in this proposition. However, in previous definitions (of the same notes) it has been presented as a directed set (partially ordered set $(A,\leq)$.
Comment: Sorry: what's the question?
Comment: @BrianM.Scott . I see where you're coming from. Given that A is an index set then, could you please explain how X has been defined? Thanks !
Comment: Will do; hang a bit.
Answer: If, as I suspect, $A$ is simply an index set, $\prod_{\alpha\in A}X_\alpha$ is the set of functions $x:A\to\bigcup_{\alpha\in A}X_\alpha$ such that $x(\alpha)\in X_\alpha$ for each $\alpha\in A$; for convenience I will write $x_\alpha$ instead of $x(\alpha)$. $A$ can be uncountable, so you shouldn't try to think of it as a product of the form $X_{\alpha_1}\times X_{\alpha_2}\times\ldots$.
If each $X_\alpha$ is a topological space, the simplest way to define the topology is to start with the projection maps
$$\pi_\alpha:X\to X_\alpha:x\mapsto x_\alpha\;;$$
then the product topology on $X$ is the one generated by the subbase
$$\bigcup_{\alpha\in A}\left\{\pi_\alpha^{-1}[U]:U\text{ is open in }X_\alpha\right\}\;.$$
In other words, the product topology has as a base sets of the form
$$\bigcap_{\alpha\in F}\pi_\alpha^{-1}[U_\alpha]\;,$$
where $F$ is any finite subset of $A$, and $U_\alpha$ is an open set in $X_\alpha$ for each $\alpha\in F$.
Comment: @eXtremiity: My pleasure; topology is still my favorite field.
Comment: Thank you so much for you help Brian. I appreciate your time and patience.

Product of Sets


Solving $xm\equiv k\bmod p$ for $x$ without linear search?

Question: Given $x, m, p, k \in \mathbb{N}$, is there a way to solve this equation without linear search?
$$x\cdot m\equiv k\bmod p$$
The numbers $m$, $p$ and $k$ are known, $p$ is prime, and $m \le p$, we have to find $x$. We can loop for $x = 0$ to $x=p - 1$ to find the answer, but, can we do it faster?
Comment: Yes, you can do it faster, by finding a multiplicative inverse for $m $ mod $p $.
Comment: When k = 1, what we want is the multiplicative inverse for m mod p, but here k can be greater than 1.
Comment: You give me the multiplicative inverse of $m $ and I'll give you  $x $.
Answer: If $m$ is not prime to $p$, then the congruence will not have a solution unless $k\equiv 0$ (mod $p$), in which case any $x$ solves the congruence.
Otherwise $m$ is invertible mod $p$, hence $x\equiv m^{-1}k$ (mod $p$) is the unique solution. $m^{-1}$ can be computed using the extended Euclidean algorithm, see for instance here.
Answer: If $m=p$ then $k$ must be zero and $x$ arbitrary.
When $0\lt m \lt p$ $m$ is invertible and $$x=m^{-1}k \pmod k$$
The respective calculation depends on the concerned numbers (it could be easy or hard).
Answer: mx= k (mod p) is the same as mx= k+ np for some integer m.  That is equivalent to mx- pn= k, a "Diophantine equation".   That can be solved by using the "Euclidean division algorithm".
For example, the equation 7x= 25 (mod 31) is the same as 7x= 25+ 31n or 7x- 31n= 25.  7 divides into 31 4 times with remainder 3: 31(1)- 7(4)= 3. 3 divides into 7 twice with remainder 1: 7(1)- 3(2)= 1.  Replacing "3" in that equation by "31(1)- 7(4)" gives 7(1)- 2(31(1)- 7(4))= 7(9)- 2(31)= 1.  Multiply both sides by 25 to get 7(225)- 31(50)= 25.  So one solution to 7x- 31n= 25 is x= 225, n= 50.  It easy to see that x= 225+ 31k, n= 50+ 7k is, for any k, also a solution: 7(225+ 31k)- 31(50+ 7k)= 7(225)- 31(50)+ 217k+ 217k= 25.


Android text view with chip type selectable boxes

Question: In my application I am making a search field some what similar to a filter. So I want to achieve my search page some what similar to this Image.  I tried to search for it but could not find what are such scrooling text views with selectable boxes called and after selection the  below box with remove sign which type of layout is that? Please help me with what kind of layout is this and any library for such thing and what are they called.
Thanks
Comment: so you want chip like textviews. means different texts wrapped in a rectangle box with closed sign or negative sign. ? Am i correct ?
Comment: Yes @Ragu Swaminathan
Comment: did the below answer worked for you?
Comment: @RaguSwaminathan No exactly what I am looking for.....I wish if I could get some better solution. THanks
Comment: does any of the below answer helps you?
Answer: I understand that you want to create the checkboxes with your own style. You can achieve this with a few XML definitions. Check the code I am using in one app:
Firstly, define the checkbox:
<CheckBox
    android:id="@+id/btn_team_home"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:layout_weight="0.4"
    android:background="@drawable/selector_match_team"
    android:button="@null"
    android:ellipsize="end"
    android:gravity="center"
    android:maxLines="2"
    android:minLines="2"
    android:textColor="@color/selector_btn_matches_text"/>

The most important attribute here is "android:background"
The background attribute contains a selector that specifies how the view reacts to different events. You can see the code for the res/drawable/selector_match_team below. Also don't forget to set android:button="@null". Other attributes in my checkbox definition are not important for your case.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_checked="true">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/btn_match_radius"/>

        <gradient
            android:endColor="@color/match_picker_match_bg_checked"
            android:startColor="@color/match_picker_match_bg_checked"/>
    </shape>
</item>

<item
    android:state_checked="false">
    <shape android:shape="rectangle">
        <corners
            android:radius="@dimen/btn_match_radius"/>

        <gradient
            android:endColor="@color/match_picker_match_bg_unchecked"
            android:startColor="@color/match_picker_match_bg_unchecked"/>
    </shape>
</item>

Here you can see that the first item is a background for the state "checked". It contains the rectangle shape with rounded corners and background color (gradient attribute). In your case, the commented "stroke" should apply since you want the border around your buttons. The colors and dimensions are not important, so I am not specifying them here.
Since your base view is already a checkbox and you implemented your own selector, you don't have to code anything by hand to handle the background/check states.
Comment: you can change the android:textColor="@color/selector_btn_matches_text"
Comment: how to change the textcolor of the checkbox?
Answer: UPDATE
check this https://github.com/whilu/AndroidTagView
A TagView library for Android. Customize your own & Drag effect.
build.gradle file.
dependencies {
    compile 'co.lujun:androidtagview:1.0.3'
}

Comment: Thanks for your answer. Actually what i am looking for is instead of these chips shown in search box, i want them to be shown separately below search so that user can scroll and select also instead of just search
Comment: using this lib, user can search and select that tag also that is default funtionality
Comment: @@AmitVanghela I finally  used https://github.com/greenfrvr/hashtag-view
 library. Thanks for help
Comment: according to me what is written in your question is different than what you have used rather my suggestions are better.@AnkeshkumarJaisansaria
Answer: I'm not sure whether this library will fulfill your needs. But let you give it a try.
Link : https://github.com/kpbird/chips-edittext-library
Let me know for queries.


Como liberar conteúdo no wordpress após X dias de registro do usuário

Question: Estou desenvolvendo uma área de membros no Wordpress, e preciso limitar o acesso de acordo com a data de registro do usuário. Eu já tenho a data de registro e já tenho a quantidade de dias que o usuário está cadastrado usando a função Diff do php.
Exemplo:
Usuário se cadastra hoje e tem acesso a página X, ele só pode ver a página Y depois de 10 Dias, caso ele tenha menos dias, exibo uma mensagem de erro e com 10 dias ou mais, eu libero a página.
Pode ser plugin, não tem problema.
Comment: você pode suar o `date('suaData', '+10 day'); e verificar com o diff novamente.
Comment: Mas como eu poderia fazer isso com mais de 10 páginas por exemplo? porque todas as páginas usam o arquivo page.php e eu preciso de dias diferentes pra cada página criada.
Answer: Você vai adicionar no banco a data em que o usuário se cadastrou, e criar para cada página uma validação que pega a data atual e compara com a data de cadastro.
If ($diasCadastrado > $diasParaExibir)
{
Include 'suaPagina.php';
}
Essa é a ideia básica, no seu caso basta adicionar no banco o momento em que ele acessou a determianda página


Hook when reading the database

Question: I need a WordPress hook which will able me to change the post content when reading the database for showing content in editor for editing or in browser.
Answer: It sounds like this is what you're looking for.
Taken from WordPress.org:
function filter_function_name( $content, $post_id ) {
    // Process content here
    return $content;
}

add_filter( 'content_edit_pre', 'filter_function_name', 10, 2 );

Edit:
Since the OP has asked for some clarification on what filter priorities do and when to use them, here's an update.
What the $priority parameter is for as defined by the WordPress Codex here:

Used to specify the order in which the functions associated with a
  particular action are executed. Lower numbers correspond with earlier
  execution, and functions with the same priority are executed in the
  order in which they were added to the action.

It's also important to note when removing a filter, priority is also important:
Excerpted from WordPress Codex entry:

Important: To remove a hook, the $function_to_remove and $priority
  arguments must match when the hook was added. This goes for both
  filters and actions. No warning will be given on removal failure.
Comment: Thanks Spencer, I have applied the same last night, but it did not work for me. But here you have added the priorities. So my question is how to know what priorities to set at what time to what hook. Please give me some reference, where I would know more about hook priorities.
Comment: It is not working always. I have four blog articles. There I changed some URL in the database. I have written some code which will change some part of the URL and show it in browse or in admin panel for edit, but it is not coming after first occurrence. Can you help in this thing.
Comment: I've updated my answer with the information you requested in your first comment. I'm not sure I follow your second comment, though. It sounds like it may be outside the scope of this question and should be in a new thread, but I could be wrong since I don't really know what you're asking.

Hook when reading the database


Stationarity in OLS time series and asymptotic properties

Question: I think I lack somewhat deeper understanding of this topic, but I thought stationarity is required in order for OLS to have asymptotic properties.
"But stationarity is not at all critical for OLS to have its standard asymptotic properties"(Wooldridge, 2012)
I thought stationarity is needed or otherwise OLS would not be consistent, but I guess I'm wrong. Could someone tell me why stationarity is not critical for LLN?
Thanks in advance!
Answer: (Stationarity of what? What kind/level of stationarity?)
Given the standard linear regression specification (without any specific stochastic assumptions)
$$\mathbf y = \mathbf X\beta +\mathbf u $$
as a  matter of mathematics we have
$$\hat\beta_{OLS} = \left(\mathbf X'\mathbf X\right)^{-1}\mathbf X'\mathbf y=\beta + \left(\mathbf X'\mathbf X\right)^{-1}\mathbf X'\mathbf u$$
For consistency of  $\hat\beta_{OLS}$  we need (as sample size $n$ goes to infinity)
$$\operatorname {plim}\left [\left(\mathbf X'\mathbf X\right)^{-1}\mathbf X'\mathbf u \right ]= \mathbf 0 \Rightarrow \left(\operatorname {plim}\frac 1n\mathbf X'\mathbf X\right)^{-1} \operatorname {plim}\left (\frac 1n\mathbf X'\mathbf u \right )= \mathbf 0$$
This requires
a) that $\left(\operatorname {plim}\frac 1n\mathbf X'\mathbf X\right)^{-1} < \infty$, and that it converges to a positive definite matrix, which is a condition usually just assumed, and it will be satisfied if the "Grenander conditions" are satisfied (in short, as $n\rightarrow \infty$, no regressor degenerates to a sequence of zeros, no single observation dominates the sum of squares of its series, and the regressor matrix always has full rank). These conditions exclude some kinds of non-stationarity of the regressors, but they do not require  covariance-stationarity (which is the one usually meant under the term "stationarity").
b) that
$$\operatorname {plim}\left (\frac 1n\mathbf X'\mathbf u \right )= \mathbf 0\Rightarrow \left [\begin{matrix}
\operatorname {plim}\frac 1n\sum_{i=1}^nx_{1i}u_i \\
...\\
\operatorname {plim}\frac 1n\sum_{i=1}^nx_{ki}u_i
\end{matrix}\right ] =\mathbf 0 $$
Now Markov's Law of Large Numbers, in order to hold  requires that
$$\frac 1{n^2}\operatorname {Var}\left(\sum_{i=1}^nx_{1i}u_i\right)\rightarrow 0,\; \text {as}\; n\rightarrow \infty$$
Here too, this condition excludes some kinds of non-stationarity, but it does not require covariance stationarity (for example, both the mean and the variance of each $x_{ji}$ and each $u_i$ may be different -we only need that the variance of the sum is of smaller order than $n^2$).
If this condition holds then the Law of Large Numbers applies and we have (abusing notation a bit)
$$\operatorname {plim}\left (\frac 1n\mathbf X'\mathbf u \right )=  \left [\begin{matrix}
\operatorname {lim}\frac 1n\sum_{i=1}^nE(x_{1i}u_i) \\
...\\
\operatorname {lim}\frac 1n\sum_{i=1}^nE(x_{ki}u_i)
\end{matrix}\right ]$$
For this to be equal to the zero-vector we need that each regressor is contemporaneously uncorrelated with the error term, $E(x_{ji}u_i)=0,\; \forall j,i$. This is a condition related to stochastic dependence/independence, and has nothing to do with stationarity.
For asymptotic normality of  $\hat\beta_{OLS}$ we examine
$$\operatorname {plim}\sqrt n(\hat\beta_{OLS} -\beta)= \operatorname {plim}\left[\sqrt n\left(\frac 1n \mathbf X'\mathbf X\right)^{-1}\frac 1n\mathbf X'\mathbf u\right] = \left(\operatorname {plim}\frac 1n\mathbf X'\mathbf X\right)^{-1} \operatorname {plim}\left (\frac 1{\sqrt n}\mathbf X'\mathbf u \right )$$
The first plim was discussed previously. For the Lindeberg-Feller Central Limit Theorem to hold for the second plim, what is required is
a) that each regressor series is comprised of independent r.v.'s,
b) that the errors are independent from each other,
(both these can be relaxed)
c) that the expected values and the variances of the rv's involved are finite, but not necessarily equal
d)and finally that "no term dominates the whole", which is expressed as a condition on the relative magnitude of the variances involved.
So again, some forms of non-stationarity are excluded, but covariance-stationarity is not needed.
Comment: Brilliant, thanks for the info. Indeed I meant covariance stationarity.
Comment: Hi, is there a formal proof for the projection matrix lim→∞P→0 under Grenander conditions (or something similar)? I have asked a [new question](https://stats.stackexchange.com/questions/584553/do-residuals-in-linear-regression-converge-to-mathcaln0-sigma2-i?).


How are driver numbers assigned in F1?

Question: In F1, Drivers have an assigned number. But how are these numbers decided?
Is it

Drivers Choice?
Constructors Choice?
Randomly assigned?

Also, if the number is chosen, who has first pick?
Answer: From 2017 FORMULA ONE SPORTING REGULATIONS:

9) CAR LIVERY
9.2 Each car will carry the race number of its driver as published by the FIA at the beginning of the season. This number must be clearly visible from the front of the car and on the driver's crash helmet.
Prior to the start of the 2014 World Championship season race numbers will be permanently allocated to drivers by ballot, such numbers must then be used by that driver during every Formula One World Championship Event he takes part in throughout his career in Formula 1. A driver's career in Formula 1 will be deemed to have ended if he does not participate in an Event for two entire consecutive Championship seasons.
Any new drivers, either at the start of or during a season, will also be allocated a permanent number in the same way.
The only exception to this allocation process will be for the reigning World Champion who will have the option to use the number one. The number that was previously allocated to him will be reserved for him in subsequent seasons if he does not retain the title of World Champion.

Which indicate they will use the number allocated from FIA by ballot and it is permanent, however reigning World Champion can choose between his allocated number and number one.
However this autosport.com article confirms that drivers were given a chance to choose their preferred number prior to 2014 season.
From article:

The FIA is also keen to ensure that the choice of number is made by the driver, rather than the team that employs him, which is why they are being contacted directly.
Comment: I'm pretty sure the drivers choose their number based on what is available, obviously no two drivers can have the same number.  The ballot referred to by the regulations may be if more than one driver wants the same number.  For example Hamilton chose #44 as it was his number when he was a child karting and kept that number instead of using #1 when he won the championship in 2015 and 2016.
Comment: @davidjwest Sir that autosport article mentions the same. Hamilton must've
chosen 44 as his number prior to 2014 season but after he won world championship he didn't choose 1.

How are driver numbers assigned in F1?


How to convert an integer array into string in javascript without losing the square bracket

Question: I want to access object property. i m not able to access key value without single quotes around the array. when i put single quotes manually it returns value. but how to get single quotes placed automatically. is there any function in java script. if i convert to string using String() function i lose the square bracket. Here is my code:
var seen = {'[7, 6]': '[0, 0]'}
function getParent(childState){
        //"""return parent of state, if it exists"""
        if(childState in seen){ return seen[childState]; }
        else{ return undefined; }
};
getParent([7, 6]);

Comment: `seen` is a key value pair. `'[7, 6]'` is the key and `'[0, 0]'` is the value. So it will work only if you pass key as `'[7, 6]'`
Comment: You'll have to add the brackets manually, and also account for the space, kind of like `'['+[7,6].join(', ')+']'`
Comment: thanks musa it works adding brackets mannually.. but it looks weird
Comment: @AmalHashim i seek a simpler way to do that. if i convert to string i lose square brackets and the spacing between the integers
Answer: In order to use a property accessor, you need to provide a string. That means that the keys in your seen object need to be in a string format. If you want to interact with getParent() using arrays, then you should translate the parameter into a string first. But the values in your seen object can still be arrays.
var seen = {'7,6': [0, 0]}
function getParent(childState){
    var key = childState.toString();
    return seen[key];
};
getParent([7, 6]);

Comment: is there any simple way to convert [7, 6] to '[7, 6]' @StriplingWarrior
Comment: @SudheeshKs: Yes, but I don't understand why you'd want to: '[' + childState.join(', ') + ']'
Answer: You can detect if you are beign passed an array and manually build the string key
if(typeof childState =="object"){
   childstate = "[" + childState.toString() + "]";
}


resolving sub-domain in apache

Question: Not sure how I fixed it, or if I did. might have just been taking forever for the dns to get resolved or something, but it works now. Apparently even though the site I listed below showed everything pointing to the right address, something somewhere wasn't resolving properly.
 --------- original message ---------------
I'm not sure what has gone wrong here, but I've been trying to get a subdomain set-up, and i can't get it to resolve.
I've checked that the domain is set-up properly by typing the url into this site
http://www.selfseo.com/find_ip_address_of_a_website.php
 to check that the subdomain is pointing to the correct server, and it returns my server ip (I also checked a subdomain not set-up, and it doesn't resolve, so that site does work).
So, now i'm figuring the problem must be in my apache config file.
The virtual host details are like this
<VirtualHost *:80>
    ServerAdmin email@example.com
    DocumentRoot /var/www/html
    ServerName mysite.com
    ErrorLog logs/mysite-error_log
    CustomLog logs/mysite-access_log common
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot /var/www/html/liveTest
    ServerName liveTest.mysite.com
    ErrorLog logs/mysitetest-error_log
    CustomLog logs/mysitetest-access_log common
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !\.(php|html|css|js|gif|png|jpe?g)$
    RewriteRule (.*)$ /index.php [L]
</VirtualHost>

i restarted the server, and I get nothing, but going to http://mysite/liveTest works, so the directory structure is all correct.
Any idea what I've got wrong here?
Comment: What do you mean by "nothing"?
Answer: Do you have < VirualHost *:80 > < /VirtualHost> surrounding each of the two code blocks? <-- ok, you have that.
Then have you checked the logs? Maybe try to remove the Rewriting in the second URL, to eliminate possible error sources.

resolving sub-domain in apache


$(123)!$ divided by $(25!)^x$. What is the maximum possible integral value of $x$?

Question: The answer given is $5$. But I am getting $4$.
Here is what I have done.
$$25!= 2^{22}\cdot3^{10}\cdot5^6\cdot7^3\cdot11^2\cdot13\cdot17\cdot19\cdot23$$
$$123!=2^{117}\cdot3^{59}\cdot5^{28}\cdot7^{19}\cdot11^{12}\cdot23^5\dots$$
So, the minimum value comes in exponent of five. It would be $\lfloor\frac{28}{6}\rfloor=4$.
What is wrong with this approach?
Comment: 5 is incorrect, you are right.
Comment: Maybe the question wanted $125!$ ?
Comment: By the way, the product of any $25$ consecutive integers is divisible by $25!$, so you can deduce without any prime factorization that the answer is at least $4$.
Comment: $270!$ or $273!$ would give the answer $11$ rather than $10$
Answer: $\let\leq\leqslant\let\geq\geqslant4$ is correct: it is the largest integer not exceeding the fractions $\frac{\text{exponent of prime p in 123!}}{\text{exponent of prime p in 25!}}$ where $p$ runs through the prime divisors of $25!$.
The minimal fraction is attained when $p=5$, giving $\frac{28}6$, so $x\leq4$ and $x=4$ works.


Why are there no left handed catchers in baseball?

Question: Why is it seemingly forbidden for a lefty to play catcher?
Lefties would have an advantage fielding bunts and throwing to first, as they would already be oriented towards first when getting the ball.
When throwing to second, it seems meaningless which hand to throw from.
Throwing to third would require you to turn around, but I believe that throwing to first, either on a dropped third, bunt, or pickoff attempt is more common than throwing to third.
Is there something I'm missing?
Comment: Having/catching the ball in the left hand seems like it would be an advantage in plays at the plate, though I don't know how much it factors in.
Comment: [This similar question](https://sports.stackexchange.com/q/13414) may provide insight.
Answer: Well, there are a few downsides for left handed catchers, such as throwing out a base stealer at 3B, which would probably happen more often with a left handed catcher, but probably the biggest reason is pointed out in this quote I found in this ESPN.com article:

Distefano offered two explanations. Bunts toward third base, he said, cause problems for left-handed catchers. In scampering to grab the ball, transferring it to their left hand and throwing to either first or second base, their bodies get closed and clumsy. Throws for right-handers are far more open and natural.
But the primary problem Distefano encountered was with plays at home. Because his glove was on his right hand, every accurate throw to the runner's side of the plate would have to be reached for backhanded, impeding a quick tag. And on outfielder throws up the first-base line, reaching out with his right hand would leave his throwing shoulder wide open to the runner.

"If there's going to be a bang-bang play, the left-handed catcher's going to get hurt," he said.
Comment: But wouldn't a RH third baseman also have to do the same thing? Also, compare to a right handed catcher, who would have to pivot 180 degrees on his right foot before throwing.
Comment: I understand the second part, but I don't understand the first. If a bunt is put down the third base line, a left handed catcher upon picking up the ball would be in the correct orientation, right foot(lead throwing foot) closer to first base. A charging right handed third baseman would also have his lead throwing foot (left foot) closer to first base. Both players would be correctly positioned to throw to first.
Comment: @FrankAnderson while true, it'd also cause him to have to throw the ball to 1B across his body in a quick situation.  Now if the catcher got to the ball quickly he'd have time to position his body, but if he picks the ball up with his glove, he's transferring the ball to his left hand and then having to throw across his body to get it back to 1B.
Answer: The most frequent throw a catcher makes (besides throwing the ball back to the pitcher) is to throw out a runner on first base trying to steal second base.  Because it is the most frequent throw, and because it keeps the runner from advancing to a scoring position (runner can score from 2nd base on a single), it is also the most consequential throw a catcher makes.  A large majority of baseball players are right handed and bat right handed.  That means, the majority of time, there is a right handed batter in the batters box. A right handed batter is in the way of the throw to second base from a left handed catcher.  As second based is the farthest base to the catcher every split second counts.  Any impedance to the throw and avoidance of the batter can make the difference between an out or a person in scoring position.
Answer: The tag plays at the plate would become more difficult and the LH catchers can not put swipe tags down. They have to turn their body to tag instead of having the ball travel to the tag.
Answer: I think it can be argued for or against in any situation. I don't believe that a bunt play is why there hasn't been a leftie catcher in the last 20+ years. It would probably stem from the lack of young left handers and their youth coaches trying to utilize them in pitching roles or 1st base. Plus, not a lot of kids like playing catcher and if you're a good youth left handed player, coaches won't risk you getting beat up behind the plate.
Comment: This answer would be improved, and higher quality, if it had citations to back up the assertions being made.


Laravel: The data are not stored properly in the database column

Question: I am having a hard time store the values of 'A' input values array to the database table. as shown in the screenshot. The expected output is that the 'A' values correspond properly to each mfo_id. If 'A' input type is blank then it will be null.

Controller Function(I used var_dump first to check the values before inserting)
    public function storeipcrcsassocp(Request $request)
{

    $store = [];
    for($x=0; $x<count($request->mfo_id); $x++){
        $store[] = [
            "mfo_id" => $request->mfo_id[$x],
            "function_name" => $request->function_name[$x],
            "Q" => $request->Q[$x],
            'average' => $request->A[$x],
            'total_weighted_score' => $request->total_weighted_score[0],
        ];
    }
    var_dump($store);

Var dump output. The average value are the same.

Blade file. the input type are in the for loop
<input type="hidden" value="{{$row->function_name}}" name="function_name[]">
<input type="hidden" value="{{$row->id}}" name="mfo_id[]">
<input type="number" class="form-control form-control-sm" id="total-weighted-score" name="total_weighted_score[]" readonly>

                        @if($row->function_name == 'Core Function')
                                <input type="number" class="form-control form-control-sm a-value-core" name="A[]" style="width: 50px" readonly>

                            @elseif($row->function_name == 'Support Function')
                                <input type="number" class="form-control form-control-sm a-value-support" name="A[]" style="width: 50px" readonly>
                            @endif
                            @if($row->function_name == 'Research and Extension Services')
                                <input type="number" class="form-control form-control-sm a-value-research" name="A[]" style="width: 50px" readonly>
                            @endif

Comment: Have you tried a dump of the entire request to see where your missing info might be located? dd($request);
Comment: Better yet, dd($request->all()) or dd($request->input())
Comment: Hello. I tried to use dd ($request->all()) still throws the same average value for all mfo_ID.
Answer: This is already resolved. Here are the keypoints on how I resolved it

The for loop is correct
There is a  tag accidentally placed before the input type for A[]. After removing it the average values are now captured in var_dump($store) and dd($store) hence, I can now stored it in the database without any errors.


Multi-Site/Application IIS in Hyper-V

Question: As a developer, I have been tasked with creating a new development environment. Currently, our dev environment has 5 different VMS with IIS hosting multiple sites and applications.
I don't know the origin of this choice, but assuming there is no technical requirement that these be on different IIS instances, wouldn't it be more efficient to have everything on a single instance? Doesn't IIS have a proven performance record in multi-tenant situations for web hosting companies?
Comment: The word "efficient" is the key in your question.  If have a different IP address per site then you skip the "host header" section of IIS processing.  Host header processing IS overhead, however "most likely" superficial.
Answer: Yes, it's more efficient to have everything on a single IIS server. Why do you want to manage 5 Windows Servers instead of 1, unless you need load balancing/HA ?
Additionally, it's a development environment, you'll probably not hit performance issues here.
You can take a look at Tuning IIS 10.0 if you are looking for tips/recommended settings.

Multi-Site/Application IIS in Hyper-V


Given a solution $y_1(x) = \cos(x)$, find the General Solution of $2y'\sin(x) + (\sin^2(x)+1)-y^2=0$

Question: The final solution via a online calculator I found to be
$y(x) = \cfrac{1}{C \csc(x) - \frac 12x\csc(x)}+\cos(x),\:$ where $C$ is a constant
I struggle to get to this solution however.
Now I know this is a Ricatti DE as a particular solution is given so this is the work I've done thus far:
Get $y'$ by itself
so $y' = \cfrac{y^2-(\sin^2(x)+1)}{2\sin(x)}$
Now using the substitution $y = y_1 + \frac 1v = \cos(x) + \frac 1v$
$y' = -\sin(x) - \cfrac {1}{v^2}v' $
Setting the $y's$ equal to one another we get
$\cfrac {y^2-(\sin^2(x)+1)}{2\sin(x)} = -\sin(x) - \cfrac{1}{v^2}v'$
Making the substitution for $y$ we get
$\cfrac{(\cos(x) + \frac 1v)^2 - (\sin^2x+1)}{2\sin(x)} = -\sin(x) - \cfrac{1}{v^2}v'$
Here I have no idea where to go from as getting v' by itself results in a absolute nightmare.
Any tips would be greatly appreciated
Answer: It might help to take the intermediate steps first, that is, first use the offset towards the given solution directly. Set $y=y_1+u$, then the DE reads as, $y_1$ being a solution,
$\newcommand{\b}[1]{\color{blue}{#1}}$
$$
0=2\sin(x)(\b{y_1'}+u')+\b{\sin^2(x)+1}-(\b{y_1^2}+2y_1u+u^2)
\\
=2\sin(x)u'(x)-2y_1(x)u(x)-u(x)^2
$$
This now is a Bernoulli equation where indeed setting $u=\frac1v$ leads to a linear equation
$$
0=-2\sin(x)v'(x)-2\cos(x)v(x)-1
\\
0=2(\sin(x)v(x))'+1
$$
etc.
Comment: I don't understand what happened after the first line, could you explain, where is the $\sin^2(x)$ gone ?
Comment: I've marked the terms in blue that cancel due to $y_1$ being a solution. One could also just insert $y_1=\cos(x)$ to the same effect.
Comment: Yes since the cosecant function is just $1/\sin x$ @TotomaLover2312
Comment: Oh cool. Thanks! Just a quick question. Why does the substitution $y =y_1 + u$ work? My textbook says that we should use the substitution $y = y_1 + \frac 1v$ and I see that you eventually use $\frac 1v$ in the Bernoulli part, but I'm not sure why we should use $y = y_1 +u$ and why this works. where does this come from? And why does this work?
Comment: If you have two solutions of $y'=ay^2+by+c$, then in the difference of their equations you get $y_2'-y_1'=(y_2-y_1)(a(y_2+y_1)+b)$ which strongly suggests to find the equation for the difference $u=y_2-y_1$, eliminating $y_2$. It just works in this special case. Luckily enough this special case also covers some DE from "real" situations.
Comment: Oh thanks. I figured that this was just a special case. I just need to look for that pattern then. Thanks for your help!