How can I convert ticks to clock cycles?

Question: I am profiling Direct3D9 API calls. I have read a lot of documentation here that describes the process. I have a question though about calculating the elapsed clock cycles. Here is my current method:
<code>// measurement vars
LARGE_INTEGER start, stop, freq;

//
// flush command buffer here
//

//
// issue begin query here
//

// start timer
QueryPerformanceCounter(&start);

//
//draw
//

//
// issue end query here and wait on results
//

// stop timer
QueryPerformanceCounter(&stop);

// calc elapsed ticks
stop.QuadPart -= start.QuadPart;

// get frequency
QueryPerformanceFrequency(&freq);

// ticks for easier handling
ULONG ticks = stop.QuadPart;

// calc elapsed clock cycles
cycles = (2.8E9 * ticks) / (double)freq.QuadPart;
</code>
My question concerns the value 2.8E9 which is supposed to represent the speed of the processor. Is this the correct way of calculating clock cycles? I am profiling single API calls and my results differ from those found on the above link. If I set the processor speed to 1E9 then the numbers are within range...I just wanted to check my method...
Answer: Quoting your given source, the formula you'd use is:

cycles = CPU speed * number of ticks / QPF

In fact you're doing exactly this in the last line of your example code, where the "magic number" 2.8E9 is the speed of your CPU in Hz. So if this is your question, the answer is Yes, you're using the right formula.
In case you want to replace your magic number by the actual CPU speed, be prepared for a good amount of work. For more information on this, see the answer
Finding out the CPU clock frequency (per core, per processor)

However in order to get reliable profiling results, the best method would be using an external profiling tool, because when you change your code to measure execution times, it may actually have an effect on the things you want to measure (e.g. regarding optimizations).
Check the wiki for some reasonable profiling tools:
http://en.wikipedia.org/wiki/List_of_performance_analysis_tools#C_and_C.2B.2B
Apart from your interest in CPU cicles, the better "intrusive" approach would be using the platform independent mechanism from the C++11 Standard library for measuring elapsed times:
http://en.cppreference.com/w/cpp/chrono/high_resolution_clock/now
Comment: I'm interested in understanding how clock cycles are calculated
Comment: Clock cycles cannot be calculated, they're counted as the term _QueryPerformanceCounter_ states. There is no simple way to evaluate the amount of work the individual hardware components do for your processing. Modern computers/OSs are build to hide exactly this. Also the linked article says that it just uses this method because "it is available in Windows and it is easy to use" to "profile **execution times**". My answer simply proposes better ways to achieve this. Sorry for possibly misinterpreting your question, but I don't see any additional info to give here.
Comment: I'm interested in understanding the formula used to calculate the number of cycles that have elapsed when given 2 timestamps...The formula in the question above says to multiply ticks by processor speed in hz and divide by the high res timer's frequency. Is that correct?


Am I counting the beat on my 4/4 meter correctly or not?

Question: I got a rhythm pattern in 4/4 time signature where I'm little confuse with the rest notes while counting. I have made my count as below given picture where you can see count are made in red text.

I played and it sounds favorable and seems like each beat note are getting there count which they use to hold. Any way please make me confirm by telling how it's fine if I didn't made mistake and if I made mistake tell me. I would love to hear the reason no matter correct or wrong. I just need solid reason of this beat count which I am little unsure of it.
Answer: I'm guessing it's being strummed on guitar. Yes, the rhythm, is written properly - not sure why there's a little dot after the a of beat 3, 1st bar.
On guitar, it's easier to play ghost strums where there are no chords sounding. It keeps the rhythmic pattern of the strumming hand/arm going. Far better than just stopping, and starting again at the next strum.
To 'play' the rests, just release the pressure of the fretting fingers, in the same way as you do with the chords marked with 'x'.
There's nothing wrong with counting the rests in the same '2e&a' way. Just because it's a rest doesn't mean it's different from a note - both have counting values!
Comment: Yes, of course. But the point in counting (out loud if you want) is to keep the rhythm going, so count the same bits for every beat, it's just easier keeping time and keeping count.
Comment: It's not written by me. Jody fisher whom I would love to give credit as he is the author who wrote this all. From here [Rhythm_Guitar](http://noty-bratstvo.org/sites/default/files/gitara-Rhythm_Guitar.pdf) I counted it with my own knowledge so, was little unsure but thanks for proving!
Comment: '2e&a' ? Won't that work as above '2 +a' ?


Confusion regarding various definitions in defining singular homology

Question: In defining singular homology,

A singular $n$-simplex is a continuous mapping $\sigma_n$ from the
  standard $n$-simplex $\Delta^n$ to a topological space $X$.  Notationally,
  one writes $\sigma_n:\Delta^n\to X$.  This mapping need not be
  injective, and there can be non-equivalent singular simplices with the
  same image in X.
The boundary of $\sigma_n(\Delta^n)$, denoted as
  $\partial_n\sigma_n(\Delta^n)$, is defined to be the formal sum of the
  singular $(n-1)$-simplices represented by the restriction of $\sigma$
  to the faces of the standard $n$-simplex, with an alternating sign to
  take orientation into account.  (A formal sum is an element of the
  free abelian group on the simplices.  The basis for the group is the
  infinite set of all possible images of standard simplices.  The group
  operation is "addition" and the sum of image ''$a$'' with image $b$ is
  usually simply designated $a+b$, but $a+a=2a$ and so on.  Every image $a$
  has a negative $−a$.)  Thus, if we designate the range of $\sigma_n$ by
  its vertices
$$[p_0,p_1,\cdots,p_n]=[\sigma_n(e_0),\sigma_n(e_1),\cdots,\sigma_n(e_n)]$$
corresponding to the vertices $e_k$ of the standard $n$-simplex
  $\Delta^n$ (which of course does not fully specify the standard
  simplex image produced by $\sigma_n$), then
$$\partial_n\sigma_n(\Delta^n)=\sum_{k=0}^n(-1)^k [p_0,\cdots,p_{k-1},p_{k+1},\cdots p_n]$$

So is a singular $n$-simplex a map, unlike a simplex, which is a geometric object?
About the last formula and about orientation: why do we have to alternate signs? I guess that is related to orientation, but I can't get why.
About the last two formulas: Is the expresion starting with [ and ending with ] referring to geometrical objects, like simplices?
Comment: Say we have a triangle with vertices $A,B,C$ going counterclockwise. You would expect the boundary to be $\overrightarrow{AB}+\overrightarrow{BC}+\overrightarrow{CA}=\overrightarrow{AB}+\overrightarrow{BC}-\overrightarrow{AC}$. If you don't alternate signs in the given formula, you will end up with $\overrightarrow{BC}+\overrightarrow{AC}+\overrightarrow{AB}$, which isn't right. Draw a picture!
Comment: I now somehow get that part. Thanks.
Comment: @wj32: Actually, the boundary is $\vec{AB}+\vec{BC}-\vec{AC}$, which is not exactly the same as $\vec{AB}+\vec{BC}+\vec{CA}$, since $\vec{CA}\neq-\vec{AC}$. But there is a close relation between a reverse simplex and the negation of the simplex, namely, $\vec{CA}-(-\vec{AC})$ is a boundary, so they are equal at the level of homology. Of course, the picture of the boundary going counterclockwise is still useful,  as it helps you remember the corrects signs of the edges.
Answer: Yes, singular $n$-simplices are maps. We are effectively trying to probe our spaces with maps from the $n$-simplex. Note that these are topologically the same as solid spheres, and their boundary is a sphere. Homology is trying to capture the idea of holes in the space, and so this is a natural thing to consider. We want to see if we can throw a sphere into the space (which has a hole) such that we can't fill the interior of the sphere. It's also important to distinguish between the map (how we've thrown it) and its image — the image could be the same, but how we've thrown it could be different.
Given some singular $n$-simplex $\sigma$, we can consider its restriction to each of the $(n-1)$-simplices which make up its boundary. This is what is being referred to in the formula. We are taking the sum of these restrictions (with a sign), and hence getting a formal sum of $(n-1)$-simplices, which is what we want to construct a chain complex.
Finally, the sign is very important for us to get the cancellation that we want. You see this algebraically when you verify that $\partial \circ \partial$ is zero, and as wj32 indicates, you see this geometrically when you consider the low-dimensional examples.


Mudar cor da Celula

Question: Preciso alterar a cor da celula:
estou fazendo da seguinte maneira
<code> dataGridView.Rows[rowIndex].Cells["nomeDaColuna"].Style.BackColor = Color.Yellow;
</code>
porem eu não posso ficar passado o rowIndex eu teria que passar o "nome da linha"
Comment: Linhas não têm nomes. Por que você precisa que seja dessa forma? Tenho quase certeza que você não precisa de uma coisa que não existe.
Comment: Acredito que a melhor forma de vc fazer isso seria verificar o valor de um campo da sua linha e de acordo com o valor do campo setar sua cor.
Answer:
Você poderia explicar o que você quer fazer e qual o resultado que quer alcançar?
O que você quer dizer com "nome da linha" e por que tem que ser o "nome da linha"?

Assim, não existem nomes para as linhas dos grids em DataGridView até onde eu sei, mas você pode criar um dicionário para isso, o que vai dar um tanto de trabalho, por isso, acho melhor pensar o que você quer conseguir no fim antes e planejar um pouco.
<code>dataGridView.Rows[0].HeaderCell.Value = "NomeDaLinha1";
dataGridView.Rows["NomeDaLinha1"].DefaultCellStyle.BackColor = Color.Yellow;
</code>
Seria algo assim, mas você teria que especificar os nomes de cada linha.

Atenção: o código acima não foi testado.
Comment: É uma limitação do site que as vezes é um pouco incomoda mesmo. De qualquer forma, sinalizei seu post como comentário, sugiro que faça o mesmo, assim um moderador irá mover para os comentários.
Comment: @DiegoFelipe Infelizmente as respostas não são movidas para comentários, mesmo que esteja escrito ali na hora de sinalizar.
Comment: @jbueno por mim então, deixaria como resposta, já que é uma tentativa de responder a pergunta, apesar desta faltar as informações citadas.
Comment: Como é que eu faço pra sinalizar como comentário?
Comment: Eu votei pra remover, mas acho que se manter apenas a parte que é tentativa de "resposta" ela SERÁ totalmente valida.

Mudar cor da Celula


Use f1 score in GridSearchCV

Question: I would like to use the F1-score metric for crossvalidation using sklearn.model_selection.GridSearchCV. My problem is a multiclass classification problem. I would like to use the option average='micro' in the F1-score.
See also:
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score
I already checked the following post:
https://stackoverflow.com/questions/34221712/grid-search-with-f1-as-scoring-function-several-pages-of-error-message
If I try exactly what is standing in this post, but I always get this error:
TypeError: f1_score() missing 2 required positional arguments: 'y_true' and 'y_pred'

My question is basically only about syntax: How can I use the f1_score with average='micro' in GridSearchCV?
I would be very grateful for any answer.
EDIT: Here is an executable example:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.metrics import f1_score, make_scorer
from sklearn.preprocessing import RobustScaler
from sklearn.svm import SVC

data = load_breast_cancer()
X = data['data']
y = data['target']

#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

scaler = RobustScaler()
estimator = SVC()

pipeline_steps = [('scaler', scaler), ('estimator', estimator)]
pipeline_steps = Pipeline(steps=pipeline_steps)

grid = [{'estimator__C': [0.1, 0.5, 1.5, 2, 2.5, 3]}]

gridsearch = GridSearchCV(estimator=pipeline_steps,
                       param_grid=grid,
                       n_jobs=-1,
                       cv=5,
                       scoring=make_scorer(f1_score(average='micro')))

# now perform full fit on whole pipeline
gridsearch.fit(X, y)
print("Best parameters from gridsearch: {}".format(gridsearch.best_params_))
print("CV score=%0.3f" % gridsearch.best_score_)
cv_results = gridsearch.cv_results_
#print(cv_results)

Answer: Ok, I found it out:
If you use scoring='f1_micro' according to https://scikit-learn.org/stable/modules/model_evaluation.html, you get exactly what I want.
Answer: You can follow the example that is provided here, simply pass average='micro' to make_scorer. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html
Comment: Thx for your help. When I do this, I get the following error:

    scoring=make_scorer(f1_score), average='micro')
    TypeError: __init__() got an unexpected keyword argument 'average'

