Biblioteca estática

Question: Criei uma biblioteca estática em C, ou seja, após compilado o arquivo .c, gerou um arquivo com extensão .a. No arquivo .c implementei algumas funções. Como eu poderia ler essa lib em outro programa e chamar uma função dela? Estou apenas dando o include do .h no programa, e quando compilo o programa ele exibe na mensagem de erro: referencia indefinida para func() que segue logo abaixo:
#ifndef STATIC_H
#define STATIC_H

extern int func();

#endif

Comment: a biblioteca estática está com extensão .a
Comment: ela esta com extensão .h?
Answer: 1ª Opção e acho que você já deve ter tentado é usar o cabeçalho:
#include "libstatic.a"

Aponte para o local correto da biblioteca.
2ª Opção encontrada nesta resposta do SOen:
cc -o yourprog yourprog.c -lstatic

ou
cc -o yourprog yourprog.c libstatic.a

3ª Opção também encontrada no SOen:
gcc -I. -o jvct jvct.c libjvc.a

Encontrei um link que ensina a criar um Lib em C (veja se não esqueceu nenhuma etapa) Link
Comment: Eu tentei incluir  o .h que contem os prototipos das funções implementadas na biblioteca estática (.a), e compilei o programa usando -l+(nome_lib_static) na hora de compilar, mas na compilção ele da o erro de refencia indefinida na chamada da função da biblioteca.
Comment: Testou a segunda opção, e o link que referenciei?
Comment: Deu certo usando a terceira opção, obrigado!!
Answer: Acredito que você já criou um .h exportando as funções da biblioteca; se fez isso basta incluir o .a na linha que monta o seu executável.
Bom, acho melhor colocar um exemplo mais completo:
teste.h:
#ifndef STATIC_H
#define STATIC_H

    extern int func();

#endif

static.c:
#include "teste.h"

int func() {

    return 10;

}

app.c:
#include <stdio.h>
#include "teste.h"

int main(int argc, const char **argv) {

    printf("func() retornou %d\n",func());
    return 0;
}

Para compilar:
gcc -o static.o -c static.c
ar rcs static.a static.c
gcc -o app.o -c app.c
gcc -o teste app.o static.a

Comment: Então, acredito que seja isso. Eu estou usando o extern, mas somento no .h, mesmo assim não deu. Postei o .h na pergunta.

Biblioteca estática


hide perspectives

Question: I created one perspective in eclipse workbench, not in eclipse rcp.Is it possible to hide other perspectives like java,debug? I just want to show only my perspective in my application.That should be the default one.Or I dont need to show any perspectives but my perspective which I created should be the default one. How do I do?
Answer: You can use activities.
I also wrote a blog entry on this some years back: Using activities for user management.
UPDATED the link
Answer: You can close wanted perspective like below:
<code>IPerspectiveDescriptor[] openPerspectives = page.getOpenPerspectives();
for (IPerspectiveDescriptor openPerspective : openPerspectives) {
//add your own perspective name
  if (openPerspective.getLabel().equals("<perspectiveLabel>")) {
    page.closePerspective(openPerspective, false, false);
  }
}
</code>

hide perspectives


stochastic integrals and inequalities (boundedness)

Question: We have  $X(t)=[X_1(t)\ X_2(t)\ X_3(t)\ \dots\ X_n(t)]$ and $Y(t)=[Y_1(t)\ Y_2(t)\ Y_3(t)\ \dots\ Y_n(t)]$ are two stochastic process such that: $$\sup E[Y_1^2] \leq K,$$ on $[t_0, T]$ with $K$ a positive integer.
Is that true
$$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt \leq \sup E[Y_1^2]E\int^T_{t_0}  F(X(t))^2 \, dt$$
Important note: $Y_1(t)$ is a function of $X_1$.
Answer: In general I don't see any reason why this should be true. However, if $Y_1(t)^2$ and $F(X(t))$ are independent for Lebesgue a.e. $t$ (it would be sufficient to assume $Y_1$ and $X$ are independent, of course), then it does hold.
You may say by Tonelli's Theorem (Fubini's Theorem for nonnegative integrands)
$$
E\int_{t_0}^T Y_1(t)^2 F(X(t))^2~dt = \int_{t_0}^T E[Y_1(t)^2 F(X(t))^2]~dt
$$
which by independence is
$$
=\int_{t_0}^T E[Y_1(t)^2] E[F(X(t))^2]~dt
$$
and by monotonicity of the integral is
$$
\leq \int_{t_0}^T (\sup_s E[Y_1(s)^2]) E[F(X(t))^2]~dt
$$
$$
= \sup_t E[Y_1(t)^2]\int_{t_0}^T E[F(X(t))^2]~dt
$$
and again by Tonelli's Theorem this is
$$
=\sup_t E[Y_1(t)^2]E\int_{t_0}^T F(X(t))^2~dt.
$$
Comment: the reality i was trying to prove that $$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt < infinity \, $$  but because Y1(t) and X1(t) are dependent so i didn't found a manner to prove it , i have also supE[F(X(t))^2]≤C,
Comment: because if i ensure $$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt \leq infinity \, $$ By the ito property i can deduce that $$E\int^T_{t_0} Y_1 F(X(t))dw \,  =0 \, $$ after a deep reading i think that i can use Holder's inequality to prove:$$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt \leq infinity \, $$ even X1(t) and Y1(t) are dependent
Comment: In the future please only ask questions that you want to know the answer to.
Comment: i just asked a part of a question because i think that if this part will be resolved the remainder is easy to do, but unfortunately this part is so hard to do. any way i'm so sorry if i made you confused.
Comment: but i realy appriciate your help teacher.
Comment: this is my question,(which i want to know the answer), we have $$\sup E[Y_1^2] \leq K,$$ on $[t_0, T]$ with $K$ a positive integer.
and $$\sup E[F(X(t))_^2] \leq C,$$ on $[t_0, T]$ with $C$ a positive integer. i want to know if $$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt \leq <infinity, $$ thus, $$E\int^T_{t_0} Y_1 F(X(t)) \, dW , $$ is an ito process
Comment: this is my question,(which i want to know the answer), we have $$\sup E[Y_1^2] \leq K,$$ on $[t_0, T]$ with $K$ a positive integer.
and $$\sup E[F(X(t))^2] \leq C,$$ on $[t_0, T]$ with $C$ a positive integer. i want to know if $$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt < infinity, $$ thus, $$E\int^T_{t_0} Y_1 F(X(t)) \, dW , $$ is an ito process
Comment: You need to make some assumptions on $F$ or on $F(X)$. Since you want to pull out the $Y_1^2$, the only way you could do this with Holder's inequality, without assuming independence, and get something finite would be if you assumed $F(X)$ is essentially bounded for a.e. $t$.
Comment: i think even with holder's inequality it still difficult, because holder's inequality leads  only to show that $$E\int^T_{t_0} Y_1 F(X(t)) \, dt <infinity, $$ and not $$E\int^T_{t_0} Y_1^{2} F(X(t))^2 \, dt <infinity, $$
Comment: i will look about another solution, thanks teacher, so sorry for troubling you


Meaning of "average correlation" in Var$(\bar X)$

Question: From some process I got a series of values. I want to compute the variance of the mean from this series. The series is built with contiguous sub-series. In each sub-series the values are correlated. All sub-series follow the same pattern but they have different total lengths.
I read on Wikipedia that for correlated variables holds
$$\operatorname{Var}\left(\overline{X}\right) = \frac{\sigma^2}{n} + \frac{n - 1}{n}\rho\sigma^2 $$
where $\rho$ is the average correlation.
Q1: What does average correlation means or how it is computed?
Intuitively I would expect it to be something like the lag or the sum of all lags of the autocorrelation function of the series, but I don't know.
Q2: Is this approach reasonable?

EDIT: I checked these questions:
According to comments, I should use:
$$\operatorname{Var}\left(\sum_{i=1}^n X_i\right) =  \sum_{i=1}^n \operatorname{Var}\left(X_i\right) + 2\sum_{1\le i<j\le n}\operatorname{Cov}\left(X_i, X_j\right)$$
but I am not sure on how to compute the $\operatorname{Cov}\left(X_i, X_j\right)$.
If it helps, the data arises from an stationary process (although it always starts with a complete sub-series).
Variance of a sum of identically distributed random variables that are not independent
Variance of sum of dependent random variables
and this article.
Comment: Use the formula just stated above in wikipedia.
Comment: @User1865345, Thank you! I am not sure how to do that. I edited the question according, could you check it out?
Comment: What is covariance in terms of correlation? Use that. All the variances are identical. The covariance between each pair is same. Proceed then to calculate the variance of the mean (divide both sides by $n^2$).
Comment: @User1865345, Thank you! Does not the covariance depends on $j-i$ ? Something like $cov(x_i,x_j)=\rho[j-i]\sigma^2$. ?
Comment: Check [Wikipedia](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Definition).
Answer: The general formula is
$$\text{Var}\left(\sum_{k=1}^n a_k X_k\right) =  \sum_{k=1}^n a_k^2 \text{Var}\left(X_k\right) + \sum_{k=1,l=1 \\k\neq l}^n a_k a_l \text{Cov}\left(X_k,X_l\right) $$
And when all the variances are equal to $\sigma^2$ and all $a_k = \frac{1}{n}$ then
$$\sum_{k=1}^n a_k^2 \text{Var}\left(X_k\right) + \sum_{k=1,l=1 \\k\neq l}^n a_k a_l \text{Cov}\left(X_k,X_l\right) = \sum_{k=1}^n \frac{1}{n^2} \sigma^2 + \sum_{k=1,l=1 \\k\neq l}^n \frac{1}{n^2} \rho_{k,l}\sigma^2 = \frac{1}{n} \cdot \sigma^2  + \frac{1}{n^2} \left( \sum_{k=1,l=1 \\k\neq l}^n \rho_{k,l} \right) \cdot \sigma^2$$
It is this sum of all the correlations $\rho_{k,l}$ that is being replaced by the average.
$$\sum_{k=1,l=1 \\k\neq l}^n \rho_{k,l}  = \bar\rho  \cdot n \cdot (n-1)$$

but I am not sure on how to compute the $\operatorname{Cov}\left(X_i, X_j\right)$.

See the definition of the Pearson correlation coefficient $\rho_{X,Y} = \frac{Cov(X,Y)}{\sqrt{Var(X)\cdot Var(Y)}}$
Comment: +1 Thank you! Could you take a look at this related question? https://stats.stackexchange.com/questions/588821/how-to-compute-the-variance-for-this-process


Five different groups

Question: We are running a study which investigates platelet aggregation changes during three trimesters of pregnancy and postnatal period.
Then we compare each of these phases to control non-pregnant women.
The sample size is 46 including 10 per each trimester, 10 postnatal and 6 as control.
The cases we recruited during these phases are not the same women (i.e first trimester women are different from those of second trimester and so on). We used nine aggregation agonists for each group.
We used the Kruskal-Wallis test to compare these five groups to each other as they are completely different then if we find p-value is significant, we performed a post-hoc Mann-Whitney test to find which pairs of groups are different.
The questions here are:

