I am looking for a responsive slider that can take text instead of images

Question: Do you know of a responsive slider that can take text instead of images?
I have been using Nivo Slider and have had great experiences with its responsive design. I am using one on the front page. I wanted another, so I used Views Nivo Slider. My client decided to have another with text instead of pictures, but Views Nivo Slider didn't seem to want to do this. I don't think I can hack the Nivo Slider code because it would effect my other sliders on my webpage.
Here are some pictures. With images, the slider behaves normally.

When I add the body content and change the slider to show the body as so,

I get this:

Nothing shows up.
The same thing happens if I try to put the body into the title instead of the image.
Comment: can you provide screenshots or examples of the errors you are encountering?
Comment: It looks like a CSS issue with word length maybe, by which I mean images can resize easily -- I doubt they mean it to be used with solely text. Eg http://stackoverflow.com/questions/9733527/nivo-slider-add-text-to-the-slider
Comment: When I look at my page, there is only HTML tags within the slider tags. This question was mainly to see if there was a module that did this without changing code, but I am willing to try to get it to work. I am just worried that my changes will effect the other sliders on my page. Also, I changed the CSS code and it didn't do anything.
Comment: With your comments, I decided to try to put an image and the body into the title. This showed the text. I think I will put a blank image and have the text show up that way. Thank You! If you put an answer I will mark it.
Answer: There is a smaller group out there Theme Boutique who built a really remarkable slideshow tool called the Revolution Slider.  It's currently out ther and available on their Dawn Responsive theme (I have used their BigWig theme in the past with the same slideshow).  It worked really well and didn't require alot of the gymnastics that I've seen with other solutions.
Here's a demo video of it in action.  https://www.youtube.com/watch?v=zZL2renvh5o
Answer: Try jCarousel uses the jCarousel jQuery plugin which can do text too


Data visualization tips for a 2x2 factorial design

Question: The data stem from a 2x2-factorial design where both factors have two levels. The x-axis shows the words of a sentence and the y-axis the mean reaction time for each single word. Here is how I visualize the data so far with base R:

I find the usual method of visualizing such data rather unappealing but I couldn't come up with a nice idea myself. Are there more appropriate ways of summarizing such data in one single plot?
Comment: What are the bars above and below the points? What are the stars? They need to be described or removed. Why is the axis broken when there are no points below the break, and the scale doesn't seem to actually break there?
Comment: And if there's any kind of natural (read: substantively relevant) ordering on the x-axis, you should use it. BTW I'm posting these as comments and not answers because they don't really relate to 2x2 experiments, but I think they do need to be addressed
Comment: The bars are error bars according to Cosineau (2005). The stars show significance but don't really matter here as this is random data. The scale with the original data is broken between 0 and a larger number. In short: This is a pure dumb plot only in existence to illustrate the problem without a lot of words. It obviously lacks the precision one would wish for.
Comment: my suggestion stands: label it or drop it. Also, don't break plots just to get 0 in there, unless 0 is an important reference point for this data (and usually it isn't)
Comment: I agree with the labeling but error bars et. al. I would outsource to a figure caption. The breaking-the-axis-part is controversial so we probably won't settle this here. Thanks for the tips.
Comment: What aspect of the reaction times do you want to emphesize? If you want a table-like visualisation but without numbers, you could create a heat-map. If you want to a bar chart maybe try a stacked or grouped bar-chart. If you're interested in the multivariate aspect maybe try a spider chart or Chernoff Faces?
Answer: The X-axis is not a continuous variable, therefore connecting the adjacent X-values is not appropriate. In other words: ditch the connecting lines.
As for visualisation, one other option would be to use a bar chart. But I am afraid it would only make things worse.
IMHO, the best visualization would actually be to put the values in a table. One word in a row with your four values as columns.
Comment: But I _do_ agree that [a table is a great idea](http://andrewgelman.com/2011/12/22/tables-as-graphs-the-ramanujan-principle/).
Comment: "The X-axis is not a continuous variable, therefore connecting the adjacent X-values is not appropriate." I [completely disagree](http://en.wikipedia.org/wiki/Parallel_coordinates).
Comment: There is nothing prohibiting you from connecting the dots with lines, but the clarity of such visualisation is very poor. Just look at that graph from the Wiki page that you linked - you have to look it from a distance to see some patterns...
Comment: Call it preference, then. But try drawing that graph without the connecting lines: good luck seeing _any_ patterns at all.
Comment: I don't see the table-"plot" to be a viable option. Regarding the bar-chart-option: A bar chart were you put four bars for each word next to each other?
Comment: @brauner I'd say that's even worse. Impossible to make within-X-level comparisons


$n$ fractional gaussian rational numbers and set of rules to govern them

Question: Suppose that there are $n$ Gaussian rational numbers of form $a_t + b_ti$. For any $t$th number, $a_t$ and $b_t$ are both constrained to be non-zero rational numbers (fractions). Suppose that we impose the following: $a_t^2 - b_t^2 = c/d $ while $a_tb_t = e/f$ where $c,d,e,f$ are non-zero integers.
We also impose the following condition: For all possible $n$ products of imaginary numbers (the product may be the multiplying the product of the multiplication of same number with the product of some number combination), only when $n$ different numbers are multiplied, the resulting product cannot be converted into $(\frac{g}{h}+\frac{j}{k}i)(\frac{c}{d} + \frac{e}{f}i)$  where $g,h,j,k$ can be any integer.
Is this possible?
Comment: I must say this is a very obscure question. Is there any motivation behind it?
Comment: Pure math curiosity + modeling curiosity.
Comment: feeling cryptic I see....
Comment: It seems there are a few of these cryptic questions about multiplying Gaussians; http://math.stackexchange.com/questions/287965/the-set-of-numbers-that-when-multiplied-do-not-get-decomposed-into-sxty-while and http://math.stackexchange.com/questions/290257/imposing-condition-of-specification-of-product-of-n-of-imaginary-numbers-on-co#comment632793_290257
Answer: I'm assuming that your $n$ product of imaginary numbers are from that initial set that you described, which I will call the 'Gaussian Rationals'.
The product of any such numbers will still lie in the Gaussian Rationals. In particular, we can set $c=d=f=1, e=0$.


return single array from json by passing a value

Question: I have a json that I need to filter a specific key and value from
the following json
{
"5": {
      "Owner": "94EAC",
      "Record":"0121ln"
},
"15": {
      "Owner": "009AC",
      "Record":"0120Pc"
},
"1": {
      "Owner": "00G11A",
      "Record":"000lPcn"
},
"199": {
      "Owner": "00G1y9",
      "Record":"01211cn"
},
"33": {
      "Owner": "001AC",
      "Record":"0121n"
}

}
I would like to be able to pass the first int and get back array for that number.
For example if I pass 15 I get
 {
      "Owner": "009AC",
      "Record":"0120Pc"
}

I tried foreach loop but cannot set specific value for the first int
If I assign $data = json

then $date[15] didn't work
$data->15 also didn't work
I did also use the json decode and was able to print an array but wasn't able to get a single value
Any help would be great, I did spend all day and still cannot get an answer.
Thank you
Comment: Did "didn't work" materialize as an error message?
Answer: Using Array:
$arr = json_decode($json, true);
print_r( $arr['15']);

Using Object:
$obj = json_decode($json);
print_r( $obj['15']);

Reference: json_decode
Comment: Thank you so much, I was missing the '' I was passing the number without the ''
Comment: Just remember if you are accessing a variable index, prefer to use square brackets. :)


Area of $x^3 -2x^2 + x - 2$ and $x$-axis

Question: I know it supposed to be so easy. But how to set up the boundaries?
Comment: A hint could be that x-axis is limited by where expression (y-coordinate) equals = 0.
Comment: Another hint:  it's $(x-2)(x^2+1)$
Comment: Are you supposed to find the area between the graph of $x^3-2x^2+x-2$, the $x$-axis, and the $y$-axis?
Comment: Question says only x axis
Comment: The questions asks for area between x-axis and $f(x)$ , not $F(x)$. What you have provided was $F(x)$.
Comment: What is $f(x)$ ?
Comment: I wrote a solution, please check it. :)
Answer: Since $F(a)=0$ we get $$ a^3-2a^2+a-2=0$$ which implies $a=2$
The rigeon that $F(x)>0$ is for $x>2$
The area bounded by the points $2$ and $x$ is $$A(x) =  \int_2^x f(t) \mathrm dt =x^3-2x^2+x-2$$
Comment: Ok. Sorry. Thanks
Answer: This is a cubic polynomial with real coefficients, and so it will either have one or three real roots(because complex roots occur in conjugate pairs). Now, when you put x=2, the function is 0. So, the question is incomplete!
Comment: Ok. Sorry. Thanks
Answer: Hint: $$F(x) = \int_a^x f(x) \mathrm dx \Rightarrow f(x) = F'(x)\ \ \ \text{by FTOC}$$
Find $f(x)$ and then try finding the area.
Comment: What is FTOC? @Rick
Comment: Oh that's Fundamental Theorem of Calculus (FTOC)
Answer: Now that you have edited the question,
it looks like it is asking for the area between $f(x)$ and the $x$-axis,
not the area between $F(x)=x^3-2x^2+x-2$ and the $x$-axis.
The derivative of $F(x)=x^3-2x^2+x-a$ is $f(x)=3x^2-4x+1$,
so we have $\int_a^x 3t^2-4t+1=t^3-2t^2+t|_a^x=x^3-2x^2+x-(a^3-2a^2+a);$
and $a=a^3-2a^2+a$ and $a\ne0$ means $a=2$.
The area surrounded by the $x$-axis and $f(x)=3x^2-4x+1=(3x-1)(x-1)$ is $$\left|\int_{1/3}^1 f(t)dt\right|=\left|F(x)|_{1/3}^1\right|.$$
Comment: Yes. Thank you..
Answer: You have:
$$F(x) = \int_a^x f(t)dt = x^3-2x^2+x-a$$
Taking the derivative:
$$F'(x) = f(x) = 3x^2-4x+1$$
So, reintegrating, you have:
$$F(x) = \int_a^x (3t^2-4t+1)dt = \left. t^3-2t^2+t \right]_a^x = x^3-2x^2+x-(a^3-2a^2+a) = x^3-2x^2+x-a^3+2a^2-a$$
This implies that $a^3-2a^2=0 \Longrightarrow a^2(a-2)=0 \Longrightarrow a=0,a=2$, but you are given $a\neq 0$.
$$F(x) = x^3-2x^2+x-2 = (x-2)(x^2+1)$$
This is a product of two real numbers, so it is positive only when both factors share the same sign. Since $x^2+1$ is always positive for all real $x$, you only care when the first factor is positive. $x-2$ is positive when $x>2$. Thus, $F(x)>0$ for $x>2$.
Finally, you are looking for the area between the $x$-axis and $3x^2-4x+1 = (3x-1)(x-1)$. Since the $x$-axis is above your function, you are looking for:
$$\int_{\tfrac{1}{3}}^1 (0-(3x^2-4x+1))dx = F\left(\dfrac{1}{3}\right)-F(1) = \dfrac{4}{27}$$
Comment: Yes. Thank you..


how can I manipulate functionality or the structure of an existing form?

Question: How can I manipulate functionality or the element's structure of an existing form in a different way and create my own template?
For example, I can use below code to display a user login form page, but this code doesn't have any flexibility and doesn't allow me to edit or customize each part of this form element separately and I can't change the look and order of this form straightforwardly.
Imagine that I want to add show password checkbox and other visual effect and style to that's form element.
Page--user.html.twig
<code>{{ page.content }}
</code>
Answer: You should separate functional and visual changes.
All the functional changes should done by hook_form_alter and the rest with preprocess functions (if needed) but rather with twig.
If you use devel module, you can use the kint() function in twig, so you will see you can also filter page.content. But if that's not enough you can make an own template to this particular form, you will need twig debug enabled, which will show you HOW TO change a part of the dom (once again preprocess function and template naming convention suggestions).


Terminology confusion re: sample outcomes