--> I added a full code example at my post
Comment: this is the correct way make_scorer(f1_score, average='micro'), also you need to check just in case your sklearn is latest stable version
Answer: gridsearch = GridSearchCV(estimator=pipeline_steps,
param_grid=grid,
n_jobs=-1,
cv=5,
scoring='f1_micro')
You can check following link and use all scoring in classification columns.
link : https://scikit-learn.org/stable/modules/model_evaluation.html

Use f1 score in GridSearchCV


Urban Airship triggers delegate functions on some devices but not on others?

Question: I'm testing with two iPhones. Both have the same version of iOS, 11.2.2, the latest one. They're both running the exact same version of the app. They have both given the same permissions for both notifications and background app refresh. Everything in the certificate is provisioned correctly.
This is an example of what I'm sending:

{
  "audience": {
    "named_user": "4"
  },
  "notification": {
    "ios" : {
      "content-available": true,
      "priority": 5
    }
  },
  "device_types": ["ios"]
}

With one iPhone both the receivedForegroundNotification delegate function and receivedBackgroundNotification delegate function is triggered appropriately depending on whether or not the app is in the foreground or background.
However, with the other device, neither of the Urban Airship delegate functions are triggered. The only thing that does work is that when I send a simple "Hello" alert it comes through just fine with the app in the background, though it never triggers any of the delegates, so I can't use it to sync data in the background.
As far as Urban Airship is telling me from the dashboard, both of the named users' devices (they're different named users) have given all green consent.
I don't know what else could be wrong. I can post some of my code if you guys want but given that it works fine on one device and not on another, I can't imagine that's the issue. Any help would really be much appreciated. I'm starting to give up on Urban Airship as a push provider but it would require a fair amount of work to transition to another one and I'm not happy with most of their privacy policies.
Answer: Urban Airship suggested I try to use their sample app to replicate the behavior, and I was not able to replicate it. So it was a problem with my code. It seems like the only thing I had changed to fix it is that I had some code that was asking for permission from the user to push notifications both through Urban Airship and directly through UNUserNotification. I got rid of the latter part, and since then the issue is gone. Still weird that this would only cause problems on some devices and not on others, but I'm glad it's fixed!


Your Ruby version is 2.0.0, but your Gemfile specified 1.9.3

Question: I have ruby 2.0 that is what comes up with ruby -v command
but I want to use ruby 1.9.3 because a gem I want to use for a project only suppoerts up to that version.
I have included:
ruby '1.9.3'

in my gemfile and get the following error when running bundle install:
Your Ruby version is 2.0.0, but your Gemfile specified 1.9.3

how can I use ruby 1.9.3? Where can I download it from I cannot find it? I still want to keep ruby 2.0 since I use it for a bunch of other projects how can I use both for different projects?
I am on a windows.
Comment: Have you tried googling "download ruby 1.9.3"?
Comment: yes downloaded it, just need to figure out how to use it now
Answer: First of all the download: http://rubyinstaller.org/downloads/archives
If you run it from cmd, you have to change the PATH variable to your target ruby version.
Comment: can you explain what you mean by change the PATH variable to target by version? If you could show example code that would be great. On the command line typing: "PATH=ruby 1.9.3" would do the trick or what do you mean?
Comment: Maybe you hit google for some questions. -> http://en.wikipedia.org/wiki/PATH_%28variable%29      You must point it to the the folder where the binarys are located. For ex: SET PATH=C:\ruby123\bin\


Chord naming conventions: When is a 6 a 13?

Question:
I have seen/ heard people say that you only write a 6 when there are no other upper extensions used (meaning no inclusion of 7 and above).

I have also heard people say that you only write a 6 when there is no 7th in the chord.

So, if we take E/G as an example, I would call this a G- flat 6 (add) flat 9. But I have seen this chord referred to as a 'G13 flat 9 sound'- ('sound' not 'chord'- as it is incomplete, with no 7th). This second labelling is more in keeping with the first view (1). 6/9 chord labelings seem to be more in accordance with the second view (2).
So, is there actually a definitive rule behind whether something is a 6 or a 13?
Answer: If there is a seventh then it's a 13th, otherwise a 6th.
A chord with a sixth and a ninth but no seventh is common.
Chords like E/G are probably better written as a slash chord rather than trying to force them into the standard naming scheme, particulary since there's not only no seventh, there's also no fifth.
Answer: A 6/9 chord is just what it is - including M6 and M9. As  C6/9 - C E G A D. A fine chord in its own right. The 6th is actually the 6th, and the 9th is actually the 9th.
Once the numbers go beyond 7, they are the actual notes involved. So, when that note is deemed the 13th, the 7, 9, 11 may well be included within the chord. It's not unusual that some notes are omitted, but the 7th must be there. At that stage, the 13th is 13th, rather than 6th.
Otherwise the chord will be a simple 6th.
Answer: Let's explain using G13 as example.
We start with the basic G major triad: G/B/D and the than we stack thirds on top of it. So G7 would be G/B/D/F, G9=G/B/D/F/A, G11=G/B/D/F/A/C, and finally G13=G/B/D/F/A/C/E
At this point the chord includes all notes in the C major scale, i.e. all the white keys on the keyboard. You can simply take a 2x4 and press down as many white keys as you can. If someone asks "what the heck are you playing?" you can answer "Why, dear sir or madam, that is a G13 chord" and you'd be theoretically correct.
In practice you will still get kicked out of the band, since it sounds terrible. It also poses a problem for guitar players: there are seven notes in the chord and you have only six string.
Obviously you don't play all the notes. Most chords have a key "tension" interval that creates the character of the chord. Make sure you capture this. You also want to include the third just to make sure you can distinguish between a major and a minor key.
For the G13 the tension interval is 13 vs 7, i.e. E vs F. You also want the E on top, hence you write it as a 13 and NOT as a 6. For grins you can try playing the F on top as well: You ears will NOT be pleased! The other chord notes are optional and can either add flavor or clutter things up depending on what else is happening.
So in this example your minimum set a good choice of notes for a G13 would be G B F E and that's probably what the person who scribbled G13 on the chart intended. If you have a competent bass instrument in the band, you can also drop the root and simplify further.
Comment: thanks for this great answer Hilmar. One thing I'd still ask: if you DID put that 6th interval BELOW the 7, would the chord then become a 6 ? Or would it still be written as 13, even though it is actually at a lower pitch than the 7? I'd imagine if it contains the 7, youd still call it 13?
Comment: I guess you could write it as a 6/7 or 6/15 but it would be fairly unusual. It's not very pretty


Is it possible to send Uri using AIDL?

Question: I have two apps, lets say AppClient and AppService. Those apps are communicating between each other using AIDL methods. Right now I would like to send Uri from AppClient to AppService in AIDL method parameter. I can send it without any problems but when I trying to open stream to read file
using
context.contentResolver.openInputStream(uriFile)

I'm getting SecurityException.
Permission Denial: opening provider androidx.core.content.FileProvider from ProcessRecord{94e65ad 6186:com.app.service/u0a231} (pid=6186, uid=10231) that is not exported from uid 10043
In AppClient before sending Uri via AIDL method I'm granting required permissions first.
val uri = FileProvider.getUriForFile(this,"com.app.client.fileprovider", fontFile)
grantUriPermission("com.app.service", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION and Intent.FLAG_GRANT_READ_URI_PERMISSION)

In documentation is see thet Uri is transported to other app using Intents but it I don't want to use Intents. It is possible to send Uri not using Intent e.g. in AIDL parameter ?
Comment: How exactly are you sending the uri? And what is AIDL?
Comment: Android Interface Definition Language, I'm passing Uri to AIDL method parameter so AppServie can receive this in Service via Binder Stub methods
Answer: grantUriPermission("com.app.service", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)

Is it possible to send Uri using AIDL?


Censored Regression model

Question: I am considering the following censored regression model. I have a question about my R code.

Then I obtain likelihood function as follow.

Then i obtain log-likelihood function.

##Data Generation#################################################
set.seed(123)
n <- 1000; u <- rnorm(n);x<- rnorm(n,0,sqrt(2))
y_star <- 1 + x + u
y <- ifelse(y_star > 0, y_star, 0)
data <- data.frame(x,y)

##Censored Regression##############################################
Censored_reg <- function(initial_value,y_in, x_in) {
  f_censored <- function(input, y_in, x_in) {
    sigma <- input[1]
    beta <- input[2:length(input)]
    xb <- cbind(1, x_in) %*% beta
    z <- (y_in - xb) / sigma
    y.indic <- ifelse(y_in > 0, 1, 0)

    log_lik <- sum(y.indic*(log(dnorm(z))-log(sigma)) + (1 - y.indic)*log(1 - pnorm(z)))
    return(-log_lik)
  }

  result <- optim(par = initial_value, fn = f_censored, y_in = y_in, x_in = x_in)
  return(result)
}
#log_lik <- -sum(y.indic*(log(dnorm(z))-log(sigma)) + (1 - y.indic)*log(1 - pnorm(z)))

# Example usage:
result <- Censored_reg(initial_value = c(2,2,2),y_in = data$y, x_in = data$x)
print(result)

I thought it works well, however, the result does not coinside with the results from censReg package.
library(quantreg)

rq <- rq(y ~ 1 + x, tau = 0.5, data = data)
screenreg(rq) #library(texreg) # similar to "stargazer"

I am very appriciate if you find my error.
Thank you in advance.
Chat GPT does not understand Censored Reg, so pls help me.
Comment: LaTeX is not built into SO.  Perhaps it'd be better if you could render those equations and pasting them as images into SO.
Comment: `pnorm(z)` does not correspond to the formula of the loglik. Should be `pnorm(xb / sigma)`.
Answer: After replacing pnorm(z) with pnorm(xb/sigma), I find:
> print(result)
$par
[1] 0.9889646 1.0033864 1.0710261

censReg gives:
> censReg(y ~ 1 + x, data = dat)

Call:
censReg(formula = y ~ 1 + x, data = dat)

Coefficients:
(Intercept)           x    logSigma
    1.00337     1.07109    -0.01101

The results are almost the same.
Comment: Dear Stéphane Laurent

Thank you for finding my mistake!!
I considered more than an hour.
sincerely appreciate your support : )

Censored Regression model


Range Initialization of a C Array