Is this the right way to analyse the data in this study using the above tests and are we justified?
What are the limitations of using these tests?
Is there any better way to use in this research?
Answer: Post hoc pair-wise tests following rejection of Kruskal-Wallis should be performed with Dunn's test, not a run of the mill rank sum test, because (1) the Kruskal-Wallis test decision was based on a separate set of rankings, and (2) Dunn's test uses a pooled estimate of the variance implied by the null hypothesis. See also: Post-hoc tests after Kruskal-Wallis: Dunn's test or Bonferroni corrected Mann-Whitney tests?.

Five different groups


Help combining 2 views?

Question: I have a content type with two fields: Exterior Images and Interior Images
Both of these fields are Unlimited Values - so the user can upload as many images as they want to exterior and interior. Screenshots: http://prntscr.com/a9m8o5 http://prntscr.com/a9m8uc
Now I'm trying to create a view that grabs all exterior and interior images uploaded and displays them.
The only way I can find to have each image displayed as its own individual field and row is to perform a UNION betwen something like SELECT exterior UNION SELECT interior etc. etc. but I just can't seem to figure out the rest.
I've tried creating two views and combining them like this:
<code>function pgallery_views_pre_execute(view &$view){

    if ($view->name == 'photo_gallery'&& $view->current_display == 'page_1') {
        // View 1 contains Interior Images
        $view1 = views_get_view('photo_gallery');
        $view1->build('block_1');
        $query1 = $view1->build_info['query'];

        // View 2 contains Exterior Images
        $view2 = views_get_view('photo_gallery');
        $view2->build('block_2');
        $query2 = $view2->build_info['query'];

        $query1->union($query2);

        $view->build_info['query'] = $query1;

    }

}
</code>
but it won't render whatever is in $query2 - it just repeats $query1 values. So I get the correct number of "rows" from the result but it repeats the data for some reason. Please help!
Answer: Views Field View module does that. Create a new view and add both needed views as fields.

This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.
This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.
Answer: You should be able to add both fields in views and in the settings for the field, there are options for multiple values. So views go through each node and outputs each image.

Help combining 2 views?


Why is the canonical product $\sigma$-algebra the right $\sigma$-algebra on the product space?

Question: Let $I$ be a finite, countably infinite or uncountable index set and let $(\Omega_i,\mathcal{A}_i)_{i \in I}$ be measurable spaces. Then we can define the sigma algebra
$$ \mathcal{A} := \bigotimes_{i \in I} \mathcal{A}_i $$
on the product space $\Omega := \times_{i \in I} \Omega_i$ as the smallest sigma algebra, such that all projections
$$ \pi_i\rightarrow \Omega : \Omega_i, \quad \omega  \mapsto \omega_i, $$
are $\mathcal{A}$-$\mathcal{A}_i$-measurable.
This is the canonical way of defining a $\sigma$-algebra on a product space and is used (mostly without further explanation) in lots of textbooks about advanced probability.
My problem is that I am lacking intuitive motivation for this defintion. Is this the only reasonable way to define a $\sigma$-algebra on the product space? Why? If not, why do whe choose this definition over all other possible methods for constructing $\sigma$-algebras on $\Omega$? What are the essential advantages of this definition? In short: why is this the right $\sigma$-algebra on $\Omega$? Why could it not be different?
Kind regards and thanks for any help!
Comment: It is the right *product* $\sigma$-algebra.
Answer: Let $(\Omega',\mathcal A')$ be a measurable space and let $f_i:\Omega'\to\Omega_i$ for $i\in I$ denote a collection of measurable maps.
Then especially if $\Omega$ is equipped with $\mathcal A=\bigotimes_{i \in I} \mathcal{A}_i$  a unique measurable $f:\Omega'\to\Omega$ such the $f_i=\pi_i\circ f$ for every $i\in I$.
Conversely every measurable map $f:\Omega'\to\Omega$ induces a family $\{f_i=\pi\circ f:\Omega'\to\Omega_i\mid i\in I\}$ of measurable maps, so the correspondence is one-to-one.
This offers the nice possibility to identify families $\{f_i\mid i\in I\}$ of measurable maps that have common domain with just one measurable map $f$.
That is for a good deal the underlying motivation for the construction of products.
Comment: The property described in this answer is the *definition* of a product in category theory.
Comment: Thanks. This is a very good answer. Do you know, if $\mathcal{A}$ is the only $\sigma-$ algebra such that there is such a one-to-one correspondence?
Comment: @Joker123 Yes, it is. If another space $(\Omega_0,\mathcal A_0)$ has the same property then it can be shown that a bijection $f:\Omega\to\Omega_0$ exists that is measurable in both directions. So actually the measurable spaces turn out to be isomorphic. Between them there is no essential difference.
Answer: The main reason, I think, is that the construction you describe satisfies the axioms for the categorical product in the category of measurable spaces.  This, of course, raises the follow-up question: why are categorical products good?  I can think of a few reasons:

With other $\sigma$-algebras on the product it could be quite hard to check that a map into a product is measurable; with the categorical product you just need to check that all compositions with your map and the projection maps are measurable.
Categorical products are compatible with a lot of other constructions like (co)limits and adjunctions that come up naturally in measure theory, and you get that compatibility for free.
Most other product structures in mathematics, like the product topology or the product group structure, are also categorical products.  With your definition you can prove quite easily that the Borel $\sigma$-algebra on the product of topological spaces agrees with the product of the Borel $\sigma$-algebras on the factors, for instance.

It's also worth noting that your definition gives the "right" answer in the case where the index set is finite: the product $\sigma$-algebra is the smallest $\sigma$-algebra for which products of measurable sets are measurable.  You could try to just naively extend this definition to get a $\sigma$-algebra on the product of arbitrarily many measurable spaces, but experience in other settings (e.g. the product topology) suggests that it's better to generalize along universal properties than along set-theoretic constructions.
Answer: This sigma algebra is chosen because it always exists. For any collection of events you may consider the intersection of all sigma-algebras containing these events, and it is the smallest sigma algebra containing these events. It always works.
But for Lebesgue sigma algebra in $R$ and in $R\times R$, it is not actually that convenient, because some nice properties of the Lebesgue measure are lost when taking the product.
From Exercise 1.7.19(v) in "An introduction to measure theory" by Terence Tao:
If $\mathcal F$ is the Lebesgue sigma-algebra on $R$, then the product sigma-algebra is not the Lebesgue sigma-algebra on $R\times R$. In particular, the product sigma-algebra of two Lebesgue sigma-algebra is not complete, so the product measure here misses out the nice property that the Lebesgue measure is complete.


How to resolve Error Starting Kernel in JupyterLab

Question: I know there are a lot of similar questions, that have already been solved out there, but the solutions are a bit too complex for me.
Long story short, I am not good at installing things and getting them up and running at all. Took me months to work out how to install JupyterLab.
But I finally did it! and I even set up a piece of Batch code to launch it in my current directory.
C:\anaconda3\python.exe C:\anaconda3\cwp.py C:\anaconda3\ C:\anaconda3\python.exe C:\anaconda3\Scripts\jupyter-lab-script.py "%CD%"

However, now I am getting this error
Error Starting Kernal
Is there a simple way to address this issue? Do I just need to move my kernel script to the right folder? Add something to redirect the batch file to find the kernel?
Answer: Run this command to fix the error
python -m ipykernel install --user

Comment: Actually, I ended up uninstalling all of my Python and Anaconda stuff because I couldn't import any of the packages and thought it might be due to there being multiply python programs on my computer.
Then I re-installed just Anaconda and now this command no longer works...


Singer "benchmarking"

Question: Are there tools or techniques around to "benchmark" singers? What I mean is: if I'm not performing up to my goals, I want to know what I'm lacking and what type of training I need to go through.
Also, I'd like to get a grip of my physical limitations so I don't waste my time trying to overcome them, but rather direct my music to work around them.
Suppose that I record my voice while singing and take a look at the spectrum. What does good singing "look like"?
Am I on the right track here? Is there such a thing?
EDIT
I have a voice coach and although he does say when I've performed brightly or not, I don't understand his means to do so. Even if he explains them to me, I'd also like to develop my own references and measures when it comes to singing, because sometimes I don't like the way I sound, I feel it's different from great singers and I don't know exactly what is sounding off to me.
EDIT
I intend to look for a more "scientific" way of measuring progress and comparing to great singers. I'll leave this question open until I've made some progress or someone contributes something in this regard.
Comment: I've found that recording yourself is a good way to keep track of progress and also see where your shortcomings are.
Answer: To be honest, I think you're on the wrong track. I don't believe that there can be a universal and objective tool that does what you want. What you need is an experienced teacher / vocal coach who will listen to the way you sing, the way you breathe, and who can tell you what you should focus on and which techniques and exercises should be used to achieve your goals.
Singing is also not only about technique, so 'benchmarking' singers will remain a very subjective matter anyway. The only thing I can think of is measuring the pitch to judge whether you sing in tune or not. There are tools for this, but they will not solve your problem because even if you sing in tune, your technique might be wrong, so it won't sound good or you will strain your voice unnecessarily.
Comment: I've updated the question with info regarding my vocal coach. Things besides measuring pitch is what I'm looking for, but I understand that they might not exist - hence the question! :)
Answer: Sounds like you have goals you'd like to meet, but art in general, including singing, is utterly subjective so as to whether you're meeting them or not is really up to you.
I guess there are a few technical things which are easy to 'yae/nae', but with caveats:

Are you singing in tune ? You can probably decide this for yourself but a second/third opinion might be worth a try just to check you're evaluating yourself well. The caveat is that singing in tune doesn't make you a great singer, and many great singers bend notes or even miss them, and it seems to just add to the character.
Vocal range : Can you hit the notes that you want to, convincingly ? Caveat:  What's 'convincingly'? eg high notes.. maybe you use falsetta meaning it sounds operatic - fine if that's what you're after, not good if you want Sammy Hagar style vocals.
Tonal quality of your voice - operatic?  rock screaming ? punky sneer ? hard rap shoutiness? Bluesy smoothness ? Maybe you can get several characters from your voice.. Caveat : What's a great tonal quality? Totally subjective !
Lasty.. mojo. Almost undefinable, but I know some vocalists who sing in tune, have a great range and nice tonal quality but somehow still sound like an estate agent singing in the car. That's where you're really stuck with "benchmarking". I'm not sure anyone's really analysed that and nailed it. This question & answer might help though :How to sing with Energy