Question: I've just started Wasserman's All of Statistics and he starts by saying:
"The sample space $\Omega$, is the set of possible outcomes of an experiment.  Points $\omega$ in $\Omega$ are called sample outcomes or realizations.  Events are subsets of $\Omega$."
So sample outcomes are just the one-element subsets of $\Omega$, while events are all subsets of $\Omega$?
Answer: A little bit different: the sample outcomes, also called "elementary events", are the points of $\Omega$, the one-element subsets of $\Omega$ are also events (that is, in elementary probability, with finite or countable sample space $\Omega$, they are events, in the more general case, they might or might no be events.
THE REST IS TECHNICAL AND COULD BE IGNORED BY MANY
That is because, in a formal definition of probability space as a triple $(\Omega, \mathcal{B}, P)$, the events are the elements in $\mathcal{B}$, a sigma-algebra of subsets of the sample space $\Omega$. Those subsets in the sigma-algebra are given probabilities by the probability measure $P$, and those are the events. Other subsets are not given any probability, and are not events. In most practical cases, the one-point subsets will be events.
Comment: The singletons (one-element subsets) might or might not be events.
Comment: @Antoni BTW, I see the source of the confusion: Wikipedia uses "event" inconsistently.  The page you reference assumes an event could be *any* subset of $\Omega$ and states that some events just have undefined probabilities (which is a strange thing to assert). However, for the definition of "event" it references https://en.wikipedia.org/wiki/Event_%28probability_theory%29, where it states "an event is ... a subset of the sample space ... to which a probability is assigned." This latter sense is, I believe, the conventional one.
Comment: @whuber Thank you for your detailed explanation. Can I conclude that a singleton is a subset of $\Omega$ which might be an event _if_ there is a probability assigned to it, or otherwise still be a subset, but not an event? It's hard to come up with an example with dice or cards...
Comment: @Antoni That's correct. For a cards example you could (say) stipulate that the only events you want to ascribe probabilities to are the suits. All events would have 0, 13, 26, 39, or 52 elements, corresponding to which suits they contain. Although this is artificial, it illustrates the distinction between an event and a subset. Questions like "what is the chance the card is red" would have well-defined answers, but questions like "what is the chance the card is the queen of hearts" would not. None of these events are singletons.
Comment: Could you elaborate, then, on what "points" are and joe to know whether they constitute events?
Comment: "points" are the elements in the sample space $\Omega$. Did you understand the explication in my answer?
Comment: @kjetilbhalvorsen Ah so if I flip a coin 3 times, then a "point" would be any one of TTT, TTH, THT, THH, HTT, HTH, HHT, or HHH, yeah?  Whereas an event is basically an element of the power set of $\Omega$, yeah?
Comment: @whuber I've been trying to understand your comment, but I'm stuck, for instance in the wikipedia page on [elementary event](https://en.wikipedia.org/wiki/Elementary_event) it sounds like they always are.
Comment: @Antoni An *event* is always a subset of $\Omega$, but not every subset of $\Omega$ is necessarily an event.  Although the distinction between events and subsets is forced on us only by the theory of integration, and is unnecessary for finite $\Omega$, even in certain practical cases it is not guaranteed that singletons are events. It frequently happens in the analysis of stochastic processes that singletons are not events: there are reasons to disallow the assignment of probabilities to them. This is one way of characterizing what information can be available at various times.
Answer: [Tentative answer. Thank you very much to William Huber for his patient guidance as apparent in the comments.]
The probability space can be thought as a construct based on three decision levels:
Decision 1: The Random Experiment

The experiment can be simply observing and counting something we have no control over, or tossing a die in the air once, or an infinite number of times. A random experiment fulfills two conditions: 1. It has more than one possible result (or outcome); and 2. The results cannot be predicted in advance.
Decision 2: The Outcome

We can focus in any of the virtually infinite aspect of the "experiment". For instance if we are tossing a die, we can measure how high above the table it flies; how far away it travels; in what quadrant of the table it lands; how many rolls it takes before settling; or the more obvious outcome: what side is facing up when it stops moving (heads or tails).
After deciding what outcome we care about, the sample space will be immediately defined as the set of all possible elementary outcomes. These outcomes or elements of the sample space are denoted by the letter $\omega$.
If we look at the quadrant of the table where the die lands, the sample space will be $\Omega =\small\{LUQ, RUQ, LLQ, RLQ\}$ (left-upper quadrant, right-upper quadrant,...), whereas if we record the most typical outcome (the number facing up), the sample space will be $\Omega= \small\{1, 2, 3, 4, 5, 6\}$. $\small 1$, $\small 2$,... $\small 6$ being the elementary outcomes constituting the sample space.
Any grouping of elements of $\Omega$ corresponds to a subset, for instance $A_1 =\small \{1, 4\}$. Singletons are one-element subsets within the set: $A_2 = \small \{1\}$ and $A_3 = \small \{4\}$.
If the experiment consists of tossing three coins and we are interested in checking the Heads v Tails dichotomous outcome, the sample space will be $\Omega= \small\{HHH,HHT,HTH,THH,TTT,TTH,THT,HTT\} =\{H,T\}^3$ containing $2^3$ elementary outcomes. These are not $\small H$ or $\small T$, but rather $\small HHH$, $\small HHT$, etc.
Decision 3: The Event

Of all the possible subsets in the sample space $\Omega$ (imagine circles around groups of elementary outcomes) only some will be interesting to us in terms of assigning probabilities to them. It is the fact that we assign a probability measure to them that makes them events. Events can be simple (singletons) if they correspond to subsets with just one element from the sample space; or compound if they encompass more than one point in $\Omega$.
For instance, the event defined as "only one $\small T$" can be expressed as $A = \small \{HHT, HTH, THH\}$. This is a subset of the sample space of the experiment throwing three coins, but not any subset - it is the subset we want to assign a probability measure to.
An event has occurred when the outcome (denoted as $\omega$ to remind us that $\omega \in \Omega$) is also contained in the subset $A$, that is, $\omega \in A$.
The original question was:
"So sample outcomes are just the one-element subsets of $\Omega$, while events are all subsets of $\Omega$?"
The first part of the question sounds at first correct, except for the mathematical inconsistency pointed in the comments: an outcome ($\omega$) is not a subset ($\{\omega\}$). Perhaps the correct terminology is "the sample outcomes are contained in one-element subsets or singletons" (?).
Not all subsets of $\Omega$ are events: Events are only those subsets of $\Omega$ we happen to be interested in. They are the collections of subsets of $\Omega$ within the $\sigma$-algebra ($\mathcal{B}$), forming together with the sample space ($\Omega$) a measurable space. Once we assign probabilities to these collections of subsets of $\Omega$ we complete the probability space $(\Omega, \mathcal{B}, P)$.
On the other hand, all events are subsets of $\Omega$.
Comment: It's very good now, Antoni, except for one small thing: one paragraph after stating you will use "$\omega$" to designate outcomes, you use it instead to designate subsets.  I suspect you intended to use something like $A$ in that example rather than $\omega$.


O que é o apvector do C++

Question: O professor da faculdade, pediu pra pesquisar sobre os scripts de ordenação e realizar testes com eles, determinando qual é melhor em que situação.
Encontrei os scripts, porém no site o cara não mostra como executar, e ele utiliza um apvector que não sei de onde vem, por isso não consigo executar os scripts.
Esse apvector é alguma biblioteca? Com consigo executar esse script?
// Bubble Sort Function for Descending Order
void BubbleSort(apvector <int> &num)
{
      int i, j, flag = 1;    // set flag to 1 to start first pass
      int temp;             // holding variable
      int numLength = num.length( );
      for(i = 1; (i <= numLength) && flag; i++)
     {
          flag = 0;
          for (j=0; j < (numLength -1); j++)
         {
               if (num[j+1] > num[j])      // ascending order simply changes to <
              {
                    temp = num[j];             // swap elements
                    num[j] = num[j+1];
                    num[j+1] = temp;
                    flag = 1;               // indicates that a swap occurred.
               }
          }
     }
     return;   //arrays are passed to functions by address; nothing is returned
}

Comment: - Fonte do [`apvector.cpp`](ftp://ftp.cs.berkeley.edu/ucb/people/clancy/fish.code/AP.CS.classes/apvector.cpp);
- Sobre a classe [`apvector`](https://academics.tjhsst.edu/compsci/CS2C/U2/array.html)
Comment: Opa, consegue colocar a resposta dando exemplo de como eu importo essa classe no meu arquivo `ordenacoes.cpp`, estou utilizando Dev C++. Assim já posso considerar como resposta válida. Valeu! :D
Comment: Consigo sim, mas dá uma olhada antes e se realmente te ajuda, não manjo de C e foi mais uma pesquisa pra ajudar.
Comment: Abre um novo projeto como biblioteca dinâmica e compila o `apvector.cpp`, depois importe a dll para seu projeto. se o devc++ usa makefile, basta acrescentar o arquivo `apvector.cpp` na compilação, se quiser tentar compilar pelo gcc, basta usar `g++ apvector.cpp meuprojeto.cpp -o projeto.exe`
Answer: A classe Apvector é baseada na classe Vector, e todos os métodos pertencentes a ela também fazem parte da Vector. É um template que você poderá especificar com qual tipo de coleção ela trabalhará.
Algumas características da Apvector:

São como arrays e seu índice inicia-se a partir do zero
Podem ser inicializados para manter o mesmo valor em cada índice, provendo um segundo argumento para o construtor enquanto o vector é definido.
Podem ser redimensionados
Devem ser passados por referência

A seguir segue o modelo de implementação da classe Apvector
// *******************************************************************
//  APCS vector class  IMPLEMENTATION
//
//  see vector.h for complete documentation of functions
//
//  vector class consistent with a subset of the standard C++ vector class
//  as defined in the draft ANSI standard (part of standard template library)
// *******************************************************************

#include <stdlib.h>
#include <assert.h>
#include <iostream.h>
#include "apvector.h"

template <class itemType>
apvector<itemType>::apvector()
//postcondition: vector has a capacity of 0 items, and therefore it will
//               need to be resized
    : mySize(0),
      myList(0)
{

}

template <class itemType>
apvector<itemType>::apvector(int size)
// precondition: size >= 0
// postcondition: vector has a capacity of size items
   : mySize(size),
     myList(new itemType[size])
{

}

template <class itemType>
apvector<itemType>::apvector(int size, const itemType & fillValue)
// precondition: size >= 0
// postcondition: vector has a capacity of size items, all of which are set
//                by assignment to fillValue after default construction
    : mySize(size),
      myList(new itemType[size])
{
    int k;
    for(k = 0; k < size; k++)
    {
        myList[k] = fillValue;
    }
}

template <class itemType>
apvector<itemType>::apvector(const apvector<itemType> & vec)
// postcondition: vector is a copy of vec
    : mySize(vec.length()),
      myList(new itemType[mySize])
{
    int k;
        // copy elements
    for(k = 0; k < mySize; k++){
        myList[k] = vec.myList[k];
    }
}

template <class itemType>
apvector<itemType>::~apvector ()
// postcondition: vector is destroyed
{
    delete [] myList;
}

template <class itemType>
const apvector<itemType> &
apvector<itemType>::operator = (const apvector<itemType> & rhs)
// postcondition: normal assignment via copying has been performed;
//                if vector and rhs were different sizes, vector
//                has been resized to  match the size of rhs
{
    if (this != &rhs)                           // don't assign to self!
    {
        delete [] myList;                       // get rid of old storage
        mySize = rhs.length();
        myList = new itemType [mySize];         // allocate new storage

            // copy rhs
        int k;
        for(k=0; k < mySize; k++)
        {
            myList[k] = rhs.myList[k];
        }
    }
    return *this;                               // permit a = b = c = d
}

template <class itemType>
int apvector<itemType>::length() const
// postcondition: returns vector's size (number of memory cells
//                allocated for vector)
{
    return mySize;
}

template <class itemType>
itemType & apvector<itemType>::operator [] (int k)
// description: range-checked indexing, returning kth item
// precondition: 0 <= k < length()
// postcondition: returns the kth item
{

    if (k < 0 || mySize <= k)
    {
        cerr << "Illegal vector index: " << k << " max index = ";
        cerr << (mySize-1) << endl;
        abort();
    }
    return myList[k];
}

template <class itemType>
const itemType & apvector<itemType>::operator [] (int k) const
// safe indexing, returning const reference to avoid modification
// precondition: 0 <= index < length
// postcondition: return index-th item
// exception: aborts if index is out-of-bounds
{
    if (k < 0 || mySize <= k)
    {
        cerr << "Illegal vector index: " << k << " max index = ";
        cerr << (mySize-1) << endl;
        abort();
    }
    return myList[k];
}

template <class itemType>
void apvector<itemType>::resize(int newSize)
// description:  resizes the vector to newSize elements
// precondition: the current capacity of vector is length(); newSize >= 0
// postcondition: the current capacity of vector is newSize; for each k
//                such that 0 <= k <= min(length, newSize), vector[k]
//                is a copy of the original; other elements of vector are
//                initialized using the 0-argument itemType constructor
//                Note: if newSize < length, elements may be lost
{
    int k;
    int numToCopy = newSize < mySize ? newSize : mySize;

         // allocate new storage and copy element into new storage

    itemType * newList = new itemType[newSize];
    for(k=0; k < numToCopy; k++)
    {
        newList[k] = myList[k];
    }
    delete [] myList;                      // de-allocate old storage
    mySize = newSize;                      // assign new storage/size
    myList = newList;
}

@edit

@Maniero - Qual a vantagem dela em relação à Vector?

A classe verifica as subrotinas em tempo de execução para garantir
que sempre fiquem dentro do limite, evitando assim bugs de out of
bounds.
O tamanho do apvector é armazenado em um Vector, eliminando assim a
necessidade de uma variável extra.
Um apvector pode ser copiado para outro utilizando o operador de
atribuição.
Quando o apvetor é declarado, o compilador aloca apenas um espaço na
pilha com o seu tamanho e um ponteiro para a matriz real, porque a
matriz real é alocada dinamicamente na memória livre.

Fonte¹
Fonte²
Apvector.h
Apvector.cpp
Comment: Boa resposta, só fiquei com uma dúvida, qual a vantagem dela em relação à `Vector`?
Comment: @bigown adicionei a resposta para tua questão.
Comment: Acho que esta é a definição do `Vector`. Está me parecendo uma classe sem utilidade prática alguma.

O que é o apvector do C++


The intersection of the convex hulls of two finite sets of points is again the convex hull of a finite set of points

Question: I have two sets, each of which is the convex hull of finitely many points in $\mathbb{R}^n$ (in my case $\mathbb{R}^5$, but that shouldn't really matter).  I'm certain that their intersection is itself the convex hull of finitely many points.
This seems to be one of those things that's "obvious" but hard to prove.  A (somewhat terse) proof in two dimensions is given by The intersection of finite number of convex hulls is a convex hull.
I am unsure whether the induction mentioned is to handle $\mathbb{R}^n$.  Attempting to generalize the argument even to $\mathbb{R}^3$ or $\mathbb{R}^3$, let alone $\mathbb{R}^n$ gets messy fast.  I'm wondering if there's an easier way to handle this.
One idea is to show that a set is the convex hull of finitely many points iff both it is bounded and it is the intersection of finitely many closed half-spaces.  That could be simpler, but I'm not sure how to do that either.
Comment: Nice question.  I agree, there should be an easy to remember and easy to communicate version of the plan you sketch in your last paragraph.
Answer: In "Polytopes, Rings, and K-Theory," Bruns/Gubeladze attribute the following to Minkowski:

$P\subseteq \mathbb{R}^n$ is a polytope $\iff$ $P$ is the convex hull of a finite subset of $\mathbb{R}^n$

which is the theorem you reference as a proof method in your last paragraph.
Sidenote: In attempting to look this up, it seems to be a special case of what many call the "Weyl-Minkowski theorem", which Bruns/Gubeladze instead attribute to Motzkin, so the attributions might still be in conflict.  In any case, it makes it hard to look up a reference.

If we've already proven the above theorem, then your question is rephrased as "Is the intersection of two polytopes itself a polytope?"  The answer to this is obviously "yes," as the intersection of two bounded sets is bounded and intersecting an intersection of finitely many closed [affine] half-spaces with another intersection of finitely many closed [affine] half-spaces is trivially an intersection of finitely many closed [affine] half-spaces (which is a whole lot of a words to basically say "finite + finite = finite")

The problem then is in proving this theorem.  Of course, Bruns/Gubeladze prove it in the above book, but they develop quite a few tools in the previous sections to make their proof succinct, so if you want to see their proof, I'll direct you to the book.
To prove it from first principles, the following sketch should work:

$(\Rightarrow)$ By definition, there is some positive integer $N$ and for any $1\leq i \leq N,\lambda_i \in \mathbb{R}^n, b_i \in \mathbb{R}$ such that $$P = \{x \in \mathbb{R}^n : \lambda_i \cdot x \leq b_i, \forall i\}$$  For any $J \subseteq \{1,\ldots,N\},$ define $F_J = P \cap \{x \in \mathbb{R}^n : \lambda_j\cdot x = b_j, \forall j \in J\},$ and let $V$ denote the set of $\subseteq$-minimal elements of $\Big\{F_J : J \subseteq \{1,\ldots,N\}\Big\}\setminus\{\emptyset\}.$  Using the assumption $P$ is bounded and every affine linear subspace of positive dimension is unbounded, we can show $V = \{\{x_1\}, \ldots, \{x_m\}\}$ is a set of singletons.  Now consider the convex hull of these points, which is immediately a subset of $P$ itself.  This leaves showing $P$ is a subset of the given convex hull, which is a little tedious, but probably would work best by induction, showing each $F_J$ is the convex hull of some subset of $V.$
$(\Leftarrow)$ Obviously the convex hull $P$ of a finite set $V$ is bounded, so we would need to show $P$ is a polyhedron.  Toward this end, we may assume $V$ is minimal (if we remove any point, the convex hull will be strictly smaller), and since an affine subspace of $\mathbb{R}^n$ is the finite intersection of closed affine half-spaces (by the existence of an orthogonal basis) we may reduce to the case that the affine subspace spanned by $V$ is all of $\mathbb{R}^n.$  Now just note that there is an affine linear map taking the $(|V|-1)$-simplex onto the convex hull of $V.$
Answer: First, note that the image of a convex hull of a finite set under a linear (affine) map is also the convex hull of a finite set ( Hint: consider the images of the generators).
Consider now two finite sets of points $\{P_i\}_{1\le i\le k}$ and $\{Q_j\}_{1\le j\le l}$ in an affine space. Consider the set of points in $\mathbb{R}^{k+l}$ described by
$$\begin{eqnarray}
\sum \lambda_i P_i = \sum \mu_j Q_j \\
\sum \lambda_i = \sum \mu_j = 1 \\
\lambda_i, \mu_j \ge 0\\
\end{eqnarray}$$
It is easy to see that the intersection of the convex hulls is the image of this set under the map
$$(\lambda_i, \mu_j) \mapsto \sum \lambda_i P_i$$
Now we finish by proving :
Let $m, n\ge 1$ natural numbers, $A \in M(\mathbb{R}, m\times n)$ a matrix of size $m \times n$ with real entries, $b \in \mathbb{R}^m$. Consider the subset of unit cube in $\mathbb{R}^n$ defined by
$$\begin{eqnarray}
A \cdot x = b \\
0\le x_i \le 1
\end{eqnarray}$$
If the above set is not void then it is the convex hull of a finite subset of itself.
The proof is by induction on $n$. If $n=1$ it is easy. Assume true for all $n-1\ge 1$. If our subset has only one point, done. Otherwise, take a point $X$ and another one $Y$ in the set. The line $XY$ intersects the boundary of the cube in two points $X'$, $X''$ such that $X$ is in the segment $X'X''$. Now for each intersection of the set with a face of the we have the induction hypothesis ( it is basically a subset of $\mathbb{R}^{n-1}$, see also the observation at the very beginning of the proof). I say we are done.


How to get $nid inside hook_menu_alter function

Question: I'm trying to show or hide a menu tab based on whether my node meets a certain condition. In my hook_menu_alter I can't seem to get the $nid even though I was under the impression that the menu_alter fired after node load...
I've been googling for a day now and trying different solutions, but just can't seem to access the $nid.
When I print arg(0) or $_GET['q'] I get the result "admin_menu/flush-cache" instead of "node/62" even though I'm on a node page... what am I missing?
Answer: Menus are cached; unless you have something funky going on, loading a node won't rebuild that cache (it would be frightfully expensive to do so).
You need to make 'live' decisions in a callback, e.g.
<code>function MYMODULE_menu_alter(&$items) {
  $items['foo']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  $node = menu_get_object();
  if ($node && $node->bar) {
    return TRUE; // Allow access.
  }

  return FALSE; // Default for anything that doesn't match your criteria.
}
</code>
The above is a contrived example, real-world will be different depending on exactly what you need to do.
Comment: Seems like there's another way to pass the $nid to the access callback instead of meny_get_object if all you need is the $nid. Add this to the menu $items:
`$items['foo']['access arguments'] = array(2),`  and then receive the nid: `function MYMODULE_access_callback(nid) {`


$f$ Open, Closed and continuous but not a local homeomorphism

Question: Give an example of topological spaces $X$ and $Y$ and a map $f: X \to Y$ that
$f$ is an open, closed, and continuous but not a local homeomorphism.
(The map and the topological spaces have to satisfy these 4 characteristics simultaneously)
Comment: HINT: There is a simple example with $X=[0,1]\times[0,1]$ and $Y=[0,1]$.
Answer: Let $f: [0,1] \times [0,1] \to [0,1]$, all in the usual topology, be given by $f(x,y)=x$ (the projection).
$f$ is open and continuous, as all projections are.
$f$ is closed as the domain is compact and the codomain is Hausdorff.
$f$ is not a local homeomorphism for dimension reasons, basically. Or: all open sets in the domain cannot be disconnected by removing a point, while (basic) open sets in the codomain can be, so they can never be homeomorphic.


Solving over-determined systems of quadratics in 3 dimensions

Question: I have a 3x3 symmetric matrix $M$ with known components $M_{ij}$. I'd like to find a vector $x$ which has the following relationship with $M$
$$ M_{ij} = x^T E_{ij} x$$
Where $E_{ij}$ is also a 3x3 matrix with known components
$$ E_{ij} = \begin{bmatrix}
\epsilon_i^0 \epsilon_j^0 & \epsilon_i^0 \epsilon_j^1 & \epsilon_i^0 \epsilon_j^2\\
\epsilon_i^1 \epsilon_j^0 & \epsilon_i^1 \epsilon_j^1 & \epsilon_i^1 \epsilon_j^2\\
\epsilon_i^2 \epsilon_j^0 & \epsilon_i^2 \epsilon_j^1 & \epsilon_i^2 \epsilon_j^2\\
\end{bmatrix} $$
The $\epsilon_m^n$ are almost Kronecker delta symbols, i.e. small if $m \ne n$, nearly 1 otherwise. In addition, I know the length of the 3 vector $x$, so if I break this down, I have 7 equations to solve for 3 unknowns (six from the distinct $M_{ij}$, and one $|x| = r$).
If I expand those 6 equations out, they yield a generic system of quadratics in 3 variables (all possible terms present), which seems to not have a general solution based on this question.
However, there are a few key differences. My problem has more than double the number of conditions than variables and I have the extra 7th condition for the length, also I'm only interested in the case for 3 dimensions.
If I set the off-diagonal $\epsilon$ to 0, I get an approximation that is not good enough unfortunately. I'm currently trying to throw away terms with two small $\epsilon$ (i.e. two off diagonals), but haven't had too much luck with that either so far. Does anyone have any ideas about how one could solve this system?  I'm thinking there might be some way to get an iterative approximation?
Thanks!
Answer:
My problem has more than double the number of conditions than variables and I have the extra 7th condition for the length

This is very restrictive. Indeed, let $x=(x_0, x_1, x_2)$ and $\epsilon_k=(\epsilon_k^0, \epsilon_k^1, \epsilon_k^2)$ for each $k=1,2,3$. Then for each $i$, $j$ we have
$$M_{ij}=\sum_{m, n=0}^2 x_mx_n\epsilon^m_i\epsilon^n_j=\left(\sum_{m=0}^2 x_m\epsilon^m_i\right)
\left(\sum_{n=0}^2 x_n\epsilon^n_j\right)=(x,\epsilon_i)(x, \epsilon_j) .$$
That is $M=XX^t$, where $X=((x,\epsilon_0), (x,\epsilon_1), (x,\epsilon_2))^t$. In particular, the matrix $M$ should have rank at most $1$ . Moreover, for each $i$ we should have $M_{ii}=(x,\epsilon_i)^2\ge 0$. Then  $(x,\epsilon_i)=\pm\sqrt{ M_{ii}}$. We should chose the signs assuring $\operatorname{sign}(x,\epsilon_i)\cdot   \operatorname{sign}(x,\epsilon_i)= \operatorname{sign} M_{ij}$ for each distinct $i$ and $j$. Satifying the conditions we obtain at most eight possiblities for the matrix $X$.
Let $F$ be a $3\times 3$ matrix whose rows from the top to the bottom are $\epsilon_0$, $\epsilon_1$, and $\epsilon_2$. Then $Fx=X$. When $\epsilon_m^n$ are sufficiently close to
Kronecker $\delta$-symbols then the matrix $F$ is non-singular by Levy–Desplanques theorem, so then $x=F^{-1}X$.
Comment: Thanks, this looks like a good solution. I also think I managed to find a way to solve it by treating each variable ($x^2, y^2, z^2, xy, xz, yz$) as an independent variable and solving it with row reduction like a linear system. So that's another way if someone else comes by one day. Your solution seems like it be more interpretable.


How to delete all nodes referencing a given one?

Question: I'm working on a catalog based on Drupal Commerce. I have a product display content type referencing product entities. I'm thinking about the ways to make life of a content manager easier.
I made a rule which fires when product is created and creates a corresponding Product display. But I can't figure out the best way to delete a product display nodes when the product is deleted.
Till now I've tried VBO, but seems in Drupal 7 rules2 lacks the ability to run VBO actions.
I guess a quick and dirty solution is to write a module for this task, but I'm looking for something more elegant. Any ideas?
Comment: A note for anyone reading this a bit later than Jun 1st, VBO now provides a way for Rules to load its result set (list of entities), on which you can then run your actions / rules, giving you a more elegant way of "running VBO actions". This happened in VBO 7.x-3.0-beta1, released on July 16th.
Answer: I think a "quick and dirty" module would be the more elegant way. I did something similar recently in drupal 6 with ubercart. I have a content type that sometimes needs to be associated with a product and sometimes doesn't. When one of the custom nodes is deleted, if it has a product associated with it, that needs to be removed as well:
your_module_nodeapi(&$node, $op) {
  if($op == 'delete') {
    $product_nid = db_result(db_query('SELECT nid FROM {content_type_product} WHERE field_product_list = %d', $node->nid));
    if(!empty($product_nid)) {
      node_delete($product_nid);
    }
  }
}

In this case, field_product_list was a node reference field added to the product. I'm sure something similar would work in your case.
Comment: This won't work for D7.
Answer: Just to add to @David_L's answer, and extending the scenario of the problem.

The example below makes use of EntityFieldQuery.
I point out that nested entity references can be handled hook_node_delete() by simply adding another IF, there is no need to write a sub-loop as the hook is called for each deletion.
<?php
function mymodule_node_delete($node) {
    if ($node->type == 'product'){// if a product is being deleted

        $query = new EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'product_display')
                        ->fieldCondition('field_product', 'target_id', $node->nid)
                        ->execute();
        if(!empty($result['node'])){
            $nids = array_keys($result['node']);
            node_delete_multiple($nids);
        }
    }

    if ($node->type == 'product_display'){// if a product's display is being deleted

        $query = new EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'product_display_child')
                        ->fieldCondition('field_product_display', 'target_id', $node->nid)
                        ->execute();
        if(!empty($result['node'])){
            $nids = array_keys($result['node']);
            node_delete_multiple($nids);
        }
    }
}
?>

Answer: This might not be the best solution but I am using the below:
Also, you can do delete mutiple.
    /**
     * Implements hook_node_delete().
     */
    function my_module_node_delete($node) {
      // Gets the node type for the newly deleted node.
      $node_type = $node->type;
      $node_id = $node->nid;
      // Everything happens only if the node is
      // of type mytype.
      if ($node_type == 'mytype') {
        // Find all nodes that reference this node in the custom import reference field.
        // the table name is for the field that keeps the reference.

        $find_nodes = db_select('field_data_field_import_reference', 'f')
          ->fields('f', array('entity_id'))
          ->condition('f.bundle', 'myotherbundle', '=')
          ->condition('f.field_import_reference_target_id', $node_id, '=');

        try {
          // Execute query.
          $resulting_nodes = $find_nodes->execute()->fetchAll();
        }
        catch (Exception $e) {
          // Or catch exception.
          $error_message = $e->getMessage();
          watchdog('mymodule', $error_message);
        }
        // If we have nodes to delete.
        if (isset($resulting_nodes)) {
          // Get the nid for each.
          foreach ($resulting_nodes as $delete_node) {
            // Delete by nid.
            node_delete($delete_node->entity_id);
          }
        }
      }
    }

Answer: The following has been borrowed from here.
Insert the following into your custom module.
/**
 * Implements hook_node_delete().
 */
function mymodule_node_delete($node) {
  if ($node->type == 'mynodetype'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}


If $X \sim$ unif$(0,1)$, what is the distribution of $U=\max \{X,1-X \}$?

Question: Let $X$ be uniformly distributed in $(0,1)$ and set $U=\max \{X, 1-X\}$. How can I find the distributiopn of $U$?
My first thought was to consider this a mixture distribution problem and use the CDF technique as follows:
$$F_U (u)= P\left( U \leq u \right)=P\left( U \leq u , U=X \right) +P\left(U \leq u, U=1-X \right)$$
and then proceed accordingly.
That approach turns out to be incorrect but I do not quite understand why.
I would be grateful therefore if someone could firstly point out the gap in my syllogism above and then present an appropriate way to deal with this kind of problems.'
Thank you.
Comment: No. You have to express the event in terms of $X$ only: note that $P(U\leq u, U=X) = P(X \leq u, X>\frac12)$, and you easily have the value of this probability by considering separately the cases $u\leq \frac12$ and $u>\frac12$.
Comment: I don't see anything wrong. You can write $U=X$ as $X < 1-X$ i.e. $X<\frac12$ and contiinue...
Comment: @StéphaneLaurent Yes, I thought so too but the distribution of $U$ turns out to be uniform on $(0,1)$ this way. The correct answer though is uniform on $(0.5,1)$.
Comment: @StéphaneLaurent Isn't it $P(U \leq u, U=X)= F_X(u) \times P(X \geq 1-X)$?
Comment: @StéphaneLaurent That was subtle, thank you. I hadn't realized this  works only for events concerning $X$. Feel free to post this as an answer, so I can mark it as the correct one.
Answer: $U$ is not a mixture of $X$ and $1-X$ because they are not independent.

One general way to deal with such problems, when a random variable $X$ is transformed according to some definite procedure into another random variable $U$, is to compute the cumulative distribution function (CDF) of $U$.  To illustrate, let's do that with this example.
The first step is to find the support of the new variable: what values can it take on? Because almost surely $X\in [0,1]$, we compute that $U\in [1/2,1]$.  An easy way to carry out this calculation is to plot the graph of $u = \max(x, 1-x)$ for $0\le x\le 1$ and inspect the range of heights it attains.

The range of this graph spans all $u$ values between $1/2$ and $1$: those are the ones for which the CDF must be calculated.
The second step is to compute the CDF for arguments in the support.  This usually proceeds in two stages.

Substitute a function of $X$ in place of $U$. The CDF of $U$ for  $u\in[1/2,1]$ is, by definition,
$$F_U(u) = \Pr(U \le u) = \Pr(\max(X, 1-X)\le u).$$
Evaluate the chance of the resulting event.  This usually requires some algebraic manipulation but often does not require any use of probability or Calculus.  Here
$$\{x \big| x\le u, 1-x\le u\} = \{x \big|1-u \le x\le u\} = [1-u, u].$$

Putting these two results together (plugging (2) into (1)) yields
$$F_U(u) = \Pr(X\in [1-u,u]) = F_X(u) - F_X(1-u) = u-(1-u) = 2u-1.$$
In some tricky cases (where $U$ has neither a continuous nor an entirely discrete distribution) it is important to evaluate the CDF at all real numbers.  (An example is worked out at Distribution function of maximum of n iid standard uniform random variables....) In the present case, because the values just computed for $F_U(u)$ range from $0$ at $u=1/2$ through $1$ at $u=1$ and any CDF must be a nondecreasing function, the remaining values of $F_U$ are completely determined: $F_U(u)=1$ for $u\gt 1$ and $F_U(u)=0$ for $u\lt 1/2$.
The job is done.  In many circumstances the resulting distribution might not be recognizable, but this one evidently is the CDF of a Uniform$(1/2,1)$ distribution.
Comment: Wonderful! Thank you very much for this great answer.
Answer: $U=\max{\left(X,1-X\right)} \sim \mathcal{U}(0.5,1)$
Because if $X > 1-X$  (i.e. if $X > 0.5$), then $U \sim \mathcal{U}\left(0.5,1\right)$, and if $1-X > X$  (i.e. if $1-X > 0.5$), then $U \sim \mathcal{U}\left(0.5,1\right)$ also.
Plus, simulation:
X<-runif(100000)
U<-pmax(X,1-X)
hist(U)
Comment: Thank you. Yes I understand why the correct answer is uniform on $(0.5,1)$. I do not understand though why my approach is incorrect.
Comment: I think $P(U≤u,U=X) = 0$ when $U\ne X$ and $P(U≤u,U=1-X)=0$ when $U \ne 1-X$, so I do not see the error. What error are you seeing?
Comment: Why are these probabilities zero? I have been using the fact that: $P(U \leq u, U=X)= F_X(u) \times P(X \geq 1-X)$
Comment: Just musing. . . (sans caffeine, just woke up :).
Comment: Well good morning, lol.


The squared-norm of the projection of a Gaussian vector onto an independent $d$-dimensional subspace is a $\chi^2_{d}$

Question: How we can prove that:
The squared-norm of the projection of a $N$-dimensional complex vector with i.i.d. unit-variance and zero mean Gaussian components onto an independent $d$-dimensional subspace is a $\chi^2_{d}$. This projection can be represented as $|v^* \,h|^2$, where $h$ is the Gaussian vector and $v$ is the vector in the direction of the projection.
Comment: Please double check your result. The correct conclusion is the projection is a $\chi_d^2$ random variable, and if the normal vector is not of mean $0$, then this chi-square random variable has noncentrality parameter.
Comment: But the truth is $\chi_d^2$, think about the simplest case, project a standard normal random variable  $Z$ onto $\mathbb{R}^1$ (which means the projection is $Z$ itself), what is the distribution of $Z^2$? $\chi_1^2$ or $\chi_2^2$?
Comment: Question edited. I think it is $\chi^2_{2d}$ and not $\chi^2_{d}$.
Comment: Please check [this](https://en.wikipedia.org/wiki/Chi-squared_distribution#Relation_to_other_distributions).
Comment: What's your point? Did you consider my example carefully?
Comment: Just to say that in your case $Z^2$ has a $\chi_2^2$ distribution and not $\chi_1^2$
Comment: How many normal random variables do we have in my example? $1$ or $2$?
Answer: A mathematics-inclined proof, may need some background of linear algebra
For clarity, let's assume the whole space is $\mathbb{R}^N$ for which we shall consider as an $N$ dimensional vector space and the subspace is $M$ with $\dim(M) = d \leq N$. Let $\{u_1, \ldots, u_d\}$ be an orthonormal basis of $M$, which may be extended to an orthonormal basis $\{u_1, \ldots, u_d, u_{d + 1}, \ldots, u_N\}$ of $\mathbb{R}^N$.
Treat $X \sim \mathcal{N}_N(0, I)$ as a vector in $\mathbb{R}^N$, the projection of $X$ onto $M$ can be expressed as
$$P_M X = \sum_{i = 1}^d (X^T u_i) u_i.$$
By orthogonality of $\{u_1, \ldots, u_d\}$, we have
$$\|P_MX\|^2 = \sum_{i = 1}^d (X^T u_i)^2.$$
Also note that for every $(u_1^T X, \ldots, u_d^T X)^T = (u_1^T, \ldots, u_d^T)^T X \sim \mathcal{N}(0, I)$ by the orthogonality of $\{u_1, \ldots, u_d\}$ and the linear transformation property of normal random vectors, thus $X^T u_i \sim \mathcal{N}(0, 1)$ and are mutually independent, consequently, by definition,
$$\|P_M X\|^2 = \sum_{i = 1}^d(X^T u_i)^2 \sim \chi_d^2.$$
Comment: Mat, it is essential that you stipulate that in your question.  If $X$ is complex it certainly isn't "standard" in any conventional sense and "$N$-dimensional" becomes ambiguous: $N$ complex dimensions or $N$ *real* dimensions?
Comment: But in my case $X$ is  complex.
Comment: @whuber Question edited. Hope it is clear now. (N complex dimensions)
Comment: This answer is still valid: when it was written, the symbol "$N$" referred to the number of *real* dimensions. Now that you have changed the meaning, you have to read "$2N$" everywhere in place of "$N$" and "$2d$" in place of "$d$" in this answer.
Comment: "$N$-dimensional complex vector" is a weird wording, if you are talking about "complex", then the dimensionality is $2$, can't be others.


How do I get the full URL of the current page?

Question: I need to get the full URL of the currently opened page. I use the following code, but it returns http://localhost/mysite/page_name.
$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

It's not enough for my code to complete; I want to get the values that are passed with the URL as http://localhost/mysite/page_name/value1=value&value2=value.
How can I do that?
Answer: Have you tried using request_uri()?
$_SERVER['HTTP_HOST'] . request_uri();

It should do the trick. I haven't tried it myself, and I may be off a bit, but I suggest you give a try.
From JavaScript, you could use the window.location.href variable.
Comment: @abd You're probably looking for `$_SERVER['QUERY_STRING']`
Comment: great trick i used $_SERVER['REQUEST_URI'] to get the url but the when i print the url:
sitename/pagename?field_empf_salaryfrom_tid=All&field_emp_date_value[value][year]=&field_emp_date_value[value][month]=

How can i remove sitename/pagename
Comment: Can i Put every value from the url in a variable?
Like
the value of (field_empf_salaryfrom_tid=All) in $s
Comment: I suggest adding  protocol to the answer  with `isset($_SERVER["HTTPS"]) ? 'https' : 'http';`
Comment: `request_uri()` even works on 404 pages, that's a really good thing.
Answer: Here's how to get the absolute URL for the current page, using the Drupal API:
$current_url = url(current_path(), array('absolute' => TRUE));

If you need the extra (non-q) querystring parameters as well, you can use:
$current_url = url(current_path(), array(
  'absolute' => TRUE,
  'query' => drupal_get_query_parameters(),
));

Answer: You can use the following code.
global $base_root;
$current_url = $base_root . request_uri();
echo $current_url;

Answer: Try $base_url variable, provides Drupal installation URL without "/" and current_path() it returns path of current page being viewed.
global $base_url;
$current_path = $base_url . '/' . current_path();

Answer: The question is pretty old but chiming in for people that might get there for a more recent version of Drupal.
You can get the current full-path for a page with:
$path = \Drupal::service('path.current')->getPath();
$queryParams = \Drupal::request()->query->all();

$path . "?" . http_build_query($queryParams);

Really handy for dynamically changing the value of certain query parameters like a page for example.
Answer: I think the best way to do that is using url() API like this
url('your/drupal/path', array('absolute' => TRUE));

Comment: The question is asking for a generic page, not one for which the path is known.
Comment: Ok, you can replace `your/drupal/path¡`with `current_path()`, as @david-thomas wrote before.


Using async with .Net 4 and ms.bcl.async

Question: I've imported ms.bcl.async nuget package with my .Net 4 project and started to write code using async/await. I've got strange error message trying to await a Task returning method.

I'm at a loss here since .Result() works, but await does not. Also this code is supposed to run on Windows Azure 1.8 (old SDK version). Got no ideas how to proceed unfortunately.
How it compiles (did not test yet):
Comment: I would clean my solution, remove references, add them again and re-build as a first attempt.
Comment: That is because the return type of client.SendAsync() is void..
Comment: Nope, problem is in the await keyword. See the second picture. The return value is awaitable Task
Comment: What VS Project is this? Class Library?
Comment: The return type of your anonymous Lamba expression there..?
Should it be async Task ()=> instead of async ()=>
Comment: How are you getting `HttpClient` on .NET 4.0? did you install the MSFT package from NuGet?
Comment: @YuvalItzchakov - Output : Class Library, Target Framework : .Net 4. Its a web project. Can you be more specific about MSFT please?
Comment: @bit Lambda is not to blame - same error when problem code is moved out of it.
Comment: @YuvalItzchakov Man, clean worked, please add and answer if you wish and I will select it as an answer, thanks!
Answer: As i said in the comments, this looks like a a build issue more than a library issue.
I would clean and re-build my solution as a first attempt at fixing these kind of problems.


Forecast models of differenced/undifferenced data?

Question: I am building different forecasting models on my time series (which is not stationary). Some models require stationarity, others don't. My goal is to test a few models on a training set, compare the forecasts to the observed values (the test set), and see which model was the most accurate in forecasting.
However, as I am differencing my data for some models only, when I'm trying to compare the forecasts I obviously end up with different type of output (differenced vs. undifferenced). How should do we usually proceed at this point? Is there a way to revert back my forecasts to "undifferenced" data (in R)?
In know that with ARIMA, it's easy as I can simply ask ARIMA to difference it for me. But when I difference manually using diff()before forecasting using ETS(), then it's a different story. I only difference once by the way.
Thank you!
Comment: ....................................
Answer: You should compare your models on identical tasks. If your goal is to forecast levels, then each model must produce a forecast of the level to compare with the others. If one of your models naturally produces a forecast of some transformation of the data, you have to invert it to do this comparison.
If the transformation is differencing, the opposite transformation is the cumulative sum. You can see this by the telescoping sum:
$$\sum_{i=1}^t (X_i - X_{i-1}) = X_t - X_{t-1} + X_{t-1} - \ldots - X_1 + X_1 - X_0 = X_t - X_0$$
So then
$$ X_t = X_0 + \sum_{i=1}^t \Delta X_i$$
Similarly, the level forecast for $t+h$ made at $t$ is:
$$ \hat{X}_{t+h} = X_t + \sum_{i=1}^h \Delta \hat{X}_{t+i}$$
In R, you can do this with the function diffinv. You have to pass in the very last point of the data as the argument xi.
Answer: If you are going to conduct that test of evaluating forecast form 1 and only 1origin , I would SERIOUSLY suggest that you evaluate accuracies from multiple origins where the model developed for the history may change as you have add new observation to the history. One origin for each series is always just 1 sample.
Differencing is just 1 part of a model which could contain ARMA structure . level shifts , time trends , seasonal pulses while incorporating remedies for non-constant parameters and remedies for non-constant error variance.
Select your tools of choice and compare the ensemble accuracy from a number of origins for each tool. Your tools should always include a provision for detecting anomalies and provision for delivering ROBUST estimates of the model form/parameters including testing the assumptions of the model form. If the tool doesn't do that then discharge that tool.


Prove that Ito process $dX_t=a(t)dt+b(t)dW_t$ is a martingale $\iff$ $a=0 dP\times dt$

Question: We have: $W_t$ - Wiener process, $b\in M_{[0,T]}^2=\left\{f:[0,T]\times\Omega\to\mathbb{R}:\text{f is adapted}, E\left(\int_0^Tf^2(t)dt\right)<\infty\right\}$,
$a:[0,T]\times \Omega\to \mathbb{R}$ process adapted to filtration $\{F_t\}_{t\ge 0}$ such that $\int_0^TE|a(t)|dt<\infty$
Prove that Ito process $dX_t=a(t)dt+b(t)dW_t$ where $E(X_0)<\infty$ is a martingale $\iff$ $a=0 dP\times dt$
I can't find anywhere a complete proof of this theorem, written in an accessible language :(
Comment: what does "$a=0dP\times dt$" actually means? that it's equal $0$ a.s. ($dP\times dt$)?
Comment: yes exactly :))
Answer: Assume $(X_t)$ is a martingale, under your assumptions regarding $b$ the process $M_t=X_0+\int_0^t b dW_s$ is a martingale as well. The linear combination between martingales is again a martingale hence
$$X_t-M_t=\int_0^t a(s) ds$$ is a martingale.
This process has bounded variation and continuous sample path,  it's a well known result that a martingale satisfying this two conditions is constant, and hence the $a=0$. The other direction is immediate.
Comment: $M_t=X_0+\int_0^t b dW_s$ is a martingale because $E(X_0)<\infty$ and $X_t$ - martingale? And then process $X_t-M_t$ has bounded variation because $\int_0^TE|a(t)|dt<\infty$?


'remote move' via FTPS

Question: I'm using FTPS to transfer some files from one remote server to another.
Now would I like to move files locally on one server, from one folder to another. More concrete: after moving the files from [remote server 1] to [remote server 2] I want to move all the files with extension .csv to the folder done.
I found the 'rename' command but there is no 'rename all' function like:
rename *.csv ../done/*.csv

Thanks in advance!
Comment: Do you have an SSH access to the machine? That would make it much easier.
Comment: yes sure, sort of! It's a win2008 machine which I have remote access to
Answer: Using * as a wildcard like you're doing is known as globbing. Globbing is often only available for local files through FTP, not remote ones. Some clients do glob remote FTP commands but, generally only the m* ones (mdelete, mget etc.)
Have a look at your clients glob command.
Also, globbing the way you asked in the question won't work, it would be:
rename *.csv ../done

I have a feeling you'll need to script it or do it manually because FTP is suited to that, not hand moving stuff around.
Comment: I'd hoped... But this command failed

'remote move' via FTPS


How to convert a string to an existing object in Groovy?

Question: How to call its methods if I only know the literal name of the existing object?
For example:
class Cat {
    def bark() {
        println "I am a cat."
    }
}

class Dog {
    def bark() {
        println "I am a dog."
    }
}

def cat = new Cat()
def dog = new Dog()

def animal = 'cat'
"${animal}".bark() // Error

As below, I only know the name of the animal (maybe cat or dog). How do I use this object?
Answer: if the cat and dog are defined as fields, you can use this:
this."${animal}".bark()

or
this[ animal ].bark()

Answer: def animals = [
  cat: new Cat(),
  dog: new Dog(),
]

def name = 'cat'
animals[name].bark()


Am I over thinking this 5th grade coin flipping homework problem?

Question: Looking over my daughter's homework, I had a question that seems best to be asked here.  It's from Everyday Mathematics (Volume 1, Grade 5, p 42.)

Tim flipped a coin 10 times.  It landed heads up 7 times and tails up
  3 times.  Tim said, "I'll flip it 4 more times to get the same number
  of heads and tails."  Is he right?  Explain why or why not.

My gut tells me the new 4 flips will be 50/50 yielding 2 heads and 2 tails and won't take into account the previous flips.  However, maybe they all land on heads giving a 50/50 overall distribution.  Am I letting my knowledge of the Monty Hall Problem confuse me?
Comment: None of my close coin friends even **remember** what they did when they were previously flipped, let alone decide to make up for any excess of heads that they produced in the past.
Answer: We're supposed to understand that Tim thinks the coin must come up heads in the next four throws, because otherwise the total outcome of the 14 throws wouldn't be 50/50. This is a fallacy, of course.
However, your gut is guilty of the same fallacy when it thinks that the next 4 throws have to be 50/50. Possibly your gut is confusing the expected number of heads with the possible actual numbers of heads. But the problem does not seem to be about expected results -- Tim's problem is that he thinks probabilty can ever guarantee him any result.
Answer: If there are 4 more heads than tails accumulated, and the coin is flipped several more times, then the chance of the excess falling to $4-k$ is the same as the chance of it rising to $4+k$ heads (for every possible $k$).  There is no statistical tendency favoring a reduction of the excess by additional flips of the coin.
There does exist a tendency to push the ratio (total heads)/(total tails) toward 1 with more coin flips.  Maintaining a 7:4 ratio for another 110 flips would be extremely unlikely.  This is not a result of the coin remembering its past history but of the nature of ratios compared to differences.  To maintain a 7:4 ratio or stay close to it one would need to get about 70 heads and 40 tails.  But outcomes with equal or nearly equal numbers of heads and tails are more likely so that ratios further from 1 are disfavored for a large enough set of coin flips.
(Assuming a fair coin)
Answer: Your gut is right. My interpretation is that Tim is thinking that the coin will somehow magically restore itself back to having the same number of heads and tails, since it's a fair coin. But of course you know that coins don't do that.
There's nothing that forces the coin to give two heads and two tails in the next four flips, though -- the flips are independent -- but certainly four heads in the next four flips is not the most likely outcome.
Comment: Tim's thinking is especially naive, because why didn't he think the same thing after six flips, when the results were (say) 5 heads and 1 tails? If his theory is that the coin will conspire to even itself out, then he's already disproved that theory. (unless 14 is an especially magic number for him....)


about the definition of connected sets in $\mathbb R^n$

Question: (Edited to make reference to the topological space $X$ precise.)
A subset $A$ of a topological space $X$ is connected if there are no two open subsets $O_1$ and $O_2$ of $X$ such that (a) $A \subseteq O_1 \cup O_2$, (b) $A \cap O_1 \neq \emptyset$, (c) $A \cap O_2 \neq \emptyset$,
and (d) $A \cap O_1$ and $A\cap O_2$ are disjoint.
Call the subset $A$ brown if in the definition above, we replace (d) by (d') $O_1$ and $O_2$ are disjoint.
The definitions imply that every connected set is brown.
The opposite is not true: take the topological space $X = \{1,2,3\}$, where a subset of $X$ is open if it contains 1 or if it is the empty set. The set $A = \{2,3\}$ is not connected yet it is brown.
My question is whether for sets in the Euclidean space $X = \mathbb R^n$ (with the standard Euclidean topology), connectedness and being brown are equivalent.
Comment: (In general, we define connectedness for topological spaces, not for subspaces. But I understand, for the purposes of this question, we are defining it otherwise.)
Comment: What have you tried? You would need to know that if $O_1,O_2$ cover $A$ with $A\cap O_1\cap O_2=\emptyset,$ then we can find $O_1',O_2'$ with $O_1'\cap O_2'=\emptyset.$
Comment: @Thomas Andrews: it says "$A$ *is* connected, if ...". Well perhaps it should be "*iff*", but apart from this, it is just an easy observation, where $A$ connected is to be understood in the usual sense. So, it's not a definition!
Comment: Why did you call this property "brown"? Since it's quite an unusual name, did you find this notion somewhere? I know of "Brown spaces" (see, e.g., [here](https://medcraveonline.com/OAJMTP/brown-spaces-and-the-golomb-topology.html), but I guess this has nothing to do with the above property?
Comment: @Ulli: I chose "brown" at random, because I like the color. Since it is an ad hoc notion, I did not want to term it in a way that resembles connectedness, so as people do not think this definition is actually used.
Comment: @Eilon: Ok, I see. Thank you for the clarification.
Answer: In at least metric space, any brown set is connected.
Let $A$ be not connected. Let $O_1$ and $O_2$ be open in $X$ sets such that $O_1 \cap A \neq \varnothing$, $O_2 \cap A \neq \varnothing$, $A = (O_1 \cap A) \sqcup (O_2 \cap A)$.
For $x \in A \cap O_1$ let $f(x)$ be such that $B_{f(x)}(x) \subset O_1$, for $x \in A \cap O_2$ let $f(x)$ be such that $B_{f(x)}(x) \subset O_2$.
Then $O_1' = \cup_{x \in A \cap O_1} B_{f(x) / 2}(x)$ and $O_2' = \cup_{x \in A \cap O_2} B_{f(x) / 2}(x)$ are disjoint and form cover of $A$, thus $A$ is not brown.
To prove disjointness, assume $p \in O_1' \cap O_2'$. Then for some $x \in A \cap O_1$ and $y \in A \cap O_2$ we have $\rho(x, p) < f(x) / 2$ and $\rho(y, p) < f(y) / 2$. Wlog assume $f(x) < f(y)$, then $\rho(x, y) < f(x) / 2 + f(y) / 2 < f(y)$, but then $x \in B_{f(y)}(y) \subset O_2$ and thus $x \in A \cap O_2$ also, which contradicts disjointness of $A \cap O_1$ and $A \cap O_2$.
I think some separation axiom should be also enough for this, but not sure.
Comment: Many thanks, @mihaild.


Finding the distribution of first arrival time in a mixed Poisson process

Question: Long time reader, first time writer here. I am dealing with a very specific type of an exercise in stochastic processes.
Calls are arriving according to the renewal process, where interarrival times are a mix of $Exp(λ)$ with the weight $1/3$ and $Exp(2*λ)$ with the weight $2/3$.
Telephone operator decides to go on a strike and to respond to a call with probability $p$, independently from everything else. Find distribution and expected value of the first responded call $T_1$.
So here's how far I have come. Calls are arrivals of the process, they are distributed as follows: $T' ∼ \frac{1}{3} * Exp(λ) + \frac{2}{3} * Exp(2λ)$. The operator throws a coin at each arrival, the coin shows heads with probability $p$ and tails with probability $(1-p)$. If the coin shows heads, the operator will accept the call - meaning that we can count the arrival in our process and $T_1 | heads ∼ T'$.
If the coin shows tails, the operator will not accept the call and the process will restart from the beginning. I am struggling to find the conditional distribution of $T_1 | tails ∼$ ?
I'm thinking it's something like $$T_1 | tails ∼ T' + p * T_1 | heads + (1-p) * T_1 | tails,$$ however I doubt that that is correct.
Answer: (Partial answer)
Let $S_n$ be the sequence of renewal times, which have interrenewal distribution
$$
f(t) = \frac13 \lambda  e^{-2 \lambda  t} \left(e^{\lambda  t}+4\right), \ t>0.
$$
Let $N$ be the first call that the operator accepts, then $N\sim\mathsf{Geo}(p)$ and by Wald's identity the mean time of the first responded call is
$$
\mathbb E\left[\sum_{n=1}^N S_n\right] = \mathbb E[N]\mathbb E[S_1] = \frac1p\cdot\frac{2}{3 \lambda }= \frac 2{3\lambda p}.
$$
The distribution of $T_1$ could be computed by the law of total probability:
$$
f_{T_1}(t) = \sum_{n=1}^\infty f_{T_1\mid N=n}(t)\mathbb P(N=n),
$$
but I was not able to find a tractable closed form for the density of $T_1$ conditioned on $N=n$ (that is, the $n$-fold convolution of the interrenewal density).


React: Exibir HTML em modal React Boostrap

Question: Estou desenvolvendo uma SPA em React para um evento e preciso consumir uma pasta com arquivos HTML e exibi-los em um modal do React Boostrap, basicamente tenho uma seção onde é exibida todos os palestrantes conforme ilustrado em print abaixo:

Eu precisa fazer uma requisição para a pasta com os currículos dos palestrantes (que fica na pasta public do projeto criado com create-react-app) e exibir no modal o HTML com o currículo do palestrante e tenho um exemplo que fiz em ASPNET: http://interleite.com.br/#palestrantes
Alguém pode me ajudar, preciso do axios para essa tarefa?
O objeto que estou consumindo para exibir os palestrantes está nesse formato:
const infoPalestrante = {
        pt: [
            {   nome: "Daniel Pelissari",
                descricaoCurta: "CEO NectarJs",
                foto: "DanielPelissari.jpg",
                cv: 'dp.html'
             },

            { nome: "Lucas da Silva",
              descricaoCurta: "Diretor da Viva Lácteos",
               foto: "avatar.jpg",
               cv: "ls.html" },
        ]
    }

Tentei fazer a requisição usando axios dessa forma, até consegui capturar os htmls mas não consigo exibi-los e o que passar para exibir o correto:
axios.get('../cvs')
    .then((res)=>{
      console.log(res.data);
       this.setState({ cv: res.data})
     }).catch((err)=>{
       console.log(err);
 })

O código completo do meu componente:
import React from 'react';
import { Container, Row, Col, Card, Modal, ButtonToolbar, OverlayTrigger, Tooltip, Button } from 'react-bootstrap';
import axios from 'axios';

export default class Palestrantes extends React.Component {
    constructor(props) {
        super(props);
        // armeza o estado  do objeto contendo os palestrantes e os cvs
        this.state = { modal: false, palestrantes: {}, cvPalestrante: {}, infoPalestrante: {}, infoSecao: {}, html: {} };
        this.toggle = this.toggle.bind(this);
    }

toggle() { this.setState(prevState => ({ modal: !prevState.modal })); }

// metodo executado assim que o componente é exibido em tela
componentDidMount() { this.carregarPalestrantes(); }

carregarPalestrantes = async () => {

    const infoSecao = { pt: { lblPalestrante: "Palestrantes" } }

    // informacoes dos palestrantes

    const infoPalestrante = {
        pt: [
            {
                nome: "Daniel Pelissari",
                descricaoCurta: "CEO NectarJS",
                foto: "avatar.jpg",
                cv: 'mpc.html'
             },
            {
                nome: "Marcelo Costa Martins",
                descricaoCurta: "Diretor da Viva Lácteos",
                foto: "avatar.jpg",
                cv: "AnaRaquel.html"
            },
        ]
    }

    // alimenta
    this.setState({ palestrantes: infoPalestrante.pt, infoSecao: infoSecao.pt });
};

abriModal(palestrante) {

    // seta um estado para o objeto cvpalestrante de acordo com o palestrante clicado
    this.setState({ cvPalestrante: palestrante });

    axios.get('../cvs')
    .then((res)=>{
      console.log(res.data);
      this.setState({ cv: res.data})
    }).catch((err)=>{
      console.log(err);
    })

    // chama a funcao responssavel por abrir o modal
    this.toggle();
}

render() {

    // armeza o estado do objeto para uso
    const { palestrantes, cvPalestrante, infoSecao } = this.state;

    // caminho das fotos dos palestrantes
    const caminho = "http://interleite.com.br/sul/assets/img/palestrantes/";

    return (

            <Row>
                <Container><Col md={12} xs={12}>
{infoSecao.lblPalestrante}
</Col></Container>
            </Row>
            <Row>
                <Container>
                    <Col md={12}>
                        <Row>
                            {Object.keys(palestrantes).map((i) => {
                                return (
                                    <Col xs={12} md={3} sm={6} className="palestrante-item" key={palestrantes[i].nome}>
                                        <Card onClick={() => this.abriModal(palestrantes[i])}>

{palestrantes[i].nome}

{palestrantes[i].descricaoCurta}

                                        </Card>
                                    </Col>
                                )
                            })}
                        </Row>
                    </Col>
                </Container>
            </Row>

            <Modal show={this.state.modal} onHide={this.toggle} centered size="lg" unmountOnClose={true} className={this.props.className} >
                <Modal.Header closeButton />
                <Modal.Body className="text-center">

{this.state.cvPalestrante.nome}

{this.state.cvPalestrante.descricaoCurta}

                </Modal.Body>
                <Modal.Footer>

                        <ButtonToolbar>
                            <OverlayTrigger overlay={ <Tooltip>Voltar ao site</Tooltip> }>
                                <Button onClick={this.toggle} className="btn btn-primary btn-circle btn-circle-lg m-1"></Button>
                            </OverlayTrigger>
                        </ButtonToolbar>

                </Modal.Footer>
            </Modal>

    )
    }
}

Obrigado, qualquer ajuda será de grande importância.
Comment: Não entendi a sua duvida, poderia ser mais claro?
Comment: Eu preciso abrir um HTML no modal que é aberto quando clico em algum palestrante, eu tenho uma pasta chamada "CVS" na pasta public do meu projeto com os arquivos html.
Comment: que seria no caso essa configuração: `cv: "AnaRaquel.html"`? esse layout por exemplo é padrão?
Comment: Nesse campo cv eu informo qual html deve ser usado, eu preciso fazer uma requisição para pasta com os cvs e alterar o estado this.cvPalestrante.cv para o conteudo desse html.

Esse layout é a seção onde é mostrado os palestrantes do evento, quando clicar em algum deles eu preciso trazer o html que está na pasta ./public/cvs
Comment: O Layout é padrão e as informações podem ser transferida pra um JSON? OU NÃO?
Comment: @DanielPelissari Eu não entendi qual o erro mas já deixo uma sugestão que talvez te ajude: adicione um iframe dentro do seu modal onde o `src` é o seu campo `cv` (que é um arquivo html).
Comment: Eu faria assim, pelo que eu vi no seu código, transferia as informações desses htmls (nome, função, caminho da imagem, etc) para um JSON e usaria no React da maneira como deve ser feita, vai dar trabalhar transferia as informações pelo visto não são 30 palestrantes, acho bem tranquilo. A sua duvida pode ser feita com um plugin, mas, vai precisar colocar as 30 htmls dentro dessa pagina ! vai virar uma bagunça sem fim ( na minha opinião)
Comment: O layout não é padrão, os htmls podem variar de acordo com o cv do palestrante. Do jeito que tá meu codigo hoje eu até consigo passar html inline direto no objeto porem é ruim para dar manutenção pois em muitas vezes tem bastante conteudo para passar ali.
Comment: é padrão o layout de informações, é uma foto, um nome um sub titulo e um texto, foi o que eu percebi vendo ... não é melhor fazer um json com essas informações? ou até um busca em um back end?
Comment: Um plugin: https://stackoverflow.com/questions/33973757/how-can-i-render-html-from-another-file-in-a-react-component não sei se é a melhor solução.
Comment: Nome, cargo e foto é padrão em todos os cvs e até ai meu código atende. Apenas a cv do palestrante que eu gostaria de trazer de um html externo para melhor organização.
Comment: https://github.com/dpelissari/SPA.SiteEventosReactJS este é um repositorio publico que montei, basicamente no componente palestrante quero consumir um html com o cv do palestrante.
Answer: Consegui resolver fazendo uma requisição a pasta cvs dessa forma com axios:
   abriModal(palestrante) {

    // seta um estado para o objeto cvpalestrante de acordo com o palestrante clicado
    this.setState({ cvPalestrante: palestrante });

    axios.get(`/cvs/${palestrante.cv}`)
        .then((res)=>{
            console.log(res.data);
            this.setState({ cv: res.data})
        }).catch((err)=>{
            console.log(err);
        })

    // chama a funcao responssavel por abrir o modal
    this.toggle();
}


Get File Size of files on Windows through Shell Script on Solaris/Unix

Question: I am writing a Shell Script using Bash on Solaris to retrieve the Size of a remote file on a Windows Server.
size=$(ssh $id@$ip <Windows Prompt command to get size of file at C:\Users\KMST\Documents\log.txt>)

Would the above be possible? I can't find a Windows equivalent of the following unix command,
du KMST_GMS_UpdateLog.txt | cut -f1

Answer: for %a in ("C:\Users\KMST\Documents\log.txt") do @echo(%~za

edited
Tested (in debian) and works as
file=C:\\Users\\KMST\\Documents\\log.txt
size=$(ssh $id@$ip "for %a in (\"$file\") do @echo(%~za")
echo $size
if test $size -gt 100
then
    echo "greater than 100"
fi
if [ $size -gt 100 ]
then
    echo "greater than 100"
fi

Comment: Do I have to enclose the above commands in anything? $(x) or ` or " or '
Comment: Would it be possible to insert a variable into the path? Eg for %a in ("$FULLPATH") do @echo(%~za
Comment: @ParkTaecyeon, sorry, I don't have a windows ssh server at hand to test, so I can't check if you need to enclose it or not. You can use any variable defined in your shell as far as you ensure it is replaced in the Solaris side and what is seen in the windows server is just a string.
Comment: I have been using, for %a in ("$FULLPATH") do @echo(%~za Unfortunately it's not working.
Comment: @ParkTaecyeon, answer updated. For me, from debian to a windows ssh server it works as posted, I'm not sure if it will work in your environment.
Comment: Thanks. I finally got a hold of servers and managed to test it as well. Don't mind if I ask another question, once I got the size as a variable in Unix, all conditional comparisons seems to fail, I don't understand why. I have tried removing tabs/spaces/newlines, but to no avail.
Comment: @ParkTaecyeon, I have tested it as shown in the answer (I've included the conditional code) and for me it is working.
Comment: Unfortunately, the conditional isn't working, it's getting a ": integer expression expected" I'm working on a Solaris server, could this be the reason why?
Comment: @ParkTaecyeon, sorry, if it is a problem in the Solaris side it is out of my knowledge. I've not touched a Solaris machine in the last 17 years. Anyway, have you tested the content of the variable? Can you use something like `echo $size | hexdump -C`?
Comment: Thanks. I got it to work. But what about files in other Drive? Eg. E:\ Where should I insert pushd/cd /d


Try to build flutter app on android studio, device not getting deetect

Question: When i try to create new app using flutter, app will get created  successfully but device or an emulator not getting detect it will show this message on clicking run
<code> No connected devices found; please connect a device, or see flutter.io/setup
 for getting started instructions.
</code>
Comment: Try by closing device and restart it again.
Comment: For now it is not clear what's wrong, so try this -  https://stackoverflow.com/a/49055266/1010710. In case it doesn't help - please update your question with more details (like "flutter doctor" and "adb devices" outputs)
Comment: Possible duplicate of [How to test android apps in a real device with Android Studio?](https://stackoverflow.com/questions/21947834/how-to-test-android-apps-in-a-real-device-with-android-studio)
Answer: Try to close Android Studio with emulator opened, so Open Android Studio Again. If don't work, close emulator and search in SDK Manager if don't have any actualizations to emulator. Try connect a Android mobile and see if Android Studio detect it.
Last, reinstall all the stuffs, including Flutter and Dart (SDK and plugin).
Answer: Uninstall all the plugins and reinstall all the plugins again and then restart android studio.


Código esta pulando linhas - Python

Question: Boa tarde!
Gostaria de uma ajuda no meu projeto que busca palavras (arquivo: Variaveis.txt) dentro de de um outro arquivo (Respostas.txt) e faz a marcação se achar alguma palavra. Porem pulando algumas frases deixando em branco o texto final (Resultado.txt).
Reduzi o tamanho das bases para facilitar o entendimento.
Código:
for i in range(1,23):

    arquivo = open('\Variaveis.txt', 'w')

    with open('\Respostas.txt') as stream:

        with open('\Resultado.txt') as arq:

            palavras = arq.readlines()

            for line in stream:

                    for word in palavras:

                        if word.lower() in line.lower():

                            a = (line.strip(), '¬', word + '\n')

                            arquivo.writelines(a)
                            print(a)
                            break

arquivo.close()

Arquivos:
-Variáveis:
oi
mundo
alo
tchau

Respostas:
oi mundo
tchau vida solteira
ola meu amigos
mundo grande

Resultado:
oi mundo¬mundo

tchau vida solteira¬tchau

Resultado esperado:
oi mundo¬oi
tchau vida solteira¬tchau
ola meu amigos¬ola
mundo grande¬mundo

Obs: Estava rodando o projeto escrevendo as variáveis dentro do código e funcionava igual ao resultado esperado, porem as bases são grandes e preciso usar as variáveis buscando dentro de um txt como esta no código acima.
Comment: tem uns `'` em falta pelo código fora. Tem isso assim so na pergunta ou tem igual no seu código ?
Comment: desculpe, fui tirar informações do meu pc para postar aqui e tirei sem querer também os '
No Código esta correta esta parte.
Comment: uma dica paralela - tente pensar melhor os seus nomes de variáveis - você tem uma variável "arq" e uma variável "arquivo", ambas representando arquivos diferentes. Nada imprede que você chame as variáveis de "resultados, respostas, palavras"  - o programa ficaria muito mais fácil de ler.
Answer: O problema é a leitura das palavras:
palavras = arq.readlines()

o método readlines retorna uma linha, inclusive com o \n no final. Da documentação:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn't end in a newline.

Ou seja, seu código só casa quando a palavra está no final da frase buscada ou se ela for a ultima palavra do seu arquivo de palavras.
Para resolver isso, você deve remover o \n das palavras antes de buscá-las, usando o método strip. Algo como:
if word.strip().lower() in line.lower():
    a = (line.strip(), '¬', word + '\n')
    arquivo.writelines(a)
    print(a)
    break

Código esta pulando linhas - Python


Weak solution and Rankine-Hugoniot condition

Question: I know from PDE lectures that in case of the following Cauchy problem:
$$
\left\{
\begin{array}{l}
        u_{t}+uu_{x}=0\\
        u(x,0)=g(x)\\
\end{array}
\right.
$$
if a piecewise $C^{1}$ function $u$ is a weak solution of above problem, i.e. it satisfies $\int\limits_{0}^{\infty}\int\limits_{-\infty}^{\infty}\left(u\varphi_{t}+\frac{1}{2}u^{2}\varphi_{x}\right)dxdt+\int\limits_{-\infty}^{\infty}g(x)\varphi(x,0)=0$ for any $\varphi\in C^{1}_{0}(\Omega)$ (spaces of $C^{1}$ functions with the compact support contained in $\Omega:=\mathbb{R}\times[0,\infty)$), then $u$ is classical solution of given Cauchy problem in domains where it is a $C^{1}$ function and satisfies Rankine-Hugoniot condition along its every discontinuity curve. I wonder if reverse theorem is true, i.e. if $u$ is classical solution of given Cauchy problem in domains where it is a $C^{1}$ function and satisfies Rankine-Hugoniot condition along its every discontinuity curve, then $u$ is a weak solution? If so, how to prove it? Thanks
Answer: It's true! All the passages in the proof that you already know are reversible.

Edit:
Let $ [u] \stackrel{\text{df}}{=} {u_{+}}(p) - {u_{-}}(p) $ for all $ p \in \gamma_{0} = \{ (\xi(t),t) \mid t \in I \} $.
(R.H.S.): As $ \xi'(t) = \dfrac{[f(u)]}{[u]}(\xi(t),t) $ for all $ t \in I $, we have
\begin{align}
& [f(u)](\xi(t),t) - [u](\xi(t),t) \cdot \xi'(t) = 0 \\ \Longrightarrow \quad
& 0 = \int_{I}
      \Big( [f(u)](\xi(t),t) - [u](\xi(t),t) \cdot \xi'(t) \Big) \cdot
      \phi(\xi(t),t) ~
      \mathrm{d}{t}.
\end{align}
Let $ v = (v_{1},v_{2}) = (1,- \xi'(t)) $. We can then write the previous formula as follows:
\begin{align}
    0
& = \int_{I} ([f(u)] v_{1} + [u] v_{2}) \phi ~ \mathrm{d}{s} \\
& = \int_{\gamma_{0} \cap \text{supp}(\phi)}
    \Big( f(u_{+}) v_{1} + u_{+} v_{2} \Big) \phi ~
    \mathrm{d}{s} -
    \int_{\gamma_{0} \cap \text{supp}(\phi)}
    \Big( f(u_{-}) v_{1} + u_{-} v_{2} \Big) \phi ~
    \mathrm{d}{s}.
\end{align}
We have taken $ \phi \in {C_{c}^{1}}(\Omega) $, so $ \text{supp}(\phi) = \omega_{-} \cup (\gamma_{0} \cap \text{supp}(\phi)) \cup \omega_{+} $.
This is the crucial point: We are going to use the Divergence Theorem in the 'non-standard' way:
\begin{align}
    \int_{\gamma_{0} \cap \text{supp}(\phi)}
    \Big( f(u_{+}) v_{1} + u_{+} v_{2} \Big) \phi ~
    \mathrm{d}{s}
& = \int_{\partial \omega_{+}}
    \Big( f(u_{+}) v_{1} + u_{+} v_{2} \Big) \phi ~\mathrm{d}{s} \\
& = \iint_{\omega_{+}}
    \left(
    u \frac{\partial \phi}{\partial t} + f(u) \frac{\partial \phi}{\partial x}
    \right) ~
    \mathrm{d}{x} \mathrm{d}{t} +
    \iint_{\omega_{+}}
    \left(
    \frac{\partial u}{\partial t} + \frac{\partial f(u)}{\partial x}
    \right) \phi ~ \mathrm{d}{x} \mathrm{d}{t}.
\end{align}
Note that the last integral is $ 0 $ because our solution is classical outside the shock. We now have the following equations:
$$
  \int_{\gamma_{0} \cap \text{supp}(\phi)}
  \Big( f(u_{+}) v_{1} + u_{+} v_{2} \Big) \phi ~
  \mathrm{d}{s}
= \iint_{\omega_{+}}
  \left(
  u \frac{\partial \phi}{\partial t} + f(u) \frac{\partial \phi}{\partial x}
  \right) ~
  \mathrm{d}{x} \mathrm{d}{t},
$$
and, similarly,
$$
  - \int_{\gamma_{0} \cap \text{supp}(\phi)}
  \Big( f(u_{-}) v_{1} + u_{-} v_{2} \Big) \phi ~ \mathrm{d}{s}
= \iint_{\omega_{-}}
  \left(
  u \frac{\partial \phi}{\partial t} + f(u) \frac{\partial \phi}{\partial x}
  \right) ~
  \mathrm{d}{x} \mathrm{d}{t}.
$$
Summing up term by term:
\begin{align}
    0
& = \int_{I} \Big( [f(u)] v_{1} + [u] v_{2} \Big) \phi ~ \mathrm{d}{s} \\
& = \iint_{\omega_{+} \cup \omega_{-}}
    \left(
    u \frac{\partial \phi}{\partial t} + f(u) \frac{\partial \phi}{\partial x}
    \right) ~
    \mathrm{d}{x} \mathrm{d}{t} \\
& = \int_{\text{supp}(\phi)}
    \left(
    u \frac{\partial \phi}{\partial t} + f(u) \frac{\partial \phi}{\partial x}
    \right) ~
    \mathrm{d}{x} \mathrm{d}{t}.
\end{align}
This is exactly what we were supposed to prove.
Hope it helps!
Comment: Maybe you can show your proof in other direction, user67133?
Comment: I've tried to do it but I failed. In ($\Rightarrow$) direction we choose a discontinuity curve, a point on it and a ball $B$ centered at that point and sufficiently small radius to not intersect other such curves. Next we take an arbitrary function $\varphi\in C^{1}_{0}(B)$ and using Green's identity we are able to show that Rankine-Hugoniot conditions holds. In other direction I have a problem because I think I can show that $\iint\limits_{B}\left(u\varphi_{t}+\frac{1}{2}u^{2}\varphi_{x}\right)dxdt$ for an arbitrary $\varphi\in C^{1}_{0}(B)$ and ball $B$ as above but what next?
Comment: of course I can, I am sorry but I had no time before :D
Comment: I edited with the solution!
Comment: Your answer is indeed helpful. Thank you!


copy files created in one folder to multiple other folders on linux

Question: I'm looking for a way to copy photos that are uploaded to one folder to many other folders and visa versa.
Example: a photo is uploaded to folder 1, it is then copied to folders 2-5. And if a photo is uploaded to folder 2 it is copied to folders 1 and 3-5.
I'm running CentOS 5. All of these folders are on the same server.
I came across another post on here that talked about incron, but that type of programming is over my head.
Comment: incron is not programming. It's just installing a daemon, creating a slightly-opaque-but-not-awful-at-least-it's-documented incrontab config file, and *maybe* a simple shell script to do the work.
Answer: rsync will do the job.
you need to setup a cron job from a shell script that what it does is running rsync over all your directories.
Answer: Instead of rsync, check out unison - it handles synchronizing two directories better than rsync.
I can envision doing this with a bash script running a series of unison commands to keep all the directories in sync:
<code>for i in 2 3 4
do
  unison /dir1 /dir$i
done
</code>
put that in a crontab that runs every hour or whatever ( I realize my unison syntax is not right).
However, I do really like the incrond approach. That would give you a cleaner design because it would allow you to only run the synchronizer when one of the directories change.  However indeed it's more work to set up.


How do I replace all the characters that don't meet this regex string in Ruby?

Question: Since AWS requires a specific regex value of ^([\p{L}\p{Z}\p{N}_.:/=+-@]*)$for its instance ID for AWS SSM, I am trying to figure out the best way to replace letters in a string if it doesn't match.
For example, if my string is Test (sample), which doesn't meet the above regex, how do I replace the parentheses (since it's a part of the characters that don't match) with a space?
Comment: For readers like me (if any), who didn't know what "AWS" was, it's evidentally [Amazon Web Services](https://searchaws.techtarget.com/definition/Amazon-Web-Services).
Answer: You could use String#sub if String#match returns nil:
str = 'Test (sample)'
re = %r{^([\p{L}\p{Z}\p{N}_.:/=+-@]*)$}

str = if str.match re
        str
      else
        str.sub(/\(.*\)/, '( )')
      end

str # => "Test ( )"

Comment: That's replacing the words in the parentheses though. What needs to be replaced are the parentheses in this example, but more importantly -- anything that doesn't match the regex needs to be replaced.


Crawler para varredura de sites

Question: Fala Galera, tudo bem?
Eu gostaria de criar um Crawler para fazer a varredura dia em alguns sites específicos e me trazer em uma planilha ou algo do tipo as matérias da home desses sites. No caso eu gostaria de fazer uma varredura em portais de noticias.
Sou leigo no assunto, então gostaria de saber oque eu preciso de recurso (Banco de dados, Servidor, algo do tipo) para criar e qual melhor linguagem para desenvolvimento desse tipo de demanda.
Muito obrigado.
Answer: Você pode usar os seguintes recursos:
1- Linguagem Python para o crawler usando uma dessas bibliotecas (Scrapy ou BeautifulSoup);
2- Um Banco de dados a sua escolha (MySQL, PostgreSQL, ...), se tiver conhecimento de banco de dados, sugiro que use um não-relacional (MongoDB, CassandraDB, ...), pois dependendo da quantidade de dados, ele trabalha de uma forma mais ágil;
3- Deploy em um servidor para que o programa rode 24h por dia (Heroku, por exemplo);
Não é crucial, mas além do banco de dados, caso deseje armazenar as informações em planilha, é bem simples de se fazer com Python usando a biblioteca openpyxl.
Caso precise de uma referência, segue um projeto pessoal de minha autoria no GitHub que trata exatamente deste assunto: https://github.com/VictorAlessander/Smith

Crawler para varredura de sites


Is there a name for the technique where a singer uses the falsetto register on releasing a note?

Question: As per the title, is there a name for the technique where a singer (especially a female one) voices a pitch in the falsetto register on releasing a note?
Examples include:-

Alanis Morissette

You Oughta Know - particularly at the end of the chorus, "You^ You^ You^ Oughta Know"

Sinead O'Connor

Nothing Compares to You - occasionally "since you been gone I can do whatever I wa-aaa-aan^t" around 45s

Dolores O'Riordan from The Cranberries

Zombie (The Cranberries) - constantly... "Z-om-bi^e, Z-om-bi^e, Z-om-bi^e e^eh e^eh e^eh o^oh o^oh" etc
Comment: In German, I'd call it _umkippen_ ("tip over") or _kieksen_ (onomatopoeic). The closest fit in English might be just _the voice cracks_, but that seems rather more severe...
Comment: Yes.  It's called "yodeling."  (Sorry, couldn't resist)
Comment: I'll add more examples if I find some. I'm listening to all sorts of embarrassing 90s pop looking for more!
Comment: While I know exactly what you mean, you might want to find a description for this other than *falsetto,* because you're talking about female singers, and it's controversial whether female falsetto exists.
Answer: I think the technique is best described as a yodel, which is defined as a quick flipping between vocal registers. A yodel isn't specific to the release of a note, but is the closest thing to a proper term for the general technique.
If you're trying to describe the style for a someone, "like a yodel" might be clearer, since most people associate yodeling with a more specific genre of music/vocalization.
Like leftroundabout mentioned, it could also be described more informally as a voice crack in some scenarios.
Answer: I believe it can also be described as 'Keening' or a song style used in the old days after a death- a form of vocal lament for the dead.
Dolores' voice, yodeling or not is beautiful.


A accessToken is not valid for connecting to Azure DevOps deployment group from Windows server

Question: In Azure Devops Server, I have created a group in  Deployment Groups. A registration script was created for run in the target server. This is the generated script.

$ErrorActionPreference="Stop";If(-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [Security.Principal.WindowsBuiltInRole] "Administrator")){ throw "Run command in an administrator PowerShell prompt"};If($PSVersionTable.PSVersion -lt (New-Object System.Version("3.0"))){ throw "The minimum version of Windows PowerShell that is required by the script (3.0) does not match the currently running version of Windows PowerShell." };If(-NOT (Test-Path $env:SystemDrive'azagent')){mkdir $env:SystemDrive'azagent'}; cd $env:SystemDrive'azagent'; for($i=1; $i -lt 100; $i++){$destFolder="A"+$i.ToString();if(-NOT (Test-Path ($destFolder))){mkdir $destFolder;cd $destFolder;break;}}; $agentZip="$PWD\agent.zip";$DefaultProxy=[System.Net.WebRequest]::DefaultWebProxy;$securityProtocol=@();$securityProtocol+=[Net.ServicePointManager]::SecurityProtocol;$securityProtocol+=[Net.SecurityProtocolType]::Tls12;[Net.ServicePointManager]::SecurityProtocol=$securityProtocol;$WebClient=New-Object Net.WebClient; $Uri='https://go.microsoft.com/fwlink/?linkid=2066756';if($DefaultProxy -and (-not $DefaultProxy.IsBypassed($Uri))){$WebClient.Proxy= New-Object Net.WebProxy($DefaultProxy.GetProxy($Uri).OriginalString, $True);}; $WebClient.DownloadFile($Uri, $agentZip);Add-Type -AssemblyName System.IO.Compression.FileSystem;[System.IO.Compression.ZipFile]::ExtractToDirectory( $agentZip, "$PWD");.\config.cmd --deploymentgroup --deploymentgroupname "DG-Test" --agent $env:COMPUTERNAME --runasservice --work '_work' --url 'https://devops.MyCompany.com/tfs/' --collectionname 'Col-FRN-Main' --projectname 'T-MyCompany'; Remove-Item $agentZip;

I run the script then PowerShell asks me to Enter authentication type (press enter for PAT), so I enter an accessToken that is generated in Personal Access Token but PowerShell returns Enter authentication type (press enter for PAT).
I could use the accessToken for connecting Team explorer in Visual studio to my DevOps server and connecting agent pool to my DevOps server, but I have trouble connecting deployment agnet.
What's wrong?
Answer: When PowerShell asks you to Enter authentication type (press enter for PAT), you are supposed to press enter on your keyboard. Then it will prompt you to enter your Personal Access Token. Follow the prompts and you should be able to connect successfully.