Question: Very simple question of where does this code work?
static void *gostruct[] =
{
    [0 ... 255] = &&l_bad,
    ['\t'] = &&l_loop, [' '] = &&l_loop, ['\r'] = &&l_loop, ['\n'] = &&l_loop,
    ['"'] = &&l_qup,
    [':'] = &&l_loop,[','] = &&l_loop,
    ['['] = &&l_up, [']'] = &&l_down, // tracking [] and {} individually would allow fuller validation but is really messy
    ['{'] = &&l_up, ['}'] = &&l_down,
    ['-'] = &&l_bare, [48 ... 57] = &&l_bare, // 0-9
    ['t'] = &&l_bare, ['f'] = &&l_bare, ['n'] = &&l_bare // true, false, null
};

Reading through it its clear to see that it initializes an array containing 256 entries to the value &&l_bad and then overrides certain indexes with specific values. But this code does not compile in VS2010 which is what I have access to so I am wondering where this is valid C code.
NOTE: This code snippet was taken from a JSON parser on github that, from my understanding, creates jump tables for the processing of JSON strings.
Comment: I believe this is using a gcc extension.
Answer: This construct is called Designated Initializers.
Using Range in Designated Initializers is a GNU gcc specific extension.

To initialize a range of elements to the same value, write [first ... last] = value
  . This is a GNU extension. For example,
int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

Compiling it with -pedantic shall tell you so.
Note that it is non-portable since it is a compiler specific extension.
Comment: Thank you, searching for this syntax is fairly difficult in most search engines it seems so the name of this is greatly appreciated.
Comment: Designated initializers are not a gcc extension (except that gcc permits them in C89 mode), but the use of `...` in designated initializers is.
Answer: This is using a number GNU C extension.
http://www.gnu.org/s/gnu-c-manual/gnu-c-manual.html
'as a GNU C extension, you can initialize a range of elements
to the same value, by specifying the first and last indices, in the
form [first] ... [last]'

'As a GNU C extension, you can also take the address of a label
with the label address operator &&. The result is a void* pointer
which can be used with goto.'

It looks like this is most likely being used as a jump table for a parser,
that entire section will need to be rewritten if you intend to port it to windows.
You'll probably find that you will implement a simple switch statement and replace
the lookup and goto jumps, something like perl will help you with the 'typing'
excersise :)
Answer: According to the reference

In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well. This extension is not implemented in GNU C++.

Both range and specific initializer are ISO C99 supported, and are not only GNU extension. You can try to enable ISO C99 (I don't know how) in Visual Studio 2010.
Reference: https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
Comment: This may help others in addition to the information above. Microsoft's support for C standards in their C++ environment is on an as-needed basis most of the time. If a standard/feature is not in heavy demand then it is generally. Since there is a view of goto being avoided at all times (instead of understanding every logic or func call is a goto) it's not likely to have this supported in Visual Studio. (I have not checked recently however)
Answer: Using ranges in designated initializers is an gcc extension, not supported in standard C99.
Also the code takes the address of labels, which I believe also is a gcc extension.
So, no this is not valid C code, just valid gcc c code.

Range Initialization of a C Array


What is $\lim_{x \rightarrow 0}\left[\psi\left(1+\frac{a}{2x}\right)-\psi\left(\frac12+\frac{a}{2x}\right)\right]$?

Question: I need to evaluate the following limit:
$$L=\lim_{x \rightarrow 0}\left[\psi\left(1+\frac{a}{2x}\right)-\psi\left(\frac12+\frac{a}{2x}\right)\right]$$
where $\psi(x)$ is the digamma function and $a$ is a positive real number.
I started by writing
$$L=\lim_{x \rightarrow +\infty}\left[\psi\left(1+\frac{ax}{2}\right)-\psi\left(\frac12+\frac{ax}{2}\right)\right]$$
and then, using the fact that $\psi(x)\sim\ln x$ for large $x$, I got $L=0$ as the result.
However, this seems wrong to me, and numerical trial suggests this is the case.
Is the result I got correct or wrong? Do you know other techniques to evaluate the limit? Thank you.
Comment: $\psi(z)\sim\ln z$ is too weak, but $\psi(z)=\ln z+O(1/z)$ is sufficient.
Comment: Maple says $$\psi \left( 1+{\frac {a}{2\,x}} \right) -\psi \left( {\frac{1}{2}}+{\frac {a}{2\,x}} \right) =\frac{x}{a}-{\frac {1}{2\,{a}^{2}}}{x}^{2}+O \left({x}^{3} \right) $$ as $x \to 0^+$.  So it agrees with the answer $0$.
Comment: Note: $A \sim \ln(x)$ and $B \sim \ln(x)$ implies only $A-B = o(\ln(x))$ and does not (by itself) imply $A-B \to 0$.
Comment: For $a=1$, the [graph](https://www.wolframalpha.com/input?i=plot+digamma%281%2Bx%2F2%29-digamma%281%2F2%2Bx%2F2%29+from+0+to+1000) supports $L=0$. What values for $a,x$ did you use for the numerical trial? You should get [this result](https://www.wolframalpha.com/input?i=digamma%281%2Bx%2F2%29-digamma%281%2F2%2Bx%2F2%29%2Cx%3D10000.0) for the numerical trial.
Comment: @TymaGaidash I used $a=1$ and $x=10000$
Comment: @GEdgar thank you for the confirm, that was what I was unsure about
Answer: Let's denote
$$I\left(\frac xa\right)=\psi\left(1+\frac{a}{2x}\right)-\psi\left(\frac12+\frac{a}{2x}\right)$$ It is convenient to use the Gauss' integral representation of  $\psi$-function
$$\psi(z)=\int_0^\infty\left(\frac{e^{-t}}t-\frac{e^{-zt}}{1-e^{-t}}\right)dt$$
Then
$$I\left(\frac xa\right)=\int_0^\infty\frac{e^{-\frac{at}{2x}}\big(e^\frac t2-1\big)}{e^t-1}dt=2\int_0^\infty\frac{e^{-\frac{at}x}}{e^t+1}dt$$
The integrand is dominated by the integrable function $f(t)=\frac2{e^t+1}$. Therefore, based on the dominated convergence theorem we are allowed to take the limit under the integral sign and find that
$$\lim_{x\to0}I\left(\frac xa\right)=2\int_0^\infty\left(\lim_{x\to0}e^{-\frac{at}x}\right)\frac{dt}{e^t+1}=0$$
Using the presentation for  Euler polynomials $\frac{2e^{xt}}{e^t+1}=\sum_{n=0}^\infty E_n(x)\frac{t^n}{n!}$
$$\boxed{\,\,I\left(\frac xa\right)\sim\sum_{n=0}^\infty\frac{E_n(0)}{n!}\int_0^\infty e^{-\frac{at}x}t^n=\sum_{n=0}^\infty\left(\frac xa\right)^{n+1}E_n(0)\,\,}$$
Giving that
$$E_0(0)=1;\,E_1(0)=-\frac12;\,E_2(0)=0;\,E_3(0)=\frac14;\,E_4(0)=0;\,...$$
$$I\left(\frac xa\right)=\frac xa-\frac12\left(\frac xa\right)^2+\frac14\left(\frac xa\right)^4+O\left(\Big(\frac xa\Big)^6\right)$$


Multilingual views hide if no translation

Question: My Drupal website has 2 languages and I created blog view that lists articles (content type). Default language is English.
Problem is that some articles are only in German and then on my English view I get German articles.
I tried adding Content: Translation language Filter that I set to Interface text language selected for page but then on German page I only get articles that were created on German and the ones that were created in English but have German translation are missing.
Query :
SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN
('article')) AND (node__field_content_type.field_content_type_value = '1')
))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

Query with Translation language filter:
SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
LEFT JOIN {node__field_tags} node__field_tags ON node_field_data.nid =
node__field_tags.entity_id AND node__field_tags.field_tags_target_id = '4'
WHERE (( (node__field_tags.field_tags_target_id IS NULL) )AND((
(node_field_data.status = '1') AND (node_field_data.type IN  ('article'))
AND (node__field_content_type.field_content_type_value = '1') AND
(node_field_data.langcode IN  ('en')) )))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

From queries, I see that LEFT JOIN is adding node__field_content_type.langcode = node_field_data.langcode and I think that is making problems when I add the language filter, any suggestion?
Comment: The LEFT JOIN is OK, it joins the entries with the same language in both tables. But your query is filtering english: `(node_field_data.langcode IN  ('en', 'en')) )))`, so by looking at the filter this means the interface language is detected as english.
Comment: @4k4 still does not explain why I do not get translations only `original language` when I add filter
Comment: The node_field_data table contains all languages, it doesn't matter whether this is the original or translated version. There was no more information for me to debug this any further. My idea was to get you away from debugging the LEFT JOIN, because this joins only one bundle field to the main node data table, and pointing you at the filter in the query and the language detection. What have you configured there? (admin/config/regional/language/detection)
Comment: Maybe I'm on the wrong track, did think that the error is the English filter on a German page. The join could be the problem, if the field `field_content_type` in your node is not translatable, see this issue https://www.drupal.org/node/2451657
Comment: @4k4 `node__field_content_type.langcode` has only original language while `node_field_data.langcode` has all languages, that is why I thought that that will make a problem. Detection http://prntscr.com/f9k62p, will check that issue. Thank you
Comment: @4k4 you were right, that `field_content_type` is not translatable and when I removed it everything was working, thank you again.
Answer: The problem was that I was doing condition in views with field that wasn't translatable and views are adding join on langcode, thanks to user 4k4 that linked to this issue that can be found here.
I fixed this by removing untranslated field from view and hooking into hook_views_query_alter and adding relationship myself :
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

function hook_views_query_alter(ViewExecutable $view,
QueryPluginBase $query)
{
    if ($view->id() == 'blog') {
        $definition = [
            'table' => 'node__field_content_type',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
        ];
        $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
        $query->addRelationship('node__field_content_type', $join, 'node__field_content_type');
        $query->addWhere('1', 'node__field_content_type.field_content_type_value', 1, '=');
    }
}

Also this hook has to be in MODULE.views_execution.inc file
Comment: Thank you for sharing the solution with us. I am not sure where you add this part of code, a file `MY_MODULE.views_execution.inc` has no impact in my environment.
For me it worked to add it to my `MY_MODULE.module`-file as the `function MY_MODULE_views_query_alter(ViewExe...`.
Comment: @btemperli maybe something changed since I needed this, I didn't work with drupal for over a year now


Is simplification from 'or' ($\lor$) valid?