I'd say your best bet would be to record yourself singing something that you think you're singing well, and get a few opinions- maybe 4 or 5 different people, whose opinion you respect (by which I mean you know they'll be honest) - they don't have to be experts though as music generally appeals to loads of sections of society, but maybe someone who you know has a musical ear, even if they don't play/sing.

Be prepared for them saying "you're crap!" - it's part of inviting opinion. But if they do, ask them to define how.
Be prepared for them saying "that's absolutely brilliant!" - cos you might be :-)
Comment: Hi-thats a toughie! about all I can think of is examples: There's that crack in your voice which may be desirable. eg Beyonce has a very clean voice whcih almost never 'breaks' into a rasp, as opposed to Pink who is right on the edge of her voice getting 'furry'. Then there's Tom Waites who sounds like he's recovering from 'flu lol (but it's ace). Also the richness of the voice - Sting and Jon Anderton (sp?) from Yes have a thin kind of high pitched voice as opposed to Nat King Cole whose voice (that tune 'there may be trouble ahead') is so creamy & full it makes you want strawberries with it.
Comment: Very nice! Can you elaborate a little about tonal quality? How do I measure it? Don't need to be something scientific haha thanks a lot!
Comment: Regards measuring that: A thinner voice will poke through loud music more easily, whereas a rich full voice might need extra room in the range for it to fill. Eg ACDC 's Bon Scott (v high) prods nicely over the loud harsh guitars, but Michael Buble might struggle unless you turned his vocals up LOUD, in whcih case they could drench the whole sound. And no-one drenches Angus hehee :-D
Comment: Great comments!
Answer: Obviously being able to hit the right note is key, but you won't need to look at a spectrum analyser for that.
Timbre us a much more complex question. There are successful singers with many different types of voice, so again, looking at the spectrum is unlikely to help you.
You are best served by visiting a voice coach and getting them to instruct you on any weaknesses.

Singer "benchmarking"


Virtual Memory and sbrk

Question: On a 32 bit Linux system, a process can access up to 4 GB of virtual address space; however, processes seem to be conservative in varying degrees in reserving any of that. So a program that uses malloc will occasionally grow its data segment by a syscall sbrk/brk. Even those pages aren't claimed in physical memory yet. What I don't fully understand is why we need to sbrk in the first place, why not just give me 4 GB address space avoiding any sbrk call, as until we touch/claim those blocks, it is essentially a free operation right?
Answer: What happens if you memory-map a file (a very common thing to do under Linux)? It has to go somewhere in the address space, so there must be some means of defining "used" and "not used" parts.
Shared memory (which is really just mapping a file without an actual file) is the same. It has to go somewhere, and the OS must be sure it can place it without overwriting something.
Also, it is preferrable to maintain locality of reference for obvious (and less obvious) efficiency reasons. If you were allowed to just write to and read from any location in your address space, you can bet that some people would do just that.
Comment: "Shared memory (which is really just mapping a file without an actual file) is the same. It has to go somewhere, and the OS must be sure it can place it without overwriting something." I see what you're saying (I think), as malloc calls mmap (with anonymous and private) I believe and that may or may not call sbrk, but if on program init malloc has done brk(4gb) it removes the syscall to sbrk etc..  But you can not longer map additional memory map files or create shared memory with different flags. Right... I think I am starting to understand
Comment: "Also, it is preferrable to maintain locality of reference for obvious (and less obvious) efficiency reasons" But if I take some memory from say 1gb into 4gb block and say 3.9gb into the 4gb block, it probably will be close in physical memory once that fresh allocation is seg faulted in (just zeroing out right)?
Comment: It might, it might not. You cannot know.
Answer: There's a couple of reasons that come to mind:

You'd no longer get segfaults when accessing unmapped memory
The Translation lookaside buffer (TLB) would be larger, possibly requiring more time to set it up
You'd have to unmap some of that memory anyway if you load in a new shared library or mmap() something

Virtual Memory and sbrk


Missing formatter options for field from a custom table defined in hook_views_data()

Question: I integrated a custom database table to views using hook_views_data().
$data['custom_watchdog']['message'] = [
    'title' => 'Message',
    'help' => 'Full log message.',
    'field' => [
        'id' => 'standard',
    ],
    'filter' => [
        'id' => 'string',
    ],
];

It works, as I can display values in a view, but it misses a formatter option.
For example, the Taxonomy term: Description field has formatter options which allows to select Default or Trimmed.
Why isn't it available for my custom field?
Answer: You are comparing a standard Views field with an entity field. Only entity fields have field formatters. Create a custom entity instead of a custom table if you want to use this feature. For a standard field you have to use the options provided by Views. There is a trim option as well, but it is named differently, trim in the alter section. You see it in Views UI. Try to configure it and check the exported View.
Comment: Thank you @4k4 for explanation. Trim was just an example, I was building custom FieldFormatter.
At the end I used hook_preprocess_views_view_field() to modify output of the view field.


proving $J=\int_{0}^{1}\frac{\cos x}{\sqrt{x}}dx<2$

Question: If $\displaystyle I = \int_{0}^{1}\frac{\sin x}{\sqrt{x}}dx$ and $\displaystyle J=\int_{0}^{1}\frac{\cos x}{\sqrt{x}}dx$. Then prove that $\displaystyle I<\frac{2}{3}$ and $\displaystyle J<2$
$\bf{My\; Try::}$ Using $\displaystyle \sin x <x\;\forall x\in \left(0,\frac{\pi}{2}\right)$
So $\displaystyle \sin x<x\Rightarrow \frac{\sin x}{\sqrt{x}}<\frac{x}{\sqrt{x}}=\sqrt{x}$
So $\displaystyle I = \int_{0}^{1}\frac{\sin x}{\sqrt{x}}dx <\int_{0}^{1}\sqrt{x}dx = \frac{2}{3}$
So $\displaystyle I <\frac{2}{3}$
But I did not understand how can i prove $\displaystyle J = \int_{0}^{1}\frac{\cos x}{\sqrt{x}}dx <2$?
Comment: Are you sure? http://www.wolframalpha.com/input/?i=%5Cint_0%5E1%5Ccos%7Bx%7D%2F%5Csqrt+%7Bx%7D
Comment: Thanks  Joseph Curwen , I have edited it,
Answer: $\displaystyle J = \int_{0}^{1}\frac{\cos x}{\sqrt{x}}dx$
Since $ cos x < 1 $ for x = 0+  to 1
Now divide both side by $\sqrt x$ and    Integrate both side than
You will get J < 2
Answer: Integrate $\displaystyle J=\int_{0}^{1} \frac{\cos(x)}{\sqrt{x}} \, dx$ by parts. It gives :
$$
\begin{align*}
J &= \left[ 2\sqrt{x}\cos(x) \right]_{0}^{1} + \int_{0}^{1} 2\sqrt{x}\sin(x) \, dx \\
&= 2 \Big( \cos(1) + \int_{0}^{1} \sqrt{x}\sin(x) \, dx \Big) \\
\end{align*}
$$
On $]0,1[$, $0 < \sqrt{x} < 1$ and $\sin(x) > 0$. So, $\displaystyle \int_{0}^{1} \sqrt{x}\sin(x) \, dx < \int_{0}^{1} \sin(x) \, dx = - \cos(1)+1$. It proves that
$$ \cos(1) + \int_{0}^{1} \sqrt{x}\sin(x) \, dx < 1 $$
As a consequence, $J < 2$.


"Orthogonal" or "mutually exclusive" coloring for a plot

Question: I have a bar graph where the bars are colored according to chemical composition: Say atoms A, B, and C are interesting. I am currently mapping (A,B,C) composition, normalized, to (R,G,B) color as way to color each bar on the graph. Unfortunately, I have found that this leads to a rather ugly result, as most compounds fall at the extremes of the scale. I am looking for an alternative to the RGB mapping. I considered rotating in hue, but this leads to only limited possibilities, and none of them so far look very nice.
Is there a good way to choose three colors that look "different enough" to be used this way? Colorblind-friendly is a bonus.
Comment: The website colorbrewer2.org is intriguing and invaluable.
Comment: You may have to resort to picking individual colors that make intuitive sense. In "additive" RGB system (as on screen or in theater lighting) R + G = Yellow. which is counterintuitive. Also, R+G+B = White. (Rest is OK intuitively, G + B = Cyan, R + B = Magenta.)  None of this is as in elementary school art class (mixing colors). Or as in color printing, a "subtractive" system based on Yellow, Magenta, Cyan ink subtracting from white of paper below. // In R, you might investigate `hsv` or color pallets instead of `rgb`. (But in `hsv`,  R at one  end and Magenta at other look almost the same.
Answer: This Lancet paper using a 3-value coloring scheme based on CMY that might fit your needs. That is, it has distinct colors at the extremities and a paint-like blending logic for in-between colors. The graphic had a positive reception in the dataviz community, which is an indicator it also meets the "looks nice" objective.
(Possibly you meant something entirely different -- in which case, please elaborate your question.)
Comment: Can you add some text to this to explicate your answer?


Are the same node paths a problem?

Question: I created a website with Drupal 8 in 4 languages. When I access a node in the default (English) language, I get to a page with a path of e.g. localhost/contact, just as it should be. Now, when I switch to Japanese, I would expect it to be localhost/jp/contact, but it is localhost/jp/node/13 (the page does display though). Both nodes have the same path listed (/contact) when I inspect them in the administration area.
For the record, my language detection methods are set in this order, in case it matters:

Account administration pages
URL (note: URL path prefixes are configured)
Session
User
Browser
Selected language

How can I achieve the expected state I mentioned above? That is, having the same (relative) paths set for each language variant of a node, while the language part of the URL would ensure displaying the proper language version of the node and while the URL would be human-readable and not just the node ID?
Answer: You either need to make your aliases not language specific (you can only do that in the alias administration page right now, not in the node edit form) or you need to create one for each language.
If the alias shows up for all languages, make sure you made the path field translatable in the content translation settings, maybe something doesn't work correctly otherwise.
See https://www.drupal.org/node/2775275 for an issue to allow language-unspecific aliases. You could also use tokens to get the original language with pathauto to work around it.
Comment: I thought that if I would be able to do this, if the paths could stay the same regardless the language, all the links on the website could also be the same regardless the language. Pitty, that would make administration somewhat easier in our environment. I'll try to manually adjust the paths, since they are configured to be translatable.

Are the same node paths a problem?


Moving for divisors inducing the same map on homology

Question: Let $X$ be a complex projective variety and let $H$ be a hypersurface section of $X$ which contains all singular points. By Lefschetz hyperplane theorem the inclusion of $H$ in $X$ induces isomorphism on $i$-th homology, for some fixed value of $i$ that is small enough (less than the dimension of $H$). Let $p$ be a singular point which is also on $H$.
We define an equivalence relation on subvarieties of $X$. We say $D\sim D'$ if $D\hookrightarrow X$ and $D' \hookrightarrow X$ induce maps on the $i$-homology such that their image are same in $H_i(X)$.

Is it possible to find an equivalent to $H$ like $H'$ such that $p$ is not on $H'$?

How about if enlarge the point $p$ and instead we consider some small enough dimensional closed subset that we want $H'$ (equivalence to $H$) to cut this subset in closed subset of codimension 1?

If the answers are positive how about we replace the projectivity condition with quasi-projectivity and the homology by Borel-Moore homology?
Answer: Suppose the variety is a surface a single orbifold point and $c_1.H $ is a non-integer rational number (This does happen, for example I think there are log del Pezzo's with $c_1^2$ non-integer). Then one cannot move it off the singular points since this would imply the above intersection number is an integer.
Comment: Thanks you fir your comment. I think by moving you are assuming some form of adequate equivalence like rational equivalence, but I mean very loosely. I will edit the problem to reflect this,
Comment: It also provides a counter example to this looser form of equivalence. This product $c_1.H$ is an honest cup product in the singular cohomology ring of the orbifold.  In fact it shows that any singular cycle in the homology class of $H$ has to pass through the orbifold point., so it is not really about subvarieties.


How do I improve the clarity of my voice?

Question: I am totally unhappy with my voice. In my opinion, my voice sounds like Kermit the Frog. I have practiced using a stick between my teeth, but this only helps with articulation.
Is it possible to train my voice to improve its tone and clarity?
Comment: Have you looked into [modifying your diet to affect](http://voicestudio.kristinaseleshanko.com/ThingsThatAffectYourVoice.htm) your voice?
Comment: A lot can be done to change the quality of your voice, both in good and bad ways, but it's nigh impossible for people who can't see and hear you sing in real time to help you with that, and it takes a lot of knowledge and experience to know what to look and listen for and what to change to make things better. Basically, your best option is to hire a teacher. Anything else is a shot in the dark and you might make your voice worse.
Answer: Go get some classes on singing... Talent is really a small part of it, and most of the rest you can learn. It can be harder or easier, but you can probably have a richer sound if you study with someone who knows what they're doing.
If you can't afford a teacher, there are tons of videos on the internet about breath support and intonation, that can help you a long way, but I strongly recommend you find help, as you can damage your voice if you do something wrong...


Why is my Cronbach's $\alpha$ negative

Question: I'm just learning about Cronbach's $\alpha$. I have recently tried to carry out this test. Having 80 completed questionnaires with 15 questions (variables), the questionnaire used the Likert scale 1-5 (1 strongly agree)
I have filled the data in, however I've ended up with a negative result! What might I have done wrong?
Comment: Names for your papers/talks: Cronbach [not Cronback], Likert [not likert] (edited accordingly). I guess that some scales need to be reversed. For example, "I strongly agree that SPSS is a good program" and "I strongly agree that R is a good program" might align negatively. I don't use SPSS but there should be syntax or menu choice to allow reversal. If not, use a different program. If this doesn't help, you may need to tell us more. Looking at correlations between variables might help you see patterns. Be circumspect about dumping variables into any routine without thinking what they are.
Comment: I think it's going to be hard to say. Can you tell us more about your situation, your data & your analysis?
Answer: Recall how cronbachs-alpha is calculated: assuming that a total test score $X$ is a sum of scores on $K$ separate items, $X=Y_1+\dots+Y_K$, then
$$\alpha:=\frac{K}{K-1}\left(1-\frac{1}{\sigma_X^2}\sum_{i=1}^K\sigma_{Y_i}^2\right),$$
where $\sigma_{Y_i}^2$ and $\sigma_X^2$ denote the variance of the $i$-th item and the total score, respectively.
In theory, $0\leq\alpha\leq 1$. In practice, you will substitute estimates of $\sigma_{Y_i}^2$ and $\sigma_X^2$, and you can definitely end up with negative values.
Now, this means that your items quite definitely do not measure the same underlying construct. Nick Cox already gave some very good points: you may need to reverse the coding of some items, or something similar. It would be good if you went and thought very critically about the wording of your items and try to make connections between them. It's probably indeed best to start by looking at correlations between items.

Why is my Cronbach's $\alpha$ negative


O que é o JSONP e como funciona?

Question: O que é JSONP, como se usa e porque usar JSONP em vez de AJAX?
Comment: @mgibsonbr fui ver agora ao dicionário e `vêz` é mesmo erro ortográfico. O `por que` e `porque` é diferença pt-BR e pt-PT.
Comment: As correções de ortografia do @GabrielSantos são correções mesmo, ou se trata de diferenças entre pt-PT e pt-BR? Fiquei na dúvida, pois no Brasil usamos "por que" ao fazer uma pergunta e "porque" ao responder, e não existe "vêz" ("vês" com "s" acento se refere ao verbo "ver"), mas não sei como é em Portugal.
Answer: JSONP (JSON com padding) é uma técnica destinada a contornar uma limitação do uso de Ajax nos browsers: o fato de que a Política de Mesma Origem não permite que o domínio A faça uma requisição Ajax pro domínio B. Antes do CORS ("compartilhamento de recursos de origem cruzada") ser proposto - e suportado pelos principais browsers - não havia um meio fácil e seguro de se contornar essa limitação, e mesmo nos dias de hoje o suporte a essa técnica é relativamente raro.
Dada essa limitação, concebeu-se uma maneira de contorná-la aproveitando-se do fato de que a tag script é uma das poucas que está isenta da Política de Mesma Origem (e assim permanece por razões históricas, apesar do impacto negativo que isso tem na segurança da web em geral). Ora, se o interesse principal do Ajax é dar acesso programático a um determinado conteúdo, e um site pode incluir scripts de outro site sem nenhuma restrição, então por que não enviar esse conteúdo na forma de um script? Como todo JavaScript na página possui o mesmo contexto de execução (não importando sua origem), o código vindo do site B pode chamar funções definidas pelo site A, usando essas funções para comunicar o conteúdo consultado.
Uma descrição detalhada da técnica, com exemplos, pode ser vista na resposta do Sergio. Quanto a por que usar, é necessário se observar alguns pontos:

O nome JSONP é inapropriado, pois embora os dados retornados sejam referidos como "JSON" na realidade são apenas literais para objetos JavaScript, e não strings (texto), que costumam ser incluídos no script. E de todo modo, o "combinado" é que o retorno seja apenas o objeto (o "JSON") dentro de uma chamada de função (o "padding"), tipo:

Mas se o site quiser "fugir do combinado" - por exemplo usando algum outro código que construa esse objeto e repasse-o à função indicada como callback - nada o impede de fazer isso. E isso é relevante porque...
Um script em uma página é um código arbitrário executando no computador do usuário; e mais, todo script tem acesso irrestrito não só ao DOM mas também ao contexto de execução (compartilhado pelos demais scripts) e também aos cookies (com exceção dos marcados como HttpOnly), histórico de navegação, armazenamento permanente (local storage, IndexedDB, etc) e até mesmo a capacidade de navegar o browser para outra página de sua escolha (dentro ou fora do site), dentre outras capacidades.
Por essa razão, a primeira pergunta a se fazer antes de usar JSONP é se você confia no domínio consultado, ou se é o seu domínio que oferecerá suporte a JSONP, como fazer com que os terceiros que irão consumir seu conteúdo confiem no seu site. Lembrando que não basta o conteúdo servido por esse domínio ser correto hoje, se no futuro ele tiver seu servidor comprometido, por exemplo, os usuários de todos os sites que consomem seu conteúdo por JSONP estarão vulneráveis a um ataque arbitrário e indeterminado.
Sendo assim, minha resposta a por que usar é simplesmente: só use se não tiver outro jeito...
A forma preferencial de se fazer requisições a domínios diferentes é mesmo o CORS. Dá um trabalhinho extra configurá-lo corretamente, e agentes de usuário mais antigos podem não dar suporte apropriado a essa técnica, mas à medida que o tempo passa esse problema se torna cada vez menor (tanto pela fração de usuários que utilizam browsers modernos, como pela evolução das plataformas no lado servidor no sentido de dar esse suporte e facilitar a configuração). Se for possível usar CORS, use.
Muitos sites não foram feitos pensando em compartilhar seu conteúdo através de uma API Ajax. O uso de JSONP exige suporte do servidor, não é algo que possa ser feito somente no lado consumidor da informação. De modo que se esse suporte não existe atualmente, temos duas opções principais:

Usar seu próprio domínio como proxy para o domínio externo; nesse caso não é necessário usar JSONP, CORS, nem nada de especial, pois o seu servidor consultará o domínio externo como se fosse um usuário pelo browser, e repassará ao usuário real via Ajax comum. Não é o ideal, dada a carga extra que isso coloca no seu servidor, mas em algumas circunstâncias pode ser a única opção.
Pedir ao domínio externo que atualize seu sistema para dar suporte a requisições Ajax de fora do seu domínio. Aí entra a seguinte questão: se uma funcionalidade nova está sendo implementada, pra quer usar a abordagem insegura quando é não só preferível mas também muito mais fácil (já que basta incluir alguns headers adicionas, sem mudança no código Ajax existente) simplesmente habilitar CORS? De novo, a menos que seja um requisito explícito do seu projeto dar suporte a browsers antigos, não há razão pra se usar JSONP.

Por fim, algumas coisas poderiam ser feitas para mitigar os riscos de se usar JSONP, mas nada 100% à prova de falhas, e de todo modo as soluções mais seguras demandariam suporte a recursos modernos de HTML5 de qualquer forma, e um browser que suporte esses recursos provavelmente também suportará CORS. Um exemplo (disclaimer: não estou sugerindo usar esse código na prática!) seria delegar a um iframe a tarefa de fazer a chamada JSONP, numa tentativa de isolar o código do restante da página:
teste_jsonp.html
function testeJSONP(url, callback) {
    var iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = "jsonp_seguro.html";
    iframe.sandbox = "allow-scripts"; // Proíbe tudo, exceto a execução de scripts
    iframe.onload = function() {
        // Se comunica com o iframe através de postMessage
        window.addEventListener("message", function(event) {
            callback(JSON.parse(event.data));
        }, false);
        iframe.contentWindow.postMessage(url, "*");
    };
    document.body.appendChild(iframe);
}

testeJSONP('http://ip.jsontest.com/?callback=showIP', function(dados) {
    console.log(dados);
});

jsonp_seguro.html
window.addEventListener("message", function(event) {
    window.showIP = function(dados) {
        // Repassa os dados recebidos para a página principal
        // (note que isso força esses dados a serem passados como string)
        event.source.postMessage(JSON.stringify(dados), "*");

        /**** E se o domínio for desonesto? E em vez de retornar um JSON: ****/

        // Tenta fazer várias coisas maliciosas
        try { var target = window.opener || top; target.location.href = "http://google.com"; } catch(e) { console.log(e); }
        try { var cookies = document.cookie; } catch(e) { console.log(e); }
        try { var teste = localStorage.getItem('teste'); } catch(e) { console.log(e); }

        // Essas ele ainda consegue... :(
        /*try { alert("SPAM!"); } catch(e) { console.log(e); }
        try { history.go(-1); } catch(e) { console.log(e); }*/
    };

    // Aqui é feita a chamada JSONP de fato; fonte: resposta do Sergio
    var script = document.createElement('script');
    script.src = event.data;
    document.body.appendChild(script);

}, false);

Exemplo (abra o console se quiser ver como as ações maliciosas foram bloqueadas).
Reiterando: não tente "emendar" medidas de segurança pra proteger o JSONP, só use essa técnica em conjunto com sites em que você confia.
Comment: Muito bom! ++ Bom teres referido mais a fundo a insegurança relacionada com o uso do JSONP
Comment: Erro de ssl no seu site. O certificado expirou!
Comment: @GabrielSantos Hehe [estou sabendo...](https://marcelogibson.com/blog/pt/) :P Por enquanto ando sem tempo pra atualizar esse site, e como é só um site pessoal mesmo sem nada muito importante eu estou empurrando com a barriga.
Answer: O JSONP é uma alternativa para enviar e receber dados em browsers antigos, e/ou sites que têm CORS desativado.
Se o browser estiver por exmeplo no dominio meusite.com e quisermos receber dados de outro dominio (por exemplo: teusite.net) muitos browsers vão dar erro (versões antigas do IE não conseguiam fazer chamadas AJAX para domínios diferentes). O erro pode ser porque o CORS está desativado, ou porque o browser é velhinho e não pode fazer pedidos a domínios diferentes. Sites com CORS desativado não permitem trocar dados via AJAX.
Mas há uma excepção nos browsers para ir buscar conteúdo a sites de outros domínios. As tags

O que é o JSONP e como funciona?


Pass current item reference to function

Question: In knockoutjs how do I pass the current item reference to a function?
I have a photo gallery that I'm looping over, when the user clicks the photo I want to check if photo the user is selecting has a specific class in the img tag.
Here is my current code which is not working.
my.Character = function () {
    var self = this;
    self.text = ko.observable();
    self.value = ko.observable();
    self.image = ko.observable();
    self.imageSrc= ko.computed(function () {
        return "/Images/" + self.image();
    }, this);
    self.selected = function ($data) {

        if ($data.hasClass('selected')) {
          // do stuff here
        };
};

The view

Comment: Can you add the view ?
Comment: Sorry Damien, been trying to edit my post, but it's not diplaying my update. Here's the view:
Comment:
Comment: You just forgot to surround the html with the "Sample code {}"
Answer: It's pretty simple to do  with the css binding:
I suppose you have a Characters array in the parent context which should look like this :
my.Parent = function(){
    var self = this;
    self.Characters = ko.observableArray();
    // stores the selected character
    self.selected = ko.observable();
    self.select = function (character) {
        if(self.selected() === character)
            self.selected(null);
        else
            self.selected(character);
     };
};

my.Character = function () {

    self.text = ko.observable();
    self.value = ko.observable();
    self.image = ko.observable();
    self.imageSrc= ko.computed(function () {
        return "/Images/" + self.image();
    }, this);
};

The view

Notice that KO will implicitly pass the bound viewmodel and the event when it calls the select function (click: $parent.select).
In others KO calls
$parent.select($data, clickEvent)

That's why I can write :
self.select = function (character) {};

Comment: Hi Damien, still not working quite right -- your code will apply/toggle the .selected class to the photo the user is clicking on, allowing a user to multi-select photos -- but I want just one photo to be selected at a time -- when the user clicks a photo the .selected class is applied, but also removed from all other photos in the gallery. Regards Melt
Comment: @Melt Down, if you want to have only one photo selected at the same time you need to store the selected character in the parent context.

Pass current item reference to function


How do i add all the values in my ascending array?

Question: First i need to re-arrange all the values of my array into ascending order then add it afterwards. For example the user input 9 2 6, it will display in ascending order first ( 2 6 9 ) before it will add the sum 2 8 17.. The problem is my ascending order is not working, is there something wrong in my code?
<code>#include <iostream>
#include<conio.h>
using namespace std;
int numberof_array, value[10], temp;
int i = 0, j;
void input()
{

    cout << "Enter number of array:";
    cin >> numberof_array;
    for (i = 0; i < numberof_array; i++)
    {
        cout << "Enter value for array [" << i + 1 << "] - ";
        cin >> value[i];
        cout << endl;

    }
}
void computation()
{

// this is where i'll put all the computation
    for (j = 0; j < numberof_array; j++)
    {
        cout << value[j];
    }
    for (i = 0; i <= numberof_array; i++)
    {
        for (j = 0; j <= numberof_array - i; j++)
        {
            if (value[j] > value[j + 1])
            {
                temp = value[j];
                value[j] = value[j + 1];
                value[j + 1] = temp;
            }
        }
    }

}
void display()
{
// display all the computation i've got
    cout << "\nData after sorting: ";
    for (j = 0; j < numberof_array; j++)
    {
        cout << value[j];
    }
    getch();
}
int main()
{
    input();
    computation();
    display();
}
</code>
Comment: why are you using C style arrays instead of `std::vector`? You could then stop sorting manually and just use`std::sort(values.begin(), values.end());`
Comment: The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger.
Comment: If does not produce the desired result, there obviously is something wrong with your code.
Comment: Besides, what's with all those globals, `` and the utterly useless function name `computation`? You need to find better learning material.
Answer: <code>   void computation(){
    for (int j = 0; j < numberof_array; j++)  cout << value[j]<<"\t";

    for (int i = 0; i <= numberof_array; i++) {
        temp = value[i];
        int temp_idx = i;
        for (int j = i; j < numberof_array; j++) {
            if (value[j] < temp) {
                temp = value[j];
                temp_idx = j;
            }
        }
        int temp_swap = value[i];
        value[i] = value[temp_idx];
        value[temp_idx] = temp_swap;
    }
  }
</code>
How about changing your second function to something like above.
I have to agree with other commentators that your coding style is not preferred but there might be more to the story than meets the eye.


Store persistent data on Services ( Angular 2 )

Question: First of all i would like to share the next info:
I have two services, one that gets the http request and another that store data. I tried a lot of ways but i can't get it. I wanna store data on the second service to get the data from differents components and dont DRY (on every component).
The specific problem: I get the http request from the API, then i want to store the json response (store on array or object) to get persistent data and get the info on every component. I will share what i tried, but it didnt work on the second service (artist.service.ts).
// spotify.service.ts

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Injectable()
export class SpotifyService {

  urlSpotify: string = 'https://api.spotify.com/v1/';
  token: string = 'BQDejsMxhS-8621YfIhK_X6uxZcFY4LIBTNNxVIDAPimiBBU5t7lQlQCUboZkt5JBypYq-IH4dv9bhxQgaU';

  constructor(public http: HttpClient) {
        console.log('SpotyApp Ready');
   }

   private getHeaders(): HttpHeaders {
     let headers = new HttpHeaders({
        'authorization': `Bearer ${ this.token }`
      });

     return headers;
   }

getArtista( id: string ) {
       let url = `${ this.urlSpotify }artists/${ id }`;

      let headers = this.getHeaders();

      return this.http.get(url, { headers});
   }

   // Methods

// artist.service.ts

import { Injectable } from '@angular/core';
import { SpotifyService } from './spotify.service';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class ArtistService {

artist: any = {};

constructor(private _spotify: SpotifyService, public route: ActivatedRoute) {}

 // It doesnt work....
 getArtista(id): Observable<any> {
    if (this.artist) {
        return Observable.of(this.artist);
    }
    return this._spotify.getArtista(id).do(artist => {
        console.log(artist, 'Artista');
        this.artist = artist;
    });
 }

  // It doesnt work...It works only on EVERY component.

getArtista(): void{
this.route.params.map(params => params['id'])
  .subscribe(id => {
    this._spotify.getArtista(id)
      .subscribe(artist => {
        console.log(artist, 'Artista');
            this.artist = artist;
      });

// artist.component.ts

import { Component, OnInit } from '@angular/core';
import { ArtistService } from '../../services/artist.service';

@Component({
  selector: 'app-artist',
  templateUrl: './artist.component.html'
})
export class ArtistComponent implements OnInit {

  artist: any = {};

  constructor(public _artist: ArtistService) {}

  ngOnInit() {
    this.artist = this._artist.getArtista();
  }
}

Comment: You have declarated artist as: artist: any **= {}**; and if (artist){ return Observable.of(this.artis). You MUST declare artist simply as artist:any or artist:any=null
Comment: What exactly is it that doesn't work? You enter a new page, a new API call is made and you get a result. Is your understanding that `this.artist` should contain information when you make second, third and more future function calls to the `ArtistService`?
Comment: @Eliseo is right. Your condition `if(this.artist)` will always return `true`.
Comment: The real problem is that i always get "undefined". So i want to know what im doing wrong.. I would like to get an observable to subscribe on the current component and get the artist, the album, etc...@DanielB Sorry , i dont get it when you say second, third, etc...So if i just make one function call, i wont get any data ???
Answer: It looks like you are trying to cache artists on the service to avoid repeated calls, but the cache should also have a map based on the id of the artist. Also a caching mechanism is never as easy as it seems when you think of cache getting dirty with other operations. It is highly recommended not to cache it if the network calls are not that expensive. Traditionally there is a trend towards minimising network calls, but I personally doesn't think some KBs will matter to the User.
Also, the use of ActivatedRoute is better suited in the corresponding component and keep the service limited to its purpose.
Also persistence makes no sense here. Its storing in volatile variables. Persistence should at least refer to local storage.
// artist.service.ts

import { Injectable } from '@angular/core';
import { SpotifyService } from './spotify.service';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class ArtistService {
artistsSources = {};
artists = {};
constructor(private _spotify: SpotifyService) {}

 getArtista(id): Observable<any> {
    if(this.artists[id]) {
        return this.artists[id];
    } else {
        this.artistsSources[id] = new BehaviorSubject(null);
        this.artists[id] = this.artistsSources[id].asObservable().filter(Boolean);

        this._spotify.getArtista(id).do(artist => this.artistsSources[id].next(artist));
    }
    return this.artists[id];
 }
}

// artist.component.ts

import { Component, OnInit } from '@angular/core';
import { ArtistService } from '../../services/artist.service';

@Component({
  selector: 'app-artist',
  templateUrl: './artist.component.html'
})
export class ArtistComponent implements OnInit {

  artist: Observable<any>;

  constructor(public _artist: ArtistService, private route: ActivatedRoute) {
    this.artist = this.route.params.map(params => params['id'])
        .switchMap(id =>  this._artist.getArtista(id))
        // you can optionally subscribe here and set this.artist as normal object
        // this example uses async pipe in template instead
        // if you subscribe, make sure you unsusbscribe in onDestry
  }

  ngOnInit() {
  }
}

//artist.component.html

{{(artist | async)?.name}}

Comment: Thnks for the answer but i want persisent data on a service just to not make repetition. I have artist component, album component, another component. With a service i store the data and a want to subscribe ( something like that ) on every component to get the current album,tracks, artist, etc...


Append a txt file in .Net

Question: I am Creating a txt file in.Net with the help of below code.
StreamWriter writerVer = new StreamWriter(@"c:\Version.txt");
writerVer.WriteLine("Version : " + Context.Parameters["ver"]);
File.SetAttributes(@"C:\Version.txt", FileAttributes.Hidden);

Then I need to Update the file on the next line by keeping the above code as it is.
This code overrites the entire file.
StreamWriter writer = new StreamWriter(@"c:\Version.txt");
writer.WriteLine("Connection string : "+con);

Regrads,
Sachin K
Answer: try this
 StreamWriter writerVer = new StreamWriter(@"c:\Version.txt", true);

There is an overload of the StreamWriter constructor that takes an additional bool parameter to indicate if you want to append or not.
Answer: Use the constructor which takes the append boolean parameter to indicate whether to append to the file - http://msdn.microsoft.com/en-us/library/36b035cb.aspx
StreamWriter writer = new StreamWriter("file.txt", true);

Answer: Alternatively, you could use the static helper methods: File.AppendAllText or File.AppendText.
Note that the latter actually returns a StreamWriter instance, so you'll need to close it before proceeding otherwise you're relying on the GC to do it for you.

Append a txt file in .Net


where to place active directory integrated DNS server and what type to use

Question: I am working at two branch offices and have been tasked with where to place active-directory integrated DNS severs and what type to use.
one of the branch offices is very small (5 users) and has very slow network connectivity. do I need a DNS server and, if so, what type of zone should it host?
the second branch office is much larger (about 30 users) and has a better network connectivity. does this office need a DNS Server and , if so, what type of zone Would you recommend?
Comment: Where are the resources that users need access to? Where to place the DC/DNS server is only part of the equation. It does the users no good to authenticate to a local DC with local DNS resolution if they don't have access to resources (shares, printers, Exchange, etc.).
Answer: Active Directory integrated zones must be hosted by Domain Controllers (DCs), and all Active Directory integrated zones are primary zones. Given this, we're really talking about where to place Domain Controllers servicing the additional role of DNS server.
Determining where to place DCs/DNS servers isn't always straight-forward. However, as a rule of thumb, I take the view that any branch location that's going to be utilize Active Directory services (authentication, file services, etc), benefits from having a local DC and domain-integrated DNS services.
You might already know much of this, so bear with me…
When deciding where to place DC/DNS Servers, keep the following things in mind:

Domain members rely heavily on DNS services to locate domain resources. For example, when a domain-joined computer boots, it queries domain Service Locator records (SRV) in DNS to locate a Domain Controller against which to authenticate. Without a local DNS instance, this process has to take place over a potentially slow site link. Of course, once a computer has located a Domain Controller, it will continue to authenticate against that server until it something forces the client to find another DC.
Over a slow link, the regular activities of authenticating against remote DCs, querying domain resources, and performing other standard DNS lookups can create a sluggish and somewhat irksome user experience. A local DC/DNS server can greatly improve the user experience (I'm all about user experience) by eliminating delays.
If the link between sites goes down and there is no local DNS service, your users won't be able to browse the Internet unless you've configured secondary DNS servers. The problem I've had with secondary DNS servers is that each query first attempts to contact the primary DNS server before attempting the secondary DNS server. This really wrecks the user experience.

For a small branch office with 5 users and a slow link, you might be able to get away without a local DC/DNS server as long as:

Users aren't dependent on the ability to authenticate against the domain (if a remote DC isn't available to service authentication requests, users should still be able to log on to their local systems using cached credentials).
Non-domain DNS servers are available to service queries in the event your site link goes down. Some DNS-enabled routers can selectively forward requests for select domains to specific DNS servers. For example, normal DNS queries can be forwarded to publicly available DNS servers (such as the DNS servers provided by your ISP), while queries to mydomain.local can be forwarded over a secure site link to your internal DNS server. This method eliminates the delay of failing over from a primary to secondary DNS servers per client.

That said, I think you would still be better off with a local DC/DNS server even though you only have 5 users. Have you looked into Read Only Domain Controllers?
For your larger branch office, I would definitely recommend provision the site a local DC/DNS server.


Repeated calls to SharedPreferences apply() causes OutOfMemoryError

Question: I am using a Firebase onChildAdded listener to store certain pieces of data persistently in my Android app. When the app starts, this might fire thousands of times. Each time this fires, I am using SharedPreferences apply to write a simple key / value pair. The keys and values themselves aren't very large, but there might be a few thousand stored in SharedPreferences.
I was excited about using apply because it does some magic around caching in-memory and delaying the actual SharedPreferences XML write. However, I am finding that if I call apply 1,000-2,000 times within a few seconds, I get an OutOfMemory error.
Internally, SharedPreferencesImpl seems to be creating a new Map based off the old Map if writes to the actual XML are still queued. However, this is causing what seems to be a few thousand Map entries on the Java heap (I believe), and I'm getting an OutOfMemory error.
Maybe I should call commit every 50 or so times I call apply - this way I won't run into OutOfMemory errors, although I may see a small performance hit? What should I do? That seems kind of hacky anyway.
Comment: shared preferences are not meant to store such large data's. You should opt for sql database instead
Comment: I find it hard to believe SharedPreferences can't store a few thousand key / value pairs, where each key and value is just a few characters (50 at most).
Comment: Yes but that's the problem with your code
Answer: The solution for me was to use a Firebase single event listener on the location, put my thousands of items, THEN call apply(). You also have to keep track of the keys you've seen already (a HashSet of Strings).
Then, make a ChildEventListener, and just ignore the onChildAdded if the key exists in my HashSet.


How to pull out backend code from an Azure function into a sub repository while keeping git history?

Question: I have an Azure function project within a GitHub repository (AnkiSentenceCardBuilder being the Azure function project) and I want to pull the backend code out into a new sub repository, so I can reuse it with other presentation layers, such as a WinForm.
In order to keep the Git history, I planned on updating the current repository to add a Class Library project, move all the backend code into that new project, clone the repository, and delete the Azure function project.
My issue with that is after creating the Class Library project, I get the error Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]. I'm assuming this is because the Azure function is trying to treat the Class Library as an Azure function. Since it's not suppose to be an Azure function, I can't fix this by calling func init on the new project, as that converts my Class Library into an Azure function.
How would I go about doing this?
For extra context, I'm pretty new to both Git and Azure and am working on this within VS with C#.
Comment: On the new project, if you remove the newly added class you can then successfuly call func init?
Comment: @ojonasplima I can remove the Class Library project and the program will work again, if that's what you mean. Unless you mean call `func init` on the main Azure function project in order for it to not show that error when I re-add the Class Library project?
Answer:
In Visual Studio, include a new Class Library project within your solution. I have named it YourbackendLibrary.

My repository structure:-

Command to create new class library:-
dotnet new classlib -n YourLibraryName

Output:-

Transfer the backend code with all the classes and utilities from the AnkiSentenceCardBuilder project to the recently added Class Library project.

Verify that the Class Library project is correctly configured as a Class Library, ensuring it targets the appropriate framework and output type.

Eliminate any references or dependencies associated with Azure Functions from the Class Library project.

If your Function code is part of Services folder, make sure you move all the classes and utilities with Function code to the newly created class library and then refactor your code with all the required dependencies.

After moving and verifying the code, commit changes to the Git repository to maintain history. Clone the repository elsewhere to replicate the updated structure without the Azure Function project. Clean up by deleting the Azure Function project from the original repository and commit this change. Ensure to update references if reusing the Class Library, such as adding it to your WinForms project.


Confirmation that I've interpreted theorem involving Dedekind cuts correctly

Question: This theorem below is from the section on Dedekind cuts in "Princples of Mathematical Analysis" by Rudin.

Let $\alpha$ be a cut, and let $r>0$ be a given rational.  Then there are rationals $p$, $q$ such that  $p\in\alpha$, $q\notin\alpha$, $q$ is not that smallest upper number of $\alpha$ and $q-p=r$.

Firstly, I would like to know if I am correct in interpreting this theorem as basically saying that we can express any positive rational as the difference of two rationals where one is in a cut while the other isn't?  Secondly, I also believe that the restriction that $q$ not be the smallest upper number is necessary because it allows us the freedom to choose very large values of $q$ in the event that $r$ is also large.
Thanks in advance
Comment: What edition are you using? I am looking at Edition 3 and can't find the theorem.
Comment: Doesn't explicitly say which edition it is, but I'm pretty sure it's the first edition.  It's theorem 1.15; it follows the proof of the commutative and associative laws for cuts
Answer: I would say you're correct in the basic interpretation, but here's how I would phrase it: Given any rational distance, there are rational points on either side of the cut which are exactly that close together. The reason I'd phrase it in terms of "closeness" is because, usually, when a theorem talks about "any positive rational" or "any positive real", it's really talking about "any positive rational no matter how small" - the idea is that big numbers aren't as interesting or difficult to satisfy as small numbers.
As for the part about $q$ not being the smallest upper number of $\alpha$: this isn't necessary, it's just useful. The theorem would still be true if you dropped that condition, because the condition is part of the conclusion. It means that the statement about "closeness" isn't just talking about the bottom half of the cut, it's talking about both halves. If we allowed $q$ to be that smallest upper number, then all the theorem would be saying is that the bottom half of the cut "squeezes close" to $q$; in principle, the upper half could be very spread out.
But the best way to get a feel for a theorem is to look at how it's used. I think you'll find that the theorem is used more for small values of $r$ than for large; it will also probably be useful that $p$ and $q$ are strictly on different sides of the cut (with neither of them falling exactly in the middle).
Answer: From my understanding of cuts, I can only tell you my intuitive feel for the theorem. Rudin is saying that for any given cut, we can 'squeeze into' it from both the left and right with rational numbers. You never want the rational numbers to be 'equal' to the cut, since he is saying that you can approximate the cut from either the left or right with rational numbers. So $r$ is like $\varepsilon$ - it is only 'interesting' for small 'challenging' numbers.
Also, in general cuts do not have a smallest upper number, so I am not sure where you are going with the 'secondly' part of your question.
Read ahead to see how this theorem is used. I would bet you are analyzing a fixed cut, and then since you can take $r$ to be arbitrarily small, that ______ is TRUE.
Answer: I spent a fair amount of time on this theorem on my first go around of Rudin's book. Yes, it shows up in the 1st and 2nd edition of his book but not the 3rd. It is not intuitive...
Theorem 1.15 states that for any rational $p$ defined within the cut, there exists a corresponding rational $q$ not within the cut such that the distance between the two is $r$, and $q$ is not the smallest upper number.
Well, what does this mean?
What this means is there will always exist some rational $p$ and $q$ such that their relationship is defined by $p+r=q$, and where $q$ is not the smallest upper number of the cut. This is a proof about EXISTENCE, nothing more. And I think that is the part that is difficult to see.
The way he goes about proving it is he creates a sequence of numbers $s_n$ for all integers $0,1,2,...$ and says that if $s_m$ is within the cut and $s_{m+1}$ is not within the cut, and $s_{m+1}$ is NOT the smallest upper number, then we are done. If it is the smallest upper number, simply increase $s_{m}$ and $s_{m+1}$ by $\frac{r}{2}$ (this is clear since if $s_{m+1}$ is indeed the smallest upper number, then we can do this by how we defined $p+r=q$.)
That's all this theorem and proof is. It's proof of existence.
It is easy to overthink this theorem because of the "smallest upper number" component. But this is an important aspect of proving Theorem 1.16.


Alternative to Google Adsense content injector module

Question: I want to "float" ads in the top right of my nodes for which Content Injector was nice enough in D6 moreover such ads convert well in my experience.
But for D7 is there any easy alternative? I know I can sub-theme and place the ads in appropriate positions.
Answer: It might not be quite as versatile, but the Block Inject module will allow you to embed adsense blocks within the node body.
Comment: It's in Alpha .. and too few sites using it. Wouldn't it be risky for production sites?
Comment: Test it, take over maintenance of Content InjectorOr or write your own. The choices are simple.
Answer: Without a module, just type adsense1, adsense2 anywhere in content.
(it's ok for any CMS: Drupal 7, WordPress, Joomla etc.)
First, create two or many scripts in your protected /inludes folder, with lines provides by Google Adsense (or somebody else).
adsense1.inc
adsense2.inc
...
adsense99.inc
// remember: just maximum 3 adsense blocks in a webpage
// I've filtered any Flash movies
Second, edit /themes/$your_theme/page.tpl.php. Write this code replacing line
print render($page['content']);
with
if(strstr(render($page['content']),'adsense1') or strstr(render($page['content']),'adsense2')){
$pContent=explode('adsense1',render($page['content']));
$pgContent= explode('adsense2',$pContent[0]);
print $pgContent[0];
if(strstr($pContent[0],'adsense2')) include('includes/adsense2.inc');
print $pgContent[1];
if(strstr(render($page['content']),'adsense1')) include('includes/adsense1.inc');
print $pContent[1];
}else{
print render($page['content']);
}
Third, refresh portal performance.
Enjoy!
P.S. www.astralia.ro
Answer: Honestly the easiest way to do ad's in Drupal 7 is with blocks. Then style your block. This is a tutorial on how to install google adsense VIA a simple block. It takes less then 3 minutes and takes no code skills. This is much simpler then adsense module or content injector module. Hope this helps you. My drupal username is alex_drupal_dev I made the video.  http://youtu.be/Ti6eApzJIrY


Problemas ao exportar app do creator para WWW

Question: Galera estou fazendo o layout do meu app pelo creator, e tento exportar as telas para o app que fiz pela linha de comando para o WWW, porém ele executa sempre o projeto da linha de comando(seja blank, tabs ou qualquer outro) e não executa o que eu colei, alguém já passou por isso?
Comment: Não entendi direito.... O que você está digitando?
Answer: Temos poucas informações. Partes do código ou do que você está digitando no CLI ajudariam bastante.
De qualquer modo, tente fazer o download do template que está no creator e depois a criação de um novo app com os comandos:
<code>ionic start <nome-do-app> <caminho-para-o-folder-local-do-template-baixado>
</code>
Isso criará um novo app baseado no template q você criou no creator.
Comment: Estou passando pelo mesmo problema que o colega acima, ele executou o comando por exemplo ionic start myApp tabs e fez o import do ionic creator pra dentro da pasta www porém ao executar o ionic serve o template roda o tabs e não o que está dentro do www


Notation: How to notate a note at the start of the first bar that is only played during the first repeat?

Question: I have read this answer, which relates to a different problem.
I want to know how to include a note to be played at the start of my first bar (ie: within the bar, not prior to it), but only during the first repeat, not the initial play-through.
The first play-through commences with an eighth rest. On the first repeat I want to put an octave chord in place of that rest. Is there some kind of bracket notation that is used in such a circumstance?
Any advice which includes how to do this in Noteflight would be even more greatly appreciated.
Answer: The classic solution would be to begin the repeat with the second measure and, if necessary, use first- and second-ending markings at the end of the repeated section, where the first ending contains the measure in question including the desired octave chord.
Another possibility is just to write "second time only" or "omit first time" over the octave chord, perhaps placing parentheses or square brackets around it.
I'd probably go with the first option because there's less room for ambiguity.
An example may be found in the fourth movement of Beethoven's fifth symphony.  Some recordings omit the repeats, but here's one that doesn't:

I'm afraid this question is my first exposure to Noteflight, so unfortunately I can't give you any specific help with that, but multiple endings at the end of repeated sections are such a standard feature of notation that it ought to support them.  If you're having trouble finding the feature, look for the Italian term volta, meaning "time" (as in "instance of repetition").
Comment: I just tried it with Noteflight, and it works during playback. I used your first recommendation. Thanks very much for the quick and accurate response.


Promise async/await que não se resolve

Question: Estou fazendo .map() em um array, para fazer uma query Mongoose/MongoDB com cada elemento desse array e retorna um outro array com os resultados.
Porém, após esse processo, eu tento acessar o novo array com console.log(novoArray) e o que imprime é [object Promise], e eu queria os resultados das queries que deveriam estar nesse array.
OBS: As queries deram certo (testei com 1): cada uma é salva na variável value. Vejam abaixo:
async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await valores.map(async valor => {
            const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}})
            let value = await query.exec()  //Tudo certo aqui
            return value
        })

        console.log('resultado '+documentos) //Imprime "resultado [object Promise]"

    }

Resumo da história, eu quero usar o array documentos cujo conteúdo deve ser os resultados das queries.
Estou há horas nisso, não sei mais o que tentar. Obrigado!
Answer: Promise dentro de um map precisam se resolvidas com Promise.all()
Você usou await fora do map pra fazer todas as queries.
No caso teria que envolver toda a as queries do map dentro de um promise.all.
Comment: Poderia dar um exemplo? Acho que sua explicação não ficou clara para alguém que não está muito familiarizado com promises.
Comment: Um instante pessoal, vou testar.
Comment: @RodrigoAzevedo Poderia me mostrar?
Comment: @RodrigoAzevedo Mas cada query estava sendo feita dentro map em   let value = await query.exec(), então eu tiro esse trecho? Eu simplesmente dou return query dentro do map?
Comment: @RodrigoAzevedo  como ficaria o await? É que eu quero usar a solução das promises ainda dentro dessa função, pra poder retornar esses valores pra fora dela
Answer: O problema aqui é que você está retornando objetos do tipo promise para o método map.
Entenda que apesar de você estar declarando a função de callback como async, o método map não está preparado para esperar pela resolução de promises, logo ele irá continuar iterando sobre os outros itens do array antes mesmo da resolução do seu await.
Um método nativo do JavaScript para esperar pela resolução de todas as promises de um array é o Promise.all (como já mencionado).
Após gerar o seu array de promises...
var documentos = valores.map(valor => {
    const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}})
    return query.exec() // não precisa utilizar await aqui, não terá nenhum efeito prático
})

Você pode aguardar a resolução com o método
var resultados = await Promise.all(documentos)
console.log(resultados)

Porém para o seu exemplo, eu imagino que seria mais eficiente criar um array de expressões regulares e então fazer apenas uma chamada para o banco de dados:
var valores = valor.split(' ')
var expressoes = valores.map(val => new RegExp(`.*${valor}.*`, 'i'))
var query = model.find({ url: { $in: expressoes } })
var documentos = await query.exec()

Comment: Entendi. Obrigado! Nem todo herói usa capa kkk
Comment: @Lucas, fiz uma revisão na resposta, considere utilizar ela.

Promise async/await que não se resolve


Is there a way to make aliases as short as possible?

Question: For instance, if you have three tokens, let's say [city], [state], and [country]
is there a way to do this:
/[city]-[state]-[country]
and then let's say there are three cities, Venice, in different places
the first, Venice, Florida, United States would get this url
/venice
the second, Venice, California, United States would get this url
/venice-california
the third, Venice, Italy would get this url:
/venice-italy
Notice that it does not cut an individual token, only cuts off the extra tokens as they are not needed (in the case of Italy, there is no state so pauthauto automatically skips this token).
From reading the documention, it looks like Pathauto's default behavior is to do this:
/venice
/venice-1
/venice-2
and so on... when what I want to do is make the first one the "venice" and any additinal ones get additial tokens as needed, so if Venice, Italy is first then they will get /venice
If there's a way to do this with pathauto, how would you do it?
If not, what's the best way to make a module that does this?
Can a module modify how pauthauto works without modifying pathauto itself?
thanks!
Answer: hook_pathauto_alias_alter() is nearest to your query.
First parameter $alias will be newly created alias by the Pathauto module. You would have to analyze it with some regex pattern for undesired pattern generation.
The second parameter will give you contextual picture of item in associated array.
module definitely be taxonomy_term
source system path of taxonomy e.g. taxonomy/term/<tid>
I think you will have pretty much to analyze the term and get its hierarchical info to update $alias variable.
Answer: What about path_save() called X number of times with whatever tokens you want in the URL fragment?
What you're asking isn't really a Pathauto question I think, as the uniqueness you describe is pretty subjective.
You could keep a one-to-many database table of node IDs for the allowed aliases you want per city.


Docker Compose with Multiple Networks

Question: I have a docker-compose file that specifies two containers which are to be created in two separate networks:

A mysql database -- this contains the adventureworks data (and belongs to adventureworks-db-nw network).
A java based webapp -- this talks to the mysql database to perform CRUD operations (and belongs to adventureworks-app-nw network).

version: '3'
services:
    adventureworks-db:
        image: mysql
        container_name: adventureworks-db
        networks:
            - adventureworks-db-nw
        ports:
            - 3306:3306
    adventureworks-app:
        container_name: adventureworks-app
        networks:
            - adventureworks-app-nw
        ports:
            - 8080:8080

networks:
    adventureworks-db-nw:
        driver: bridge
    adventureworks-app-nw:
        driver: bridge

For brevity, I have omitted certain parts of the docker-compose.yml file that will perhaps not be relevant to the question I have.
How can I get the java webapp in adventureworks-app container, that belongs to the adventureworks-app-nw to talk to the mysql database in adventureworks-db container, that belongs to the adventureworks-db-nw network?
Please note that I want to maintain the separation of these two networks as two separate custom (user-created) docker networks.
Comment: Why wouldn't the app be on the same network as the database?
Comment: @OneCricketeer They typically would be. But in this particular scenario, I'm trying to mock a non dockerized ecosystem. The app resides in a separate network, the MQ (for ex, Kafka) is hosted by some provider on their own network,  the database is hosted by some other provider on their own network, etc. I'm using containers to represent individual services that are typically going to be provided by different providers on separate networks..
Comment: In that case, you need to model the router/proxy as well that allows you to interact between those two different networks. In other words **something** is responsible for routing traffic between networks. Otherwise, you will run into the issue you have now
Comment: @OneCricketeer Yep, exactly. How can I go about modelling a router/proxy between two docker networks?
Comment: Traefik is one example that I know of, but it would be easier to just allow the Java app to exist on the database network rather than remodeling external network infrastructure.
Comment: Will check it out. Thanks @OneCricketeer
Answer: If you want the java app to communicate with the db container via it's service name, then you would have to add the "adventureworks-db-nw" network to the app service.
If you don't want to do that then since you are exposing the ports I guess you should be able to connect by using the host ip/hostname and the exposed port.

Docker Compose with Multiple Networks


Bootstrapping confidence intervals in randomization model and population model

Question: Ernst 2004 shows that the permutation tests in the random assignment scheme (e.g., controlled experiment) and in the random sampling scheme (e.g., observational study) share the same constructing mechanics but different reasoning (pages 677, 681). The scopes of inference in two cases are inherently different.
I then wonder about the construction of confidence interval of a statistic by bootstrapping. It seems sensible under the random sampling scheme. Does it make sense under the random assignment scheme?
Update: I continue with the code from @BruceET in which I use difference between means as the metric in the permutation test, p-val is similar. My concern is about the 95% bootstrap CI that I calculate below for this difference in the improvement scores between two groups of student, whether it makes sense in the random assignment setting.
set.seed(1234)
x1 = rnorm(15, 100, 14)
x2 = rnorm(15, 110, 14)

d.obs <- mean(x2) - mean(x1); d.obs
[1] 11.14442

x <- c(x1, x2)
d.per <- rep(0, 99999)
for (i in 1:99999){
    newx <- split(sample(x), rep(c("x1", "x2")), c(15,15))
    d.per[i] <- mean(newx$x2) - mean(newx$x1)
}

p <- (sum(abs(d.per)>=abs(d.obs))+1)/1e5; p
[1] 0.02118

d.boot <- rep(0, 99999)
for (i in 1:99999){
    newx1 <- sample(x1, replace = T)
    newx2 <- sample(x2, replace = T)
    d.boot[i] <- mean(newx2) - mean(newx1)
}
quantile(d.boot, c(0.025,0.975))
2.5%     97.5%
 2.640416 20.407527

Comment: Are you trying to decide whether to do a permutation test or to make a bootstrap CI to analyze data at hand? If your question is fundamentally a philosophical one, then your link may have something to offer. But if you are talking about analyzing some actual data, I would like to know more about your study, data, and objectives.
Comment: @BruceET Hi, I want to analyze actual data in both cases (random assignment in which we compare control and treatment group and random sampling in which we compare clean station and polluted station). I want to calculate the effect size (e.g., difference bw means, ratio of means), do a permutation test using that effect size as the test statistic to get the p-value, and use bootstrapping to construct the CI of that effect size. The randomized p-value seems ok in both situations according to the paper, but I am not sure about the bootstrap CI.
Comment: For permutation test, be careful you have _exchangeability_ under $H_0.$ My personal preference is to use bootstrapping for CIs and permutation tests for testing. // I would not want to take any one paper (incl. your link) as a definitive guide. Opinions vary.
Answer: I will show both a bootstrap CI and a permutation test, with comments along the way. In both cases it happens to be possible to get similar results without computationally intensive methods.
Bootstrap. A nonparametric bootstrap CI for a population standard deviation $\sigma.$
Let x be a sample of size $n = 100$ from
a population with unknown SD $\sigma.$ Find a 95%
bootstrap CI for $\sigma.$
set.seed(2022)
x = rnorm(100, 50, 7)
sd(x)
[1] 7.140652

The bootstrap procedure helps to estimate the
variability of the sample SD $S.$
If we knew the distribution of $S=\sigma,$
then we could find bounds $L$ and $U$ such that
$P(L < S-\sigma < U) = 0.95$ so that a 95% CI
for $\sigma$ would be of the form $S-U < \sigma < S-U.$
Not knowing $L$ and $U,$ we repeatedly take re-samples, which are samples of size $n$ with replacement from x, find the sample standard deviation $S^*$ of each and use distances $S^* - S_{obs}$ to get an idea of
the distribution of $S - \sigma,$ and thus estimates of $L$ and $U.$
The resulting
95% CI for $\sigma$ is $(6.13,\, 8.24).$
s.obs = sd(x);  s.obs
[1] 7.140652

set.seed(417)
d = replicate(2000,
       sd(sample(x,100,rep=T))-s.obs)
LU = quantile(d, c(.975,.025))
s.obs - LU
   97.5%     2.5%
6.125899 8.241970

In this particular example, we are using simulated
normal data, for which $\sigma = 7.$ and
for which an exact 95% CI $(6.27,\, 8.30)$ for $\sigma,$ based on a chi-squared distribution, is available. [In an application with real data, none of this would be known.]
sqrt(99*var(x)/qchisq(c(.975,.025),99))
[1] 6.269541 8.295119

Of course, the exact CI is better. Moreover, we could have improved the bootstrap CI in various
ways; perhaps most notably by recognizing that $\sigma$ is a scale parameter and bootstrapping ratios instead of differences.
The main point is that even one of
the simplest bootstrap methods gives a useful CI
if we know nothing about the population distribution, except that it has a standard deviation, as does its estimate $S.$
Permutation test.  Consider two independent samples. We wish to test whether their population means are equal.
set.seed(1234)
x1 = rnorm(15, 100, 14)
x2 = rnorm(15, 110, 14)
x = c(x1, x2)
g = rep(1:2, each=15)
boxplot(x ~ g, horizontal=T, col="skyblue2")

Suppose the 30 randomly chosen students are randomized into two groups, and
taught how to do a task using two different methods. Data x1 and x2 are improvement
scores derived from before and after tests, the
same tests used for both groups.
Not having
done this kind of training before, nor used these
tests before, we wonder whether data are normal.
Particularly because of the small sample sizes
we wonder whether it is appropriate to use a pooled 2-sample test to judge whether the group means
differ.
If the null hypothesis (no difference) is true,
then we believe that the values in x1 and x2 are exchangeable. That is, under $H_0$ we believe the two groups are indistinguishable.
We may have doubts about the validity of a pooled
2-sample t test, because it may not be clear that the t statistic has a t distribution. Nevertheless, we are willing to use the pooled t statistic a reasonable way to measure any difference
between the two groups. Accordingly, we will use
the pooled t statistic as a 'metric' for a permutation test. And we will simulate the distribution of the metric under $H_0.$
The permutation distribution of the t statistic
can be approximated by scrambling the improvement scores in x1 and x2 at random at each iteration and finding
the t statistic for each scrambled set of samples.
We use $m =100\,000$ iterations.
The following R code finds the $m$ pooled t statistics and the approximate P-value of the
the permutation test. Note that 'sample(g)` randomly scrambles the group assignments at each iteration.
t.obs = t.test(x~g,var.eq=T)$stat;  t.obs
        t
-2.374767
set.seed(418)
t.stat = replicate(10^5, t.test(x~sample(g),var.eq=T)$stat)
mean(abs(t.stat) >= abs(t.obs))
[1] 0.0211  # aprx P-val of perm test

The histogram below shows the simulated permutation distribution of the t statistic. The P-value of the test is the total probability outside the two vertical bars.
hist(t.stat, prob=T, col="skyblue2")
 abline(v=c(t.obs,-t.obs), col="brown")

The P-value $0.025$ of the pooled t test is
nearly the same as the P-value of the permutation test. [So, the pooled t test would have been OK.]
t.test(x~g, var.eq=T)$p.val
[1] 0.02464866

Comment: Thank you. I update my post based on your answer to clarify my intent. I would like to know if the bootstrap CI I built for the difference bw means of two groups (a kind of effect size) makes sense in your hypothetical experiment.
Comment: Interesting proposal. This site works best when people stick to methods they really know about from practical experience. As I said in my previous comment, I would prefer a permutation test for this. However, there are various approaches to what you propose. Suggest you google `bootstrap difference between two means` for an overview. // If someone on this site has used such procedures successfully, we may hear from them. Perhaps along with a reason for not using a permutation test instead.


Error when starting .Net-Application from ThinApp-Application

Question: one of our customers uses SAP through VMWare ThinApp.
In SAP there is a button that launches an .Net application from a server. When starting the .Net-application directly, there is no error. If the user tries to start the application by clicking the button in the ThinApp-Application, it displays the following errors:
Microsoft Visual C++ Runtime Library

R6034
An application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support team for more information.

After clicking "OK" it displays:
Microsoft Visual C++ Runtime Library

Runtime Error!

R6030
- CRT not initialized

So, does the customer have to install some components into his ThinApp (if yes, which?) to get things working?
Regards,
inno
----- [EDIT] -----
@Sean:
It's installed the following way: The .exe of the .Net-Application is on a mapped drive on a server. All clients have the requirements installed (.Net-framework for example) and start the .exe from the mapped drive.
The ThinApp-Application tries to start this application and throws the mentioned exceptions. AFAIK there are no entry points for this application configured.
What I should also mention is: The .Net-Application crashes during execution. That means, we have a debug mode implemented that shows what the application is doing. The application shows what it's doing and after some steps it crashes.
The interesting point is: It's a .Net-application, not a C++ Application.
Comment: in that application is there any component that may leverage some legacy/unmanaged code? also check with the developer if there is any requirement to satisfy for third party components, if any.
Answer: It depends on how the application was packaged ultimately. When you say you launch the .net application directly, is that installed in the base operating system as another entry point for that ThinApp?


ios Swift UICollectionViewCompositionalLayout Mirrored UI on switching UI Layout direction

Question: whenever I switch language at runtime using the following code:
//set apple language to force localization use the intended language
let userdef = UserDefaults.standard
userdef.set(["ar" /*or "en" to switch to english*/], forKey: "AppleLanguages")
userdef.synchronize()
//force all views to use propery layout direction
UIView.appearance().semanticContentAttribute = forceRightToLeft /*or .forceLeftToRight*/
//reload root view controller
(UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController = UIStoryboard(name: "Main", bundle: .main).instantiateInitialViewController()

Any collection view that uses Compositional Layout would be mirrored, not that the layout flipped but the content is mirrored.
Answer: Finally figured it out, must go old school:
1- for collection views, whenever created(either in storyboard or by code), fix the semantics to force LTR
2- whenever the language require RTL, apply transform with scaleX = -1, scaleY = 1 to the CollectioView itself.
3- for every view cell, apply another transform with scaleX = -1, scaleY = 1
Note for some layouts (mainly horizontal scrolling with dynamic item width) assigning transform to the collection view cell directly won't work and will leave the CollectionView Cell mirrored by the collection view transform.
3.1- so need to apply the transform to the top level subviews of the collection view cell.
To minimize the code, should wrap all the subViews of the collection view cell into one view filling the collection view cell, and apply the transform to it.