Question: The question in my text is :
Identify the error or errors in this argument that supposedly shows that if $\forall x (P (x ) \lor Q(x ))$ is true then $\forall x P(x) \lor \forall x Q(x)$ is true.
\begin{array}{l l l}
(1) & \forall x(P (x) \lor Q(x)) & \text{Premise} \\
(2) & P (c) \lor Q(c) & \text{Universal instantiation from }(1) \\
(3) & P (c) & \text{Simplification from }(2) \\
(4) & \forall x P (x ) & \text{Universal generalization from }(3) \\
(5) & Q(c) & \text{Simplification from }(2) \\
(6) & \forall xQ(x) & \text{Universal generalization from }(5) \\
(7) & \forall x(P (x) \lor \forall x Q(x)) & \text{Conjunction from } (4) \text{ and } (6)
\end{array}
According to me the errors occur at step 3, 5 and step 7. Step 3 because the rule for simplification is
$$(p \land q) \rightarrow p$$
and in step 7, it isn't conjunction but addition? Because rule of addition is $$ p \rightarrow (p \lor q)$$
Also step 5 because we can't assume that the $c$ that makes $P$ true is the same $c$ that makes $Q$ true.
Am I right?
Comment: Step 3 is wrong: we cannot safely infer from the fact that: "either the cat is balck or the cat is red" that "the cat is black". As you correctly noted, *simplification* holds for *conjunction* ($\land$).
Comment: ah! thanks for the example. I can now see this is really simple,but I got confused by the question. @MauroALLEGRANZA
Comment: After step 3 you can use [disjunction eliminiation](https://en.wikipedia.org/wiki/Disjunction_elimination) to start a "proof by cases"... but then you cannot "generalize".
Comment: The mistake of step 5 is the same as the one from step 3.
Comment: You are right; step 7 is wrong: "conjunction" rules introduces a conjunction: $\land$.
Comment: There is no way to recover it; if we modify 3 to use proof by cases, we are stuck with generalization. But if we use the (incorrect) generalization at step 4, then we need an extra step (4') with $\lor$-introduction to derive $\forall x \ P(x) \lor \forall x \ Q(x)$. The same for the other "branch" of the $\lor$-elimination.
Answer: Depending on how the rules in your formal proof system are defined, steps 4 and 6 could be incorrect as well: when the $c$ is used for the universal instantiation, some formal proof systems consider that to be a specific individual and, as such, you can't apply universal generalization on that. Instead, these systems demand that either $c$ be 'marked' as an arbitrary individual from the domain, or that a temporary subproof structure be used, or that variables be used.
So, how is universal generalization defined? What text are you using?
Comment: @momo Hmm, that book, while a great book on Discrete Structures, pays little attention to *formal* proofs. In it, the Universal Generalization rule is stated as being able to infer $\forall x P(x)$ if you know that $P(c)$, and $c$ is an arbitrary individual. Which all makes sense ... but it is not clear how exactly the 'arbitrariness' of $c$ is formally fleshed out in a formal proof. However, looking at the answer in the back of the book of problem 27, it seems like what is happening in lines 4 and 6 of your 'proof' is in fact formally correct.
Comment: As Bram28 said, I don't recommend you study logic by that book. It leads you to wrong direction, and useless knowledge in modern logic.... That book didn't pay attention on the semantics and syntax nature of logic, and messed up the object language and meta-language. You will totally be frustrated if you want to study logic rigoursly in the future. I was a victim by beginning studying logic by that book..., but safe from study Robert Causey's *Logic, Sets and Recursion*. :)
Comment: I am using the book by Kenneth Rosen.
Answer: You're correct, but your objection to step 7 is more about nomenclature (and cosmetics) which may differ somewhat. The step is otherwise correct since if we have $p$ then we can conclude $p\lor q$ (however we actually don't need to prove $q$ too for this step).
Also the instantiation means that you pick a specific $c$ from which you can't generalize later. However there are formalizations where one can do something similar (in which case $c$ isn't considered specific, but general).
I think the last comment is the most important and somewhat captures why the conclusion is not correct. It's about that in the first statement the variable $x$ work in unison in both $P$ and $Q$ while in the last they work independly (that is the last is the same as $\forall x\forall y(P(x)\lor Q(y))$).


How can I remove items from the allowed values list of a select field that has data for the values?

Question: I've created a content type that has a list / select option field, and I've entered the key|value pairs as necessary for the select list to function.
Data has been entred, and it's been decided that certain terms no longer apply and that they should be deleted.
However, when trying to remove said terms, I get the following error:
Allowed values list: some values are being removed while currently in use.
Obviously, in the life of a project, values are going to change. What's a practical way to remove items once nodes are associated with the listed terms?
This is about the closest thing that I could find:
https://drupal.org/node/1653012
It references a d6 plugin and some patch trickery I'd prefer not to have to resort to.  If I did have to ultimately resort to using the patch to remove the validation check on that field, is there any harm in leaving those items orphaned on the nodes they were associated with?
Update, I have come accross this issue again with a government client who, for the last 7 years of having a Drupal site has had 50 states and territories in a select list. Now, policy has changed and the territories no longer needed to be included. Being able to remove items from the select lists is important, and thus I'm offering a bounty.
I'm looking for a safe solution to be able to remove items from a select list. What I don't know is if that solution should update any of the nodes as I'm not sure how the field values are stored in relation to a node's total content.
I'm happy with a pure SQL solution to run in MySQL; or, I'm looking for a module.
Comment: _Obviously, in the life of a project, values are going to change._ I would dispute that - values for a static select list should be defined at the start of the project. If you need it to be flexible, you should use a term reference instead of a static list. Static lists are for things like sex (male/female) which, unless we have a serious shift in things, isn't likely to change anytime soon. And if it does, it will be _added_ to, not _removed_. Whenever I've made this 'mistake' I've always found the best way to back out is to run manual queries on the data
Comment: Do you want to make this list dynamic? being dynamic in creation and deletion.
Comment: Yeah I guess that's just down to opinion then - car manufacturer would always be a node type or vocabulary for any site I would build. Since manufacturer is a category of car (or category of car that someone repairs), it makes most sense as a taxonomy to me rather than a content type. But I know that doesn't help...I would be wary of leaving orphan data in the DB, it's very hard to say what effect that could have without knowing exactly what's installed on your site and how it's configured
Comment: What's wrong with views_bulk_operations?
Comment: heh, none of these answers have any upvotes yet :/
Comment: @clive can't say I agree here. It's a mechanic that after 10 years of servicing Audi, no longer services Audi, and the make model fields on the service form need to be updated / removed from the list. My point is, businesses go through changes, and, well, I am where I am now. Thought about redoing it with taxonomy, but that architecture doesn't feel right - I'm not categorizing anything. I'd prefer not to delete them as the term needs to be a part of the old data for historical records (so I'm hoping ophaning them is ok). If I have to, ok, they can just keep prior records on a backup server.
Answer: I did something like this recently with the following approach.

Add the new allowed values.
Add a setting to configure "active" values.
Filter out the "inactive" values from display on the form.

e.g:
/**
 * Admin settings form
 */
function MODULE_admin_settings(){

  $form = array();

  // Select active preferences for display
  $field = field_info_field('field_preferences');
  $preferences = list_allowed_values($field);
  $form['field_preferences_active'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Active preferences'),
    '#options' => $preferences,
    '#description' => t('Select the preferences available for user selection.'),
    '#default_value' => variable_get('field_preferences_active', array()),
  );

  return system_settings_form($form);

}

/**
 * Implements hook_field_attach_form
 */
function MODULE_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {

  // Filter out inactive preferences
  if(isset($form['field_preferences'])){
    $preferences = variable_get('field_preferences_active', array());
    foreach($preferences as $key => $preference){
      // If this preference isn't checked, but is set in the field values, unset it.
      if(empty($preference) && isset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key])){
        unset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key]);
      }
    }
  }

}

This way the legacy data is preserved for reference, the form validates, and the data integrity is intact.
Comment: This option is essentially non-desctructive (ie, hide stuff rather than delete), and is probably the best starting point until you can determine the best course of action for how to deal with any entities that have the outdated options.
Answer: As I know, all fields data is stored in 2 tables: field_data_field_FIELDNAME and field_revision_field_FIELDNAME. And I found confirmation of my thought here: https://stackoverflow.com/a/7773117/1300562
So to remove unnecessary field values you need to delete these values from above-mentioned tables and then remove them from the list of allowed values.
Step 1.
$values_to_remove = array('value1', 'value2'); // an array of unnecessary values
$fieldname = 'FIELDNAME'; // name of your field. For example,
                          // 'territory' for field with machine name 'field_territory'
$entity_type = 'node'; // it's 'node' in your case, but it can be 'taxonomy_term' or something else

db_delete('field_data_field_' . $fieldname)
  ->condition('entity_type', $entity_type)
  ->condition('field_' . $fieldname . '_value', $values_to_remove)
  ->execute();

db_delete('field_revision_field_' . $fieldname)
  ->condition('entity_type', $entity_type)
  ->condition('field_' . $fieldname . '_value', $values_to_remove)
  ->execute();

Step 2.
Remove unnecessary pairs of key|value on the field settings page and submit the form to save changes.
Cache should be cleared automatically after that, but if you still can see removed field values on node pages, clear the cache manually.
P. S. Recently I faced with similar problem, and now I prefer to use fields of type "Term reference" or (even better) "Entity reference" instead of list of text values. When using reference field, you can create separate vocabulary for each field and simply create/edit/delete terms at any time.
Comment: If the field is repeating, then those queries will not adjust the deltas for the remaining data.
Answer: I think you actually can done this by using Views Bulk Operations module.

add a new option on that field you would like to replace. for example: na|NA
create a View to list node contain with that field
add "Bulk operations: Content" fields on that View
check "Modify entity values" and "show avaiable tokens"(select All on display values)
Add the field you want to change on Filter Criteria and "expose" that filters
set url Path on that View
Go to that view page and change
Now, use the expose and operations features to change the field option
Done
Answer: First of all check if you have any allowed values specified in the field? If you do, then an other option will not be validated. So try to remove the values from Field Settings tab first.
Alternatively you have 2 options:

1.
Remove all values that you've put in the allowed values list that are in-use by user accounts.
For example, you can run a SQL query to find these:
SELECT * FROM field_data_field_MYFIELDNAME WHERE entity_type = 'user' and value = 'MY VALUE'

or create a user view that shows you what user accounts have the value you want to remove from the allowed values list.

2.
If you don't want to remove values from the fields, this can be achieved by hack.
Warning, this is not suggested solution for production and you should know what you're doing!

Find and edit modules/field/field.module
Find field_has_data() function and add return TRUE; in the first line of function.
function field_has_data($field) {
  return FALSE; // HACK !!!
  $query = new EntityFieldQuery();

Re-save the field with values you want.
Remove the hack as soon as you do that.
Answer: I used kenorb's 2nd suggestion and it worked to update the list of values in a Drupal 7.52, Profile2 7.x-1.3 field. So if you were getting the drupal warning: "Allowed values list: some values are being removed while currently in use." the following allowed me to remove values from the (profile2) field, without removing or replacing them in the database.
In Drupal core's root directory, there is a folder called modules, and the file to edit is located at: modules/field/field.module. THIS IS A CORE FILE, you must absolutely revert your changes when done updating values. I took the site offline, temporarily replaced the following code block in (drupal root)/modules/field/field.module
function field_has_data($field) {
  $query = new EntityFieldQuery();
  $query = $query->fieldCondition($field)
    ->range(0, 1)
    ->count()
    // Neutralize the 'entity_field_access' query tag added by
    // field_sql_storage_field_storage_query(). The result cannot depend on the
    // access grants of the current user.
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

  return (bool) $query
    ->execute() || (bool) $query
    ->age(FIELD_LOAD_REVISION)
    ->execute();
}

WITH EXACTLY
function field_has_data($field) {
    return FALSE; // hack
    $query = new EntityFieldQuery();
}

And drupal stopped complaining and I was able to alter the list. (In my case, it's faculty in the list of values that have left the university, but are still associated with a students record, as their advisor, mentor, etc.)
Comment: Thank you Michaell. it's working fine (d7.67). This is the easy way imho
Answer: Here comes an improvement for H-L answer which I think is the best:
To sum up, you need to assign new values to content which has "old" values assigned for your select field.
Apart from Views Bulk Operations, you will need to install and enable Administration Views module. With this module, you already have an out-of-the-box view with bulk operations enabled (just see admin/content once enabled). Then:
1) Go to admin/structure/views an edit "Administration: Node" view
2) Add a new page display for the view using button "Add -> Page" on top
3) Asssign a path to the new display: Example admin/content/custom
4) Add a new filter for your select field: Select operator "is one of" and then select all options you want to delete
5) Save the view
6) Go to admin/content/custom Now you see all content that you need to bulk edit (change value for your select field)
7) Select all rows by clicking first checkbox in the left of the table (if there is more than one page, also select a button which will say "Select all X rows in this view")
8) Select operation "change value" and press "Execute"
9) For your select field, select a new value to overwrite the ones you want to delete
10) Select the checkbox for that select field
11) Click Next and you are done
Answer: It sounds like your Drupal problem is based on a deeper data problem: What happens to the entities which are currently using the depreciated list values?  This question is at the root of the error message that Drupal is sending you.
Lets take a closer look at your state/territory example.  Your client has been using a system that treats states and territories in the same way for years and has build up a huge group of nodes which contain both states and territories.  Then one day, the powers that be decide that territories need to be handled differently and that the drop-down for assigning region should no longer contain territories.  Great.  Simply create a view that uses standard filters to render a list of all the territory nodes and use Views Bulk Operations to change all of their region values to... what... some 51th state called other maybe?  The fate of the territories is a very serious question.  Your solution must include a method for preserving or relocating the territory status.  You may need to create a new list field called 'Territory' which can be used to identify areas that are territories, or create an entirely new data type for them.
You will need to use Rules with View Bulk Operations in order to perform these changes.  If you don't know much about rules, please take some time to learn about how they work.  Rules gives you the ability to manipulate information based on triggers, conditions and actions.  After learning about rules, you may find that the answers you are looking will intuitively present themselves.  Basically, You will need to create a rule, which is triggered by a Bulk Operation, that will target all of the territories and remove, reassign, rename or otherwise separate them from the main body of information.  The Rule must be able to store the territory state in some way while at the same time, set the state dropdown to 'other' or 'N/A' status.  This may be all that is needed.  Otherwise...
After the reassignment is done, it should be a simple operation to alter the original list field and remove the territory names.  However, if the system still does not allow you to alter the list, you may need to create a new list field, then use Views Bulk Operation and Rules to review all of the current state values and reassign them to the new list.  Rules can work with Views Bulk Operations to target all of the relevant nodes and act upon them based on the field values.  Setting a the value of a new list field based on the value of an existing list field for a group of nodes is easy when you use Rules.
Also remember, if Drupal gives you trouble with an operation, always flush the cache before considering a difficult alternative.
Answer: I would assume your client wants legacy content to hold to it's original value, meaning changing the select list will effectively destroy any previous data.
If that's not a concern, then any of the other answers would probably work.  If it is however, you can't really change the select list without loosing that data history.
I might go a much simpler route, to allow for historical data, while making the site a little more future-proof - I would suggest using field permissions:
*set up a new field for that select list using a taxonomy instead of static data
*set the field permission for the existing select list as VIEW, but not EDIT by anyone except admin
With this, the old field should remain viewable and searchable (add a new title reflecting it as legacy only) but not editable. This of course depends heavily
on custom searches, views, etc that may need to be adjusted.
I suggest this (as messy as it may sound) because removing that data, removes history, and that may end up being devastating in the long run. You could even use
css to hide the old field in the edit node, and a hook to hide it for new content (where it doesn't have a value set).  In this way, it would only show for that legacy content.
Of course, you could then take it a step further with a custom one-off module to copy the data from the old select list to the new taxonomy.
Answer: A simple drush script to the rescue! We update the field data and field revision tables and replace the old values with new ones before manually changing the field settings.
If we have something like this in our current field settings:
&date=today|today
&date=last2days|last2days

and want to replace it with the following:
date=today|today
date=last2days|last2days

We run the drush script first and then change the field settings in admin UI.
Note: This code is for a field with machine name field_foo_bar.
    $field_name = 'foo_bar';

    print "for {$field_name}...\n";

    replace_field("&date=today", "date=today", $field_name);

    replace_field("&date=last2days", "date=last2days", $field_name);

    function replace_field($old_value, $new_value, $field_name, $entity_type='node') {
      print "Replacing {$old_value} with {$new_value}...\n";
      $data_count = replace_options_data_field($field_name, $entity_type, $old_value, $new_value);
      $revision_count = replace_options_revision_field($field_name, $entity_type, $old_value, $new_value);
      print $data_count + $revision_count . " entries replaced.\n";
    }

    function replace_options_data_field($field_name, $entity_type, $old_value, $new_value) {
      $num_updated = db_update('field_data_field_' . $field_name)
        ->fields(array(
                   'field_' . $field_name . '_value' => $new_value,
                 ))
        ->condition('entity_type', $entity_type)
        ->condition('field_' . $field_name . '_value', $old_value)
        ->execute();
      return $num_updated;
    }

function replace_options_revision_field($field_name, $entity_type, $old_value, $new_value) {
  $num_updated = db_update('field_revision_field_' . $field_name)
    ->fields(array(
               'field_' . $field_name . '_value' => $new_value,
             ))
    ->condition('entity_type', $entity_type)
    ->condition('field_' . $field_name . '_value', $old_value)
    ->execute();
  return $num_updated;
}


Are you allowed to ask questions related to estimates?

Question: For example, how long does it take to install / configure Apache Solr as the search engine for a Magento CE build?
Perhaps a related question (or a part of that question) would be to break the task down into the different sub-tasks involved.
UPDATE:
I wanted to reply in comments but had too much to say, so here are some responses to some of the great feedback I've received thus far.
Precedent in other SE sites
It looks like cost estimates are not allowed on Stackoverflow, but are allowed on Programmers.  They talk mostly about the reasons for not asking about costs, but they don't mention things related to time estimates specifically.  Also, part of the reason I thought to ask this on this site is I get the sense this will be a more business-friendly site than others given the nature of the Magento community.  Not sure what that means exactly, but trying to feel that out.
Depends on experience
While it's true that any answers related to experience do depend highly upon an individual's experience level, that's not necessarily a problem.  It's actually very useful for me to know that it's possible for Solr to be deployed in one minute for a highly experienced and specialized individual.  It doesn't mean that I would use that estimate myself, but it's useful information none the less.
You might say that multiple people could submit completely different valid answers - one person says it would take a week and another says it would take a minute.  Well for starters, that information alone would probably tell you that the person who says it would take a week is significantly less experienced (and perhaps trustworthy on this particular topic) than the other - which could, again, be useful information.
But also, there are many questions that don't always have One Single Correct Answer to them, such as What is the Best Magento Server Setup?.
Estimates tend to lead to good questions
I find that the process of thinking through an estimate can lead to a lot of good questions, such as the ones that you posted related to Solr installation - sometimes even more so than if someone simply asks a more generic How-To question.
Shopping Questions
I can see the concern with someone just irresponsibly posting a question up for an estimate and giving that to their client without any further due dilligence or thought.  Of course that would be irresponsible, but ultimately it's not our problem to ensure that users are responsible.
I also saw your other question (Should those profiting from answers be allowed to ask questions?) which seems somewhat related.  It seems to me that the vast majority of questions on any SE site will be directly or indirectly related to profit and I actually think that's a Good Thing.
You also say that it could promote people carrying out work that they aren't capable of completing.  Aren't all users asking questions attempting to get help with carrying out work that they are not currently capable of completing?
And, in fact, this could be a safeguard to end clients, because if irresponsible developers are getting their estimates from reliable, trusted sources on this site (reliable, trusted sources are what SE sites tend to produce and highlight), then it should decrease the chances that they would unrealistically bloat estimates.
Answer: In order to answer questions related to estimates "how long does it take to...?" detailed information should be provided, also depends on various factors (developer skills, experience, evironment, tools used, etc).
A reformulated question:

What are the steps [and what skills should someone have] to do a certain
  task

I believe can be more appropriate and a better answer can be posted.
Comment: I agree that they should be allowed, but with adequate information on the requirements. It's one of those timeless questions, "How long does it take to do something you've never done before".
Answer: I think, this site is for shop owners, agency owners, etc. therefore they can get a feeling how long something take.
An answer like take 3-5 days is something other than 3-4 weeks.
Answering estimations is always a problem. But getting a feeling is helpful
Comment: +1 Yes that was my feeling as well, since this site is more "business-friendly" in a sense to agencies and shop owners, these kinds of questions could come in handy.
Answer: I disagree. Questions like this shouldn't be allowed.

How long ...
How much ...

The answer is subjective to the person answering the question's skill and what they have at their disposal. It isn't at all reflective of how long it would take the OP to do something - the fact they are asking the question defines that.
Thus, the answer has no validity.
Eg. How long does it take to install and configure SOLR
For us
1 minute - there's an installer built into the MageStack OS that we run. Even still, we've installed it over 100+ times; so it takes mere minutes to install and configure.
For you

What OS are you using
How many cores/instances do you need to run (staging/development/live)
What level of access do you have to the machine (root/non-priv)
Is there an available binary in your OS repo or do you need to compile from source
Are you looking to tailor to any specific requirements (language, attribute weighting etc.)
Are you running a single machine, or multi-machine configuration

etc.
Also include the fact there will be a cycle of rinse-wash-repeat as further information is extracted by means of answer editing, or comment addition. All to derive an answer which is ultimately useless to others.
It is a shopping question and thus off-topic
Server fault frowns upon shopping/consultancy type questions - why should it be any different here?
If the question was more specific

How can I ...

Then it becomes something worthwhile to other readers and users - and far more suitable to the Q&A format of the website.
Comment: +1.  Thanks this helps to articulate some of the underlying assumptions that I had.  Gonna chew on it for a bit but I think I'll give this the answer :)
Comment: Updated the question with some thoughts.  :)


If T is bounded, is it closed if X and Y are not Banach?

Question: Let $T:D_T\subseteq X\to Y$ be a bounded linear operator between normed spaces. If $X$ and $Y$ are Banach spaces, then it can easily be shown that $T$ is closed. But what if $X$ and $Y$ are NOT complete? If we assume that $x_n\in D_T$, $x_n\to x, Tx_n\to y$, then since $T$ is bounded, $Tx=y$ If $x\in D_T$, but how do we guarantee that $x\in D_T$?
Comment: In your last sentence, you say "since $T$ is closed."  Isn't that what you want to prove?
Comment: Yes I meant to say since $T$ is bounded.
Answer: No, $T$ doesn't have to be closed.  For instance, let $D$ be any dense subset of a Banach space $B$ and consider the identity $T = \text{Id} : D \to D$.  Then $T$ is bounded, but it's not closed.  In particular, if $v \in B \setminus D$, then there is a sequence $(v_{n})_{n \in \mathbb{N}} \subseteq D$ such that $v_{n} \to v$ and $T(v_{n}) = v_{n}$ so $T(v_{n}) \to v$.  Nonetheless, $v \notin D$ so $T$ is not closed.  An explicit example of this is $D = \mathbb{Q}^{d}$ and $B = \mathbb{R}^{d}$ with the Euclidean norm.
Comment: This is contrary to what my definition of closed says. Is there some intuition you can give as to why $T$ would be closed? Thanks!
Comment: What is your definition of closed?
Comment: $T$ is closed if and only if for $x_n\in D_T, x_n\to x, Tx_n\to y$, then $x\in D_T$ and $Tx=y$. So to show that $T$ is closed, we have to show both that $x\in D_T$, and that $Tx=y$
Comment: Ah, yes, you are right.  I just checked and the definition of Reed and Simon, vol. 1, is the same as you just gave.  I'll edit my answer.


Why my Alexa ReportStatus directive response not working?

Question: I want to enable alexa voice control for my smart home device. I was able to discover device. Now all devices are showing in alexa app. But when I try to turn on the device from my alexa app it is getting stuck. Loader is moving unlimited period of time. It is actually calling ReportStatus directive.
This is the json that I am getting from alexa app for a light. The light has only turn on and turn off capabilities.
   {
"directive": {
    "endpoint": {
        "cookie": {
            "detail1": "For simplicity, this is the only appliance",
            "detail2": "that has some values in the additionalApplianceDetails"
        },
        "endpointId": "endpoint-001",
        "scope": {
            "token": "weza|IwEBIGu_tmpSTQaEPvhm0OYy-4ncjve_Au1788TAWR2DC8b7xJlPDiX3HV3rJUtG0qyauIlman4bX4ZCK0-6NvKWagqXNLSdH3bDBLxD_9VtgCQo6wUlEd4DNmL9Yf5sWuUCkV1ALAxxbhqPs3QlTofubxtpSnF05ZWOSjyNUlM3ShryLh7owTywFa_7oXCCaLdLCTiqOm27aPn-yyJEDNG57Sc9iysrZkJHaxVPbdZdcqRmaw9zFGVWOqsgjqiojkKrfztslVL1Ggo6v7Teg8isrZD8osr5HFkWAmZHi8K7UrHmwQnsD9CosgSxSG0avnUoomdsZx3_LPjLJKf5twJrN1vbLolzOgxUbVuAVPVrs8UN40KFEu6eCv_7rYz9AER_61di-4w1K27kjeJvzPMIKlLXLvv6Z-2GyuQq_8M1fUdM0SgiAkqjf92S9SNxezTUiDYdOjB1JrktbQc0WM6OYYXOMjtXcCPx3bqNwWoPZWBk7qptLTurCHcYnnDl27Q0RcJ3u1vFvMaT8l0x87K6wqW2",
            "type": "BearerToken"
        }
    },
    "header": {
        "correlationToken": "AAAAAAQAeXUb9VLQcUVXClbXZQBvIDAIAAAAAAAAiBMdYahxBjRIHYbFACdRe+68uyc0KiCkClvpOCfh5dZw7NlTHoqnbbjPPydl4Nmkh4KLuFtKboYiwENwsVa9Q2WwAgRlEM+SR9PSNrWqnKvKDtulnkVXuTDkHf8f4LskbFd4VhX6cN518TA0MaZZvSfli9CN7KNY7m07P+eIv71nwxUFP5UN4xe4Jsz1V6nLzUGAG2jJIW4Lg0ARHENqDhbFtra4SV+vPXUN8L4qIwvC5xD6/mjsdN7B1ihGy/8djQA2+cxZ3XOEz2UOATyPEDlpVw5PBasQiJbRiSFSZZqEvQ0NHNfPWAWz5ieQXO1z1NAE5RMgn9d5gcEfDecjScP9DE2Yw43MypX/3VMDJmbjuTlhg9AabxLTQndKV8w9JNM1lLXcdp7i2JShOLO0bDDBPqJH1zsiZGJ93zWn+VDOTzDt+482V/AWgcHOWYnB+UZnL9GZFwEKVWTcQ20u2inFK9J11M5wr3ia57WDP6SQ7zkAmERDGfL0wswN/j0vFpqw+0/G7vjAUs2hGyg9oOy7fN2PFntk6IHV8mh47sC+ENj9dujJ9+ENwfEwEi792m7WlA8PGtvxdEqyVib5hY3qfNirqPMhMmPBf2hZlpbUfpf69q9R8GNFq41EZnTlg/AxSBjjLUJazaKQ8RU1VgipcdK1aGupJf5Oi85uEuYWN96OoEtivhUTZXg==",
        "messageId": "dd8670d5-3afa-483a-93a3-f0fff0ab6572",
        "name": "ReportState",
        "namespace": "Alexa",
        "payloadVersion": "3"
    },
    "payload": {}
  }
}

This is the response I am sending from lambda function. It is written in python 3.6.
    {
"event": {
    "context": {
        "properties": [
            {
                "name": "powerState",
                "namespace": "Alexa.PowerController",
                "timeOfSample": "2018-12-17T18:17:35.00Z",
                "uncertaintyInMilliseconds": 500,
                "value": "ON"
            }
        ]
    },
    "endpoint": {
        "cookie": {
            "detail1": "For simplicity, this is the only appliance",
            "detail2": "that has some values in the additionalApplianceDetails"
        },
        "endpointId": "endpoint-001",
        "scope": {
            "token": "weza|IwEBIGu_tmpSTQaEPvhm0OYy-4ncjve_Au1788TAWR2DC8b7xJlPDiX3HV3rJUtG0qyauIlman4bX4ZCK0-6NvKWagqXNLSdH3bDBLxD_9VtgCQo6wUlEd4DNmL9Yf5sWuUCkV1ALAxxbhqPs3QlTofubxtpSnF05ZWOSjyNUlM3ShryLh7owTywFa_7oXCCaLdLCTiqOm27aPn-yyJEDNG57Sc9iysrZkJHaxVPbdZdcqRmaw9zFGVWOqsgjqiojkKrfztslVL1Ggo6v7Teg8isrZD8osr5HFkWAmZHi8K7UrHmwQnsD9CosgSxSG0avnUoomdsZx3_LPjLJKf5twJrN1vbLolzOgxUbVuAVPVrs8UN40KFEu6eCv_7rYz9AER_61di-4w1K27kjeJvzPMIKlLXLvv6Z-2GyuQq_8M1fUdM0SgiAkqjf92S9SNxezTUiDYdOjB1JrktbQc0WM6OYYXOMjtXcCPx3bqNwWoPZWBk7qptLTurCHcYnnDl27Q0RcJ3u1vFvMaT8l0x87K6wqW2",
            "type": "BearerToken"
        }
    },
    "header": {
        "correlationToken": "AAAAAAQAeXUb9VLQcUVXClbXZQBvIDAIAAAAAAAAiBMdYahxBjRIHYbFACdRe+68uyc0KiCkClvpOCfh5dZw7NlTHoqnbbjPPydl4Nmkh4KLuFtKboYiwENwsVa9Q2WwAgRlEM+SR9PSNrWqnKvKDtulnkVXuTDkHf8f4LskbFd4VhX6cN518TA0MaZZvSfli9CN7KNY7m07P+eIv71nwxUFP5UN4xe4Jsz1V6nLzUGAG2jJIW4Lg0ARHENqDhbFtra4SV+vPXUN8L4qIwvC5xD6/mjsdN7B1ihGy/8djQA2+cxZ3XOEz2UOATyPEDlpVw5PBasQiJbRiSFSZZqEvQ0NHNfPWAWz5ieQXO1z1NAE5RMgn9d5gcEfDecjScP9DE2Yw43MypX/3VMDJmbjuTlhg9AabxLTQndKV8w9JNM1lLXcdp7i2JShOLO0bDDBPqJH1zsiZGJ93zWn+VDOTzDt+482V/AWgcHOWYnB+UZnL9GZFwEKVWTcQ20u2inFK9J11M5wr3ia57WDP6SQ7zkAmERDGfL0wswN/j0vFpqw+0/G7vjAUs2hGyg9oOy7fN2PFntk6IHV8mh47sC+ENj9dujJ9+ENwfEwEi792m7WlA8PGtvxdEqyVib5hY3qfNirqPMhMmPBf2hZlpbUfpf69q9R8GNFq41EZnTlg/AxSBjjLUJazaKQ8RU1VgipcdK1aGupJf5Oi85uEuYWN96OoEtivhUTZXg==",
        "messageId": "dd8670d5-3afa-483a-93a3-f0fff0ab6572",
        "name": "StateReport",
        "namespace": "Alexa",
        "payloadVersion": "3"
    },
    "payload": {}
}
}

Please help me. I am stuck in this for last 2 days.
Answer: Not sure if this is related to your problem. In your response, the context element is inside event. But according to the documentation and code sample, context and event should be at the same level.
{
    "context": {
        "properties": [...]
    },
    "event": {
        "header": ...,
        "endpoint": ...,
        "payload": {}
    }
}

Comment: Thank you. How I missed that. I don't know . I even checked it with Alexa sample codes. But it was the same. Thanks again. You saved me.


Como buscar todos os registros no banco de dados?

Question:
Me ajudem ai pessoal!!!

$BuscaProdutosAtivos = $pdo->prepare("SELECT * FROM tbl_produtos p
                                      INNER JOIN tbl_categorias c ON c.cat_id = p.prod_categoria
                                      INNER JOIN tbl_variacoes v ON v.cod_prod = p.id
                                      WHERE p.prod_ativo = 1");

////////////////////////////////
$BuscaProdutosAtivos->execute();
$BuscaProdutosAtivos->rowCount();

Estou buscando 3 tipos de informações dentro do banco de dados: primeiro eu busco um produto que esteja ativo para mostrar na loja, até ai tudo bem.
Depois eu busco a categoria a qual pertence este produto e também corre tudo bem.
O meu produto pode ser verde, amarelo ou azul e é isso que eu busco na tabela tbl_variacoes e tento colocar dentro de um dropdown e é ai que eu tenho problema porque ele retorna só a primeira variação, ou seja, só a primeira cor.
while($PA = $BuscaProdutosAtivos->fetch()){ ?>
    <select name="variacoes" class="form-control chosen-select" data-placeholder="Escolha a variação">
        <option value=""></option>
        <option value="1"><?=$PA['cor']?></option>
    </select>
?>

Como retorno todas as variações dentro do dropdown?

Este código me retorna todos os produtos da base que respondem aos requisitos. Se puder ajudar a compreender !!!!
Comment: Rodando a query diretamente no MySQL os registros esperados são retornados?
Comment: Revisa esse `JOIN`, aparentemente ele está errado: `INNER JOIN tbl_variacoes v ON v.var_id = p.prod_categoria`, você está cruzando o `ID` da variação com o `ID` da categoria
Comment: Não dá erro algum !!! Somente no list do dropdown ele pega só a primeira variação. Na verdade esse while é pra listar todos os produtos, então acho que precisa fazer mais alguma coisa para retornar as variações. Fiz um update da pergunta colocando link do código completo.
Comment: A query está retornando perfeitamente o que ela deve retornar que é todos os produtos ativos com pelo menos uma categoria e uma variação. Só falta retornar TODAS as variações.
Answer: Com esta query, a consulta irá retornar todas as variações cadastradas em tbl_variacoes.

$BuscaProdutosAtivos = $pdo->prepare("SELECT * FROM tbl_produtos p
                                      INNER JOIN tbl_categorias c ON c.cat_id = p.prod_categoria
                                      INNER JOIN tbl_variacoes v ON v.cod_prod = p.id
                                      WHERE p.prod_ativo = 1");

Vamos supor que você tenha 3 cores cadastradas como variações, na hora que fosse rodar o comando while, no resultado gerado, iria realizar 3 repetições. No seu atual código, irá lhe retornar 3 box do mesmo produto. Para evitar que isso aconteça, será necessário um pequeno ajuste na query:

$BuscaProdutosAtivos = $pdo->prepare("SELECT *, GROUP_CONCAT(v.cor) AS cores FROM tbl_produtos p
                                      INNER JOIN tbl_categorias c ON c.cat_id = p.prod_categoria
                                      INNER JOIN tbl_variacoes v ON v.cod_prod = p.id
                                      WHERE p.prod_ativo = 1 GROUP BY p.id");

Observe que no final da query incluí o GROUP BY p.id, que irá agrupar o resultado pelo id do produto em tbl_produtos e após o SELECT * incluí o GROUP_CONCAT(v.cor) AS cores que irá concatenar o resultado agrupado da coluna v.cor, separando por ,, e defini o apelido como cores.
E no código que você compartilhou neste link, será necessário realizar uma pequena alteração:
<select name="variacoes" class="form-control chosen-select" data-placeholder="Escolha a variação">
<option value=""></option>
<?php foreach(explode(',',$PA['cores']) as $cor) : ?>
    <option value="<?=$cor?>"><?=$cor?></option>
<?php endforeach; ?>
</select>

Comment: Bom dia. Então a tabela variações está se relacionando com a tabela produtos, ou seja, tal produto tem tantas variações. No meu código deu-se a entender que variações se relacionava com a tabela categorias, o que não é verdade. Modifiquei a SQL para deixar isso claro. A resposta dessa forma continua valendo para está situação?
Comment: Sim. Porém, a tabela `tbl_variacoes` precisará ter a coluna `cod_prod`.


Gravar dados em API RestFul Laravel através de JSON

Question: Estou tentando gravar dados em uma API Restful em Laravel através de um JSON, mas eu não consigo gravar mais de um grupo de informações quando o arquivo tem mais de um.
<code>"data": [    {
   "client_id": "3",
   "veiculo_id": "3",
   "carreta1_id": "3",
   "carreta2_id": "3",
   "motorista1_id": "3",
   "motorista2_id": "3",
   "embarcador_id": "3",
   "inicioprevisao": "2018-10-10 11:00:00",
   "fimprevisao": "2018-10-10 18:00:00",
   "nroliberacao": "3"
 },
  {
   "client_id": "4",
   "veiculo_id": "4",
   "carreta1_id": "4",
   "carreta2_id": "4",
   "motorista1_id": "4",
   "motorista2_id": "4",
   "embarcador_id": "4",
   "inicioprevisao": "2018-10-10 11:00:00",
   "fimprevisao": "2018-10-10 18:00:00",
   "nroliberacao": "4"
   }
</code>
] }
Este é o meu Controller:
<code>public function storeapi(Request $request)
{
  $array = $request->all();
    foreach ($array['data'] as $row) {
        return Sm::create([
            'client_id' => $row['client_id'],
            'veiculo_id' => $row['veiculo_id'],
            'carreta1_id' => $row['carreta1_id'],
            'carreta2_id' => $row['carreta2_id'],
            'motorista1_id' => $row['motorista1_id'],
            'motorista2_id' => $row['motorista2_id'],
            'embarcador_id' => $row['embarcador_id'],
            'inicioprevisao' => $row['inicioprevisao'],
            'fimprevisao' => $row['fimprevisao'],
            'nroliberacao' => $row['nroliberacao']
        ]);
  }
</code>
}
Desta forma, o POST na função storeapi só grava o primeiro grupo de dados que tem no JSON, o segundo não grava. Segui este artigo para conseguir gravar: https://stackoverflow.com/questions/48861486/laravel-5-6-bulk-inserting-json-data
Answer: Problema resolvido. O problema era o return que tinha na chamada do create.
<code>$array = $request->all();
$insertedIds = [];
    foreach ($array['data'] as $row) {
        $newSm = Sm::create([
            'client_id' => $row['client_id'],
            'veiculo_id' => $row['veiculo_id'],
            'carreta1_id' => $row['carreta1_id'],
            'carreta2_id' => $row['carreta2_id'],
            'motorista1_id' => $row['motorista1_id'],
            'motorista2_id' => $row['motorista2_id'],
            'embarcador_id' => $row['embarcador_id'],
            'inicioprevisao' => $row['inicioprevisao'],
            'fimprevisao' => $row['fimprevisao'],
            'nroliberacao' => $row['nroliberacao']
        ]);
        $insertedIds[] = $newSm->id;
  }
  //Now we can return an array with the inserted elements' IDs
  //In this case, since this is coming from a JSON, we'll answer the same way.
  return response()->json($insertedIds);
</code>


How can I make a user-friendly account approval for admins?

Question: Right now on my Drupal site I have everything set to send an email to the administrator once an account is created.
The administrator receives a link that says a new account is created, and there's a link to the user's profile in the email.
Is there any way for there to be a little option on the user's profile page that just says 'approve user' (that only the admin can see), or for an admin to get a link submitted to him through the email that he can click to automatically approve a user?
I'd rather admins not have to dig through the backend, look up a user, and then edit the user and approve the account manually.  Is this possible? The most preferable would be the the administrator gets an 'approval link' in the email, so he can just click 'approve' from his email, and assuming he's logged in on the site, it automatically approves the new user account.
Answer: There are two modules that you can take a look into
Admin Users

This module helps to administrate all registered users. You can sort
  out users according to their status (active or blocked), the number of
  published nodes, the number of comments, the last visit or the period
  of registration. You can also change the role of any user, block or
  delete many users with one click just ticking them in the table.

Multi-admin pending approval notifications (MAPAN)

Problem
The current behavior in Drupal core when a new user registers
  requesting approval sends mail only to the site's contact address.
  Thus only one person is notified even though there may be several
  administrators/moderators.
Solution
This module improves this basic behavior by notifying all users that
  have the 'administer users' permission by default.
  Administrators/moderators get a setting to disable these notifications
  in their user profile form. A link is also appended to each of these
  notifications.
Answer: There is another module called User registration notification which states

Allows admin notifications to roles or custom e-mail address
Allows changing the 'from' address
Allows adding custom 'reply-to' address
Settings can change all core account setting e-mail templates
Allows you to send emails on user create/update/delete to your delegated users
Allows selection of e-mail message types that will be altered
Allow customization of Core hidden Admin (pending admin approval) e-mail

but in hindsight it offers nothing towards what sound like the crux of the OP, namely that approval can be triggered by just 'clicking a link in an email'


How can I query a MongoDB database with different child levels?

Question: I'm new to mongoDB using pymongo. I'm trying to query a collection and also get a specific child from a field. This is what I tried:
import pymongo
import csv
from pymongo import MongoClient

connection = MongoClient()
db = connection.database
collection1 = db.data1
collection2 = db.data2
writer = csv.writer(open("Result_example.csv", "w"))
with open('Data_example.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=';')
    for row in spamreader:

        for rows in collection1.find({"_id": row[0]}, { "childs.first.name": 1}):
            writer.writerow([row[0], rows.get("childs.first.name")])

The database structure is like this:
child
   first
      name

What I want to get is the name...Any ideas?
Thanks!!!
Answer: Other than the field not being pluralized in the example structure that was provided, the following query looks fine.
for rows in collection1.find({"_id": row[0]}, { "child.first.name": 1}):

Note that child field is singular.
rows is a reference to a dictionary object like below:
{
    'child': {
        'first': {
            'name': 'Vorname'
        }
    }
}

rows.get("childs.first.name") returns None in writer.writerow([row[0], rows.get("childs.first.name")])
You can retrieve the name using

rows.get('child').get('first').get('name')

Or

rows['child']['first']['name']

You can save these nested key accesses by running an aggregation that returns the document id and firstname in place of collection1.find({"_id": row[0]}, { "child.first.name": 1}).
children_names = db.collection1.aggregate([
    {
        '$match': {'_id': ObjectId(row[0])}
    },
    {
        '$replaceRoot': {'newRoot': {'_id': '$_id', 'first_name': '$child.first.name' }}
    },

])

Key access could then be done once.
for rows in children_names:
    writer.writerow([row[0], rows.get("first_name")])


C# como fazer pesquisa em database usando parâmetros

Question: Tenho o seguinte código
public DataTable PesquisarPorNome(string NomePesquisado)
{
    try
    {
        DataTable tabela = new DataTable();
        SqlDataAdapter adaptador = new SqlDataAdapter("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade LIKE '%" + NomePesquisado + "%' ", conexao.StringConexao);
        adaptador.Fill(tabela);
        return tabela;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    finally
    {
        conexao.DesconectarDoBanco();
    }
}

Sei que se eu disponibilizar isso, a vaca vai para o brejo, pois SQL Injection está aí para isso, porém como usar parâmetros ?
Obrigado
Comment: Ok, não sei se entendi a sua pergunta, estou usando o MSSQL  . Sei que SQL é uma linguagem , que muitas vezes confundimos com o MSSQL é que o SGBD.
Comment: Qual banco de dados vc esta usando?
Comment: Desculpe, não estou recebendo notificações, estou usando SQL
Comment: Antonio, o Structured Query Language  [(SQL)](http://pt.stackoverflow.com/tags/sql/info)  é uma linguagem para consultar bancos de dados.
Answer: Veja o exemplo abaixo,
public DataTable PesquisarPorNome(string NomePesquisado)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = myConnString;
        try
        {
            var SQL = string.Format("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade  LIKE @NomePesquisado");

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = SQL;
            cmd.Parameters.Add("@NomePesquisado", SqlDbType.NVarChar).Value = "%" + NomePesquisado + "%";
            SqlDataAdapter sqlA = new SqlDataAdapter();
            DataTable tabela = new DataTable();

            sqlA.SelectCommand = cmd;

            conn.Open();
            sqlA.Fill(tabela);

            return tabela;
        }
        finally
        {
            conn.Close();
        }
    }

Só faltou vc especificar o banco de dados que esta usando..
Answer: Assim que se faz consulta com parameters e LIKE clause.
var cmd = new SqlCommand("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade LIKE '%'+ @NomePesquisado +'%'", connection);
cmd.Parameters.Add("@NomePesquisado", SqlDbType.VarChar, 50).Value = NomePesquisado;
var dr = cmd.ExecuteReader();

Comment: Quem deu downgrade pode justificar?


Can a football team buy and sell a player in the same transfer window?

Question: For example, the current transfer window for most leagues in Europe ends tomorrow.
Manchester United bought Depay from PSV this window. Could they sell him tomorrow if they wanted? Or do they need to wait until the mid-season transfer window at least?
Answer: YES
It has happened last sunday (30/08/2015).
Jelle Vossen was transferred from Burnley to Club Bruges after only buying him this transfer window from KRC Genk.
Play for maximum two teams in one season
However, there is a rule saying a player can only play for maximum two clubs in one season. If for instance Depay would have played an official match for PSV, then an official match for Man Utd, he would no longer be able to play for a third club, even on loan.

Regulations on the Status and Transfer of Players Chapter III, Article 5.3
Players may be registered with a maximum of three clubs during one
  season. During this period, the player is only eligible to play offi
  cial matches for two clubs. As an exception to this rule, a player
  moving between two clubs belonging to associations with overlapping
  seasons (i.e. start of the season in summer/autumn as opposed to
  winter/spring) may be eligible to play in offi cial matches for a
  third club during the relevant season, provided he has fully complied
  with his contractual obligations towards his previous clubs. Equally,
  the provisions relating to the registration periods (article 6) as
  well as to the minimum length of a contract (article 18 paragraph 2)
  must be respected.


Use of low rank approximation of a matrix

Question: I am trying to figure out why do we need a low rank approximation of a matrix. Why is it used and where? Any insights?
Comment: For example, if your matrix represents a graphic image, you could use a low rank approximation of it as a form of lossy compression.
Answer: Please, read http://arxiv.org/pdf/0912.3599.pdf, page 3. This might be helpful.
I have also reformulated your question a bit here https://math.stackexchange.com/questions/906417/applications-of-low-rank-matrix-approximation


After releasing my app gmail auth does not work

Question: I have tested my app before releasing it, tested in "debug/release Build Variant". With the both build Gmail login was working fine. As soon as i release my app in google play store ..
I am unable to login using gmail login. I have added SHA1 and SHA256 finger print in firebase, and added respective google.serivces.json file inside app folder.
Any one can help to fix this issue?
Comment: can you paste logs ?
Comment: When you click on Gmail login what's going on ?
Comment: @TGMCians How to get the log of running apps, which has downloaded from Google play store. I dont know.. Please let me know one's...
Comment: @Arrabidas92.. When i click gmail login... It allows to press gmail id/add new gmail id.. After that it does not do any action.. Means "Intent" shouldn't call required file.
Answer: There are two different SHA keys, debug & release.
Comment: I have added both the SHA1 finger Printa.In the release Build variant I am able to login through Gmail Auth.                                 But when i publish my app and after that if i download it and use it.. Gmail Auth is not working.. It is grey area for me..


PDF of an order statistics divided by a parameter

Question: Let $$ x_{1}, x_{2}, ... x_{n}  $$
be IID uniform on $$ [0,\theta] $$
Find the PDF of $$ \frac {x_{(n)}} {\theta} $$
The way I initially though about this question is to find the pdf of nth order statistics, but I do not how to proceed from there.
Now I saw the solution, I know I was supposed to find the CDF and then differentiate to get the PDF.
However, I just want to know is there any way to get to the answer from my initial approach?
Thanks!
Answer: remember that
$ x_{(n)}=Max \{x_1,...,x_n\} $
and
$ F_{x_{(n)}}(x)={F(x)}^n = (\frac{x}{\theta})^n  $ on $ 0 < x<\theta $
then
$F_{\frac{x_{(n)}}{\theta}}(x)=P(\frac{x_{(n)}}{\theta}<x) = P(x_{(n)}<x\theta ) $
$= (\frac{(x\theta)}{\theta})^n $ on $0 < x\theta < \theta $
dividing theta
$= x^n $ on $0 < x < 1 $
These problems are typically tedious because you have to consider the limits of their distribution


How to add 2 days excluding sat and sun days in XSLT

Question: I am using XSLT 2.0, there is no date input from the XML file so I have to use the current date for this operation and produce the output in HTML.
The condition is to add 2 days from the current date and exclude Saturday and Sunday from it.
Example:
The current date is 14th July 2022 Thursday
The Expected date is 18th July 2022 Monday
Another example:
The current date is 15th July 2022 Friday
The expected date is 19th July 2022 Tuesday
Could you help me with this?
Comment: What if today is Saturday or Sunday?
Answer: Here's a simple (not to say "primitive" ) way you could look at it:
XSLT 2.0
<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="today" select="current-date()"/>

<xsl:template match="/">
    <xsl:variable name="day-of-week" select="format-date($today, '[FNn, *-3]')" />
    <xsl:variable name="add">
        <xsl:choose>
            <xsl:when test="$day-of-week='Sat'">3</xsl:when>
            <xsl:when test="$day-of-week='Fri'">4</xsl:when>
            <xsl:when test="$day-of-week='Thu'">4</xsl:when>
            <xsl:otherwise>2</xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <result>
        <xsl:value-of select="$today + $add * xs:dayTimeDuration('P1D')"/>
    </result>
</xsl:template>

</xsl:stylesheet>
</code>
A smarter way would calculate the number of days to add - but I think in this case it's not worth the bother.
A better way would examine each added day in a loop - subtracting it from the count only if it's a work day. That is the only way I know of that would also consider holidays.
Comment: A general solution that adds N days would be rather more elegant, but he asked for N=2 so this meets the requirement.
Comment: You can request the day of the week as an integer (F1) but I'm not sure the spec says what answer you get....
Comment: @MichaelKay I could also subtract some epoch from the given date modulo 7 to get a more convenient result of 0..6. But the "elegant" solution would still not cater for holidays.
Comment: Great it works now. Well, wonder how easily you coded this.
Comment: Comment on my previous comment: the spec says that "in the ISO calendar the days of the week are numbered from 1 (Monday) to 7 (Sunday)".


Prove that hyperbolic isometry with constant distance is the identity

Question: Let $f$ be an isometry of the Poincaré half-plane model of two-dimensional hyperbolic geometry, denoted by $\mathbb{H}^2$. Prove that if the distance $d(z,f(z))=c$ for some constant $c\geq0$ for all $z \in \mathbb{H}^2$, then $f$ is the identity isometry.
This is of course not true in the Euclidean case. A translation in the Euclidean plane has constant distance but is not the identity.
My first idea was to prove the contrapositive - that if $f$ weren't the identity, then it would have to be one of the non-trivial isometries, so expressible as either:
$$f(z)=\frac{az+b}{cz+d} \quad \text{or} \quad f(z)=\frac{a\bar{z}+b}{c\bar{z}+d}$$
For some $a,b,c,d \in \mathbb{R}$ satisfying $ad-bc=1$ in the former case (orientation preserving) and $ad-bc=-1$ in the latter (orientation reversing), with the added condition that $(a,b,c,d)\neq(1,0,0,1)$ in the former case, as we do not want the identity.
But this approach is quite unwieldy and requires the use of the distance function, taking cross-ratios $\textit{et cetera}$. I believe there must be a slicker solution using the concept of fixed points or some other notion of hyperbolic geometry.
All help or input would be highly appreciated.
Comment: If you don't want me to use the distance function, what am I allowed to use?
Comment: For example, this problem would be a snap if I could use the classification of isometries.
Comment: Yes, that's what I meant regarding classification of isometries. I can write an answer like that if you want.
Comment: @LeeMosher I mean that the method suggested above required the consideration of separate cases and computing the explicit distance of two points, using the explicit distance function $d(A,B)=|\textrm{log}[A,B,X,Y]|$ in each case. One is, naturally, going to have to use the notion of distance to solve the problem.
And by classification of isometries, do you mean to say that we can use the fact that if the isometry is not the identity, then it is either parabolic, elliptic, hyperbolic or loxodromic, and then show in each case that none of these types isometries fix distances?
Comment: @LeeMosher I believe I understand what your argument entails. We know that if the isometry $f$ belongs to one of the four classes of non-identity isometries, then at least one point is fixed, and so we must have $c=0$ (with $c$ defined above) - contradicting the fact that the isometry is not the identity. My only scruples with this argument are that if we let $f$ be a parabolic isometry, so that it only preserves one point, and let the preserved point be $\infty$. Can we say that $d(\infty,f(\infty))=0 \implies c=0$?
Answer: Here's a proof, which uses the classification of isometries.
But first I need to address an issue that you raised in the comments.
Warning: When an isometry acts on the compactified hyperbolic plane $\overline{\mathbb H}^2 = \mathbb H^2 \cup S^1_\infty$ it always has at least one fixed point of $\overline{\mathbb H}^2$. But, points in $S^1_\infty$ are not involved in distance measurements; points in $S^1_\infty$ are "infinitely far" and are not part of the domain of the distance function; $d(p,q)$ is only defined for $p,q \in \mathbb H^2$.
So the problem asks to prove that if $f$ is not the identity then $d(p,f(p))$ is not constant for $p \in \mathbb H^2$.
Having said that, let me go through the cases of non-identity isometries. Let $Fix(f)$ be the fixed point set of $f$ on $\overline{\mathbb H}^2$, which breaks into two pieces: the finite fixed points $Fix_{fin}(f) = Fix(f) \cap \mathbb H^2$, and the infinite fixed points $Fix_{inf}(f) = Fix(f) \cap S^1_\infty$.
Every non-identity isometry falls into one of four cases, as follows:
Case 1: $Fix(f)$ consists of two infinite points $\xi,\eta \in {Fix}_{inf}(f)$. In this case, letting $L$ be the line with infinite endpoints $\xi,\eta$, one proves that $d(p,f(p))$ is constant for $p \in L$ and that $d(q,f(q)) > d(p,f(p))$ for $p \in L$ and $q \not\in L$. Geometrically $f$ is either a "translation" along the line $L$, or what is called a "glide reflection" which is a translation along $L$ composed with a reflection across $L$.
Case 2: $Fix(f)$ consists of an entire line $L = {Fix}_{fin}(f)$ and its two infinite endpoints $\partial L = {Fix}_{inf}(f)$. In this case then $d(p,f(p))=0$ for $p \in L$ but $d(p,f(p)) \ne 0$ for $p \not\in L$. Geometrically $f$ is a reflection across $L$.
Case 3: $Fix(f)$ consists of a single finite point $p = {Fix}_{fin}(f)$. In this case $d(p,f(p))=0$ and $d(q,f(q)) > 0$ for $q \ne p$. Geometrically $f$ is a rotation around $p$ of some angle $\theta \in (0,2\pi)$.
Case 4: $Fix(f)$ consists a single infinite point $\xi = {Fix}_{inf}(f)$. Since ${Fix}_{fin}(f) = \emptyset$, $d(p,f(p))>0$ for all $p$. However, given any line $L$ with endpoint $\xi$, $\lim_{q \in L, q \to \xi} d(q,f(q)) = 0$ where we let $q$ approach $\xi$ in $\overline{\mathbb H}^2$ along the line $L$. So $d(q,f(q))$ is not constant. Geometrically $f$ is a parabolic isometry.
There's still the question of how the conclusions are proved in these four cases. But if you know the classification of isometries in more detail, i.e. if you know how the classification is related to the fractional linear transformation formulas you provided in your question, then it's not too hard to justify those conclusions.


Which tensorflow-gpu version is compatible with Python 3.7.3

Question: Actually, I am tired of getting "ImportError: DLL load failed"
in

Windows 10
CUDA Toolkit 10.0 (Sept 2018)
Download cuDNN v7.6.0 (May 20, 2019) / v7.6.4
tensorflow-gpu==1.13.1 / 1.13.2 / 1.14 / 1.15 / 2 (none of those were working)
Answer: At the moment TensorFlow for GPU doesn't support Python 3.7 on Windows 10.
For a list of packages see "Package location" at the bottom of https://www.tensorflow.org/install/pip?lang=python3
It lists the following for Windows:
Python 3.5 CPU-only https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-2.0.0-cp35-cp35m-win_amd64.whl
Python 3.5 GPU support  https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.0.0-cp35-cp35m-win_amd64.whl
Python 3.6 CPU-only https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-2.0.0-cp36-cp36m-win_amd64.whl
Python 3.6 GPU support
https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.0.0-cp36-cp36m-win_amd64.whl
Comment: suggest a preferable CUDA version and CUDNN
Answer: I am using Windows 10 (64 bit) and I use these versions in a project and they work together:
<code>python:3.7.4
tensorflow-gpu: 1.15
cuda:10.0
cudnn:22.214.171.124
numpy:1.17.4
</code>
Comment: in windows10x64,1909,nvidia GPU