OpenCSV parse() returns object with null values

Question: I have this input .csv file(here just a sample - there are 1.500.000 line)
OBJECT_ID¦TYPE¦NAME¦PARENT_ID¦MANUFACTURER¦POSITION_CODE¦MAINTENANCE_STATUS¦PHYSICAL_STATUS
9143101068113202824¦Card¦H603CSRI - 6¦9143101069013360101¦Huawei Technologies¦74EX.G010.R13.031 (H603).006¦Not on Maintenance¦In Service
9143101068113202825¦Card¦H603CSRI - 7¦9143101069013360101¦Huawei Technologies¦74EX.G010.R13.031 (H603).007¦Not on Maintenance¦In Service

I've created a model class called Card
public class Card {
    @CsvBindByName(column = "OBJECT_ID")
    private String object_id;

    @CsvBindByName(column = "TYPE")
    private String type;

    @CsvBindByName(column = "NAME")
    private String name;

    @CsvBindByName(column = "PARENT_ID")
    private String parent_id;

    @CsvBindByName(column = "MANUFACTURER")
    private String manufacturer;

    @CsvBindByName(column = "POSITION_CODE")
    private String position_code;

    @CsvBindByName(column = "MAINTENANCE_STATUS")
    private String maintenance_status;

    @CsvBindByName(column = "PHYSICAL_STATUS")
    private String physical_status;

public Card() { }
public Card(String object_id, String type, String name, String parent_id, String manufacturer, String position_code, String maintenance_status, String physical_status) {
    this.object_id = object_id;
    this.type = type;
    this.name = name;
    this.parent_id = parent_id;
    this.manufacturer = manufacturer;
    this.position_code = position_code;
    this.maintenance_status = maintenance_status;
    this.physical_status = physical_status;
}

public String getObject_id() {
    return object_id;
}

public void setObject_id(String object_id) {
    this.object_id = object_id;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getParent_id() {
    return parent_id;
}

public void setParent_id(String parent_id) {
    this.parent_id = parent_id;
}

public String getManufacturer() {
    return manufacturer;
}

public void setManufacturer(String manufacturer) {
    this.manufacturer = manufacturer;
}

public String getPosition_code() {
    return position_code;
}

public void setPosition_code(String position_code) {
    this.position_code = position_code;
}

public String getMaintenance_status() {
    return maintenance_status;
}

public void setMaintenance_status(String maintenance_status) {
    this.maintenance_status = maintenance_status;
}

public String getPhysical_status() {
    return physical_status;
}

public void setPhysical_status(String physical_status) {
    this.physical_status = physical_status;
}
}

And I have this method that should load all the csv content into the cards List and then put the data into a Map
public static Map<String, Card> getAllCards(String fileLocation) {
        log.logInfo("getAllCards  started!");
        long totalTime = System.currentTimeMillis();
        Map<String, Card> map = new HashMap<>();
        try (
                Reader reader = Files.newBufferedReader(Paths.get(fileLocation))
        ) {
            CsvToBean<Card> csvToBean = new CsvToBeanBuilder(reader)
                    .withSeparator('¦')
                    .withType(Card.class)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            List<Card> cards = csvToBean.parse();
            System.out.println(cards.size());//1.535.232
            for(Card card: cards) {
                Card cardObj = new Card(card.getObject_id(),card.getType(),card.getName(), card.getParent_id(),
                        card.getManufacturer(), card.getPosition_code(), card.getMaintenance_status(),card.getPhysical_status());
                map.put(card.getObject_id(), cardObj);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map.get("OBJECT_ID"));//null
        System.out.println(map.size());//1 as it inserts only one null key
        log.logInfo("getAllCards completed in " + ((double) (System.currentTimeMillis() - totalTime) / 1000) + " sec.");
        return map;
    }

The problem is that the cards List contains a list of objects that have all null values. The size is correct so it is reading the csv file but is not populating with data. Any idea on what is happening?
Comment: above program works fine for me.
Comment: how does one of your setter method int the model looks like?
Comment: you can put your complete Card class. I will let you know if it is different from mine
Comment: ok, I've updated the question
Comment: it is same as yours, no idea why this isnt working for u
Comment: I changed the openCsv binding from `@CsvBindByName(column = "OBJECT_ID")` to  `@CsvBindByPosition(position = 0)` and now I get the values...
Comment: I was using openCsv 4.0 and after upgrading to 4.2 it works also with name binding, so I think there was a case sensitive issue in 4.0
Answer: In my case, I was instantiating incorrectly the InputStreamReader.
Receiving the file as MultipartFile, all i did was new InputStreamReader(csvFile.getInputStream()).
I would try to change your reader instantiation to a FileReader new FileReader("yourfile.csv").


is it possible to make a Facebook canvas app that is not a game?

Question: I am interested in creating a canvas app that will work as a communication tool that will use facebook user's friends lists. Is it possible to make a facebook canvas app that is actually a tool and not a game? Or is this agains facebook's policies? I couldn't find a direct answer for this question anywhere, so I thought I would ask here.
Thanks.
Answer: Of course you can create Apps too, but you will still not get the full friend list of the user, only those who are using the App (with /me/friends).
You can use taggable_friends to tag friends, But you are not allowed to use those for something else - only for tagging.
According to the Facebook docs, invitable_friends is only for Games - and of course it has to be used for inviting friends only.
Comment: no, that is not possible (anymore), see changelog. you can only get the friends who are using the app too with /me/friends, since v2.0. this is for privacy reasons, an app should not be able to access someone who is not even using the app.
Comment: Thanks a lot. Just to make sure I am getting this, if a user signs up for an app, will that user have access to all of his friends through the app?


Why do PHP versions prior to 8.0 reject the namespace "Random\Namespace" as invalid syntax?

Question: <?php
namespace Random\Namespace;

When I run this code on 3v4l.org (https://3v4l.org/kk0bD) it works fine on PHP 8.0.0+ but on PHP >= 5.4.0 and PHP < 8.0.0 I get this error:
Parse error: syntax error, unexpected 'Namespace' (T_NAMESPACE), expecting identifier (T_STRING)

I don't understand. namespaces have been around in PHP since PHP 5.3.0.
Any ideas?
Comment: This looks like the word `Namespace` is reserved.
Comment: I've just played with this in PHP 5.6 ... It's because Namespace is a keyword.
If you try `namespace Random\SomethingElse` it works. I assume, "they" considered it to be a bug and fixed it in PHP 8
Answer: Until PHP 8.0, every component in a namespace was considered as a distinct name, and each part could not use any of the list of reserved keywords.
In this case, the namespace Random\Namespace contains the reserved name "Namespace" as one of its components, so is rejected by the parser.
In PHP 8.0, a change to the parser was introduced where the entire namespace name is treated as a single token (as part of a general trend to making keywords reserved in as few contexts as possible). So for PHP 8.x, the name is parsed in one go as "Random\Namespace", which is not reserved.
The linked proposal notes that the keyword namespace is still reserved at the start of namespace names, because it would cause ambiguity in some contexts, so namespace Namespace\Random; is still an error.


Statistics on a table with `value' column and `number of events' column

Question: I have a table which looks like
value(0 < v< 1),  # of events
---------------   -----------
0.1,              1000
0.5,              20000
0.7,              3000000
0.1,              400000000
0.5,              50000000000
0.9,              6000000000000
...,              ...

the value can take any number from 0 to 1 possibly with repetition and the number of event is so large that it is inefficient to transform this into a usual form of vector, like
0.1,0,1,...0.1, 0.5,0.5,0.5, ...

When I try to apply some function, eg plot(), to this table, R does not identify rows with same value but treats them separately. What would be a good way of doing some statistics with this kind of table as if we have the following table?
value,  # of events
0.1,    400001000
0.5,    ...

Answer: Your question is a bit unclear, but I think you just want to sum events by each unique value? If so, there are multitudes of answers to this and related questions. Here's one approach:
#fake data
set.seed(1)
x <- data.frame(value = 1:3, events = sample(1:10, 9, TRUE))

#Option 1

 aggregate(events ~ ., data = x, FUN = "sum")
  value events
1     1     23
2     2     14
3     3     22

#Option 2
> tapply(x$events, x$value, FUN = "sum")
 1  2  3
23 14 22

#Option 3
> library(plyr)
> ddply(x, "value", summarize, sum = sum(events))
  value sum
1     1  23
2     2  14
3     3  22

#Option 4
> library(data.table)
> x <- data.table(x)
> x[, sum(events), by = value]
     value V1
[1,]     1 23
[2,]     2 14
[3,]     3 22

These solutions (and others) scale differently as your data grows. I gave a pretty comprensive answer to compare timings and methods here
Comment: Answers with various options - this really helps. Thanks a lot!
Answer: As a first step, here's how to convert your first table into the second form.
Construct data:
dd <- setNames(as.data.frame(matrix(c(0.1,1000,
                                      0.5,20000,
                                      0.7,3000000,
                                      0.1,400000000,
                                      0.5,50000000000,
                                      0.9,6000000000000),
                                    ncol=2,byrow=TRUE)),
                             c("value","count"))

Use tapply to condense the data
dd2 <- tapply(dd$count,dd$value,sum)

Then use melt to get the data into a (possibly) more useful format:
library(reshape2)
(dd3 <- melt(dd2,varnames="value",value.name="count"))
##   value        count
## 1   0.1 4.000010e+08
## 2   0.5 5.000002e+10
## 3   0.7 3.000000e+06
## 4   0.9 6.000000e+12

You may want to be careful when adding very small and very large numbers.
For the "what kind of statistics should I do?" part of the question -- sorry, that's too vague.  What do you want to find out ... ???
Comment: Sorry for being vague. I was wondering how do I apply basic functions like mean or median to this table to get a sense of dealing with data in R. As you already noticed, I'm new to R but I have to learn this as quickly as possible :-)
Answer: If you want a weighted mean:
 weighted.mean(dd$value, dd$count)
[1] 0.8966414

Weighted median: (and there are several other 'weighted' functions in Hmisc)
 library(Hmisc)
 wtd.quantile(dd$value, dd$count, .5)
#50%
#0.9

To plot just use barplot
 barplot(dd$count)  #perhaps with log="y"
 barplot(dd$count, log="y")


A complex function that is harmonic but not analytic

Question: Can someone give a simple example of a complex function that is harmonic but not analytic?
Thanks.
D.
Comment: Natural examples are $\mbox{Re}\;z, \mbox{Im}\; z, \bar{z}$...
Answer: $x{}{}{}{}{}{}{}{}{}{}{}{}{}{}$
Comment: Sorry, couldn't resist the temptation of  a one- typographical-character answer :-) [But made it community wiki].
Comment: You probably mean $z\mapsto\mathrm{Re}(z)$.
Comment: Must be a [French](http://math.stackexchange.com/a/97032/) [thing](http://math.stackexchange.com/a/74383/)... :-)
Comment: @girianshiido: yes.
Comment: @Martin: oui! (and thanks for the link to my predecessors-rivals: grrr...!)
Comment: Why didn't you add the links yourself, one wonders?


Linear Regression: How can the error term have variance?

Question: I seem to be missing something fundamental about the structure of the linear regression model.
Suppose we have a response variable $Y$ and $p$ predictor variables $X_1$ to $X_p$.
For a particular sample of sample size $n$ we seek to model $Y$ in terms of the predictor variables so that for the $i$-th observation we get
$y_i = \beta_0+\beta_1x_{i1}+\beta_2x_{i2} +...+ \beta_px_{ip}+\epsilon_i$
So we deal with $n$ error terms $\epsilon_1$ to $\epsilon_n$ - $n$ numbers, one for each observation. What does it mean, in the context of least squares estimation, to stipulate that each of the $\epsilon_i$ be homoscedascic, i.e. each of them has the same variance $\sigma^2$ when all we have is one error term for each observation? How can we talk about variance of $\epsilon_i$ when it is a single number rather than a random variable which has a distribution and hence variance?
Comment: Hi, welcome. Homoskedasticity means there is *one* $\sigma$ for all $\varepsilon_i$. Heteroskedasticity would be implied by an error variance that is a function of the regressors $\mathbf{X}$. For a simple example of heteroskedasticity see the second image in https://stats.meta.stackexchange.com/a/613/ where $\text{Speed}$ is regressed on $\text{Rep}$.
Comment: How could there be more than one $\sigma$, more than one variance measure for the set of $n$ numbers $\epsilon_i$? I don't get how for the continuous range of $X$ the condition of equal variances is defined. Equal to what? Is the idea to say that for any fixed _subrange_ or _interval_ of $X$ the error terms of the model must have the same variance for homoscedasticity to hold?
Comment: A practical example of having more than one $\sigma$ is a posttest-only two-group randomized controlled study where the treatment has a homogenizing effect. In this example, $\epsilon$ is actually composed of two random variables, with different distributions, both mean zero, but larger $\sigma$ for the control than for the treatment.
Answer: To attempt an answer to your original question, each $\epsilon_i$ is considered to be one realization of the random variable $\epsilon$. So each $\epsilon_i$, $i = 1,\ldots,n$, is indeed only one number, but there is an underlying distribution which generates those numbers. I have never seen the notion of homo/heteroscedasticity as referring to any single one $\epsilon_i$ in particular (and would certainly not choose that phrasing myself), rather the concept refers to the whole collection of error terms.
A simple example would be to consider that you are taking 50 measurements manually, using some tool that requires hand stability, so your sample is $y_1,\ldots,y_{50}$. Then a friend of yours with shaky hands takes another 50 measurements, $y_{51},\ldots,y_{100}$. Intuitively, if you model your 50 observations separately from those of your friend, you'd expect that your $\epsilon_i, i=1,\ldots,50,$ would tend to deviate less from their mean value than those $\epsilon_i, i=51,\ldots,100$ your friend would get from his model on the same predictors, because you know you have steadier hands. This means that your $\epsilon_i$ are in fact homoscedastic within their own group, i.e. for $i=1,\ldots,50$ (assuming you don't get tired after a while). What's more, your friend's errors are also homoscedastic with respect to his group, i.e. $i=51,\ldots,100$. If you pool everything together though, the collection $\epsilon_i, i=1,\ldots,100$ is decidedly not homoscedastic, because not all of these $\epsilon_i$ were generated by the same mechanism (half the errors came from your hands, the other half from your shaky friend).
Another example of heteroscedasticity would be to take all 100 measurements yourself but (much more realistically) assume fatigue with time: you'd see that your $\epsilon_i$ would be very low for the measurements you took first, but they would increase with time as your muscles grow tired and your precision suffers, thus increasing the variance of future errors (i.e. the chance that you make bigger errors in the measurement). Hope this helps.
Comment: I love this example. It clearly demonstrates the error term as a realization of a random variable.
Comment: Very happy to hear that. Hopefully others also found the answer useful, though from what I read in the question, OP had an issue with the definition of homoscedasticity in the sense that it's not defined w.r.t to a single observation but rather by looking at any slice & dice (i.e. random sub-samples) combination of the data, so if all these combinations have the same variance, then we have homoscedasticity.
Answer: It's easier to understand on a concrete example. Suppose, you want to predict the precipitation based on the temperature of a site. So, you posit a model:
$$y_i=\beta_0+\beta x_i+\varepsilon_i$$
Here, $y_i$ average precipitation and $x_i$ - average temperature in town. Do you think that the prediction uncertainty is the same regardless of a town? If you do, then you assume that the errors are homoscedastic.
However, one could make an argument that the uncertainty is not the same for all geographies. Maybe for some reason this model forecasts better for Ulanbaator than for Washington DC. In this case the error variances will be larger for Washington, and smaller for Ulanbaator, i.e. heteroscedastic errors
I suspect that you naturally consider the errors $\varepsilon_i$ as realizations of some random variable $\varepsilon$. Hence, you think of a variance $\sigma^2$ as a variance of that variable $Var[\varepsilon]$. It seems to fit the intuition. However, in reality each error terms $\varepsilon_i$ is a random variable itself. Each one of these have their own variance $Var[\varepsilon_i]=\sigma_i^2$, they don't need to be the same


Group action - using the orbits to find cosets

Question: Let $G$ be a finite group with a subgroup $H$ of index $5$. Also $5$ is the smallest prime divisor of $|H|$. Let $X=\{gH:g\in G\}$ be the set of left cosets of $H$ in $G$, $H$ acts on $X$ by left multiplication.
Every orbit of $X$ has length $1$ (See here). Using this fact that every orbit has length 1, show that $hg\in gH$ for $h\in H$, and $g\in G$.
I'm not sure how I would show this, I tried by assuming it was normal and therefore $gH=Hg$ but I think this is wrong because I don't think I can assume that orbits of length 1 means it's normal?
Answer: Let $gH$ be one coset in $X$. Since it's orbit has only one element (i.e., one coset), you just need to figure out which coset it is. You can show fairly easily that $gH$ must be in its own orbit, so the orbit of $gH$ is just $\{gH\}$. Then you know that for any $h\in H$, $h(gH)$ must be in the orbit of $gH$, which means that $h(gH)=gH$. But $h(gH)=\{hgk|k\in H\}$, so you can use that to deduce that $hg\in gH$.
Comment: Thank you, do you know how I would use this fact to prove the theorem 'If 5 is the smallest prime dividing the order of a finite group G, then any subgroup of index 5 in G is normal'.

My thoughts were that maybe by showing $hg\in gH$ we have shown that $H$ is normal? And because of this every H would be normal.. I'm unsure if I can just assume that.
Comment: Normality is equivalent $gH=Hg$ for all $g$. You've shown that $hg\in gH$, which is only a few steps away from normality.
For the results of this question (and the other) you assumed that 5 was the smallest prime divisor of $\vert H\vert$. For the next question you are assuming that $H$ has index 5. Can you show that $[G:H]=5$ implies that 5 is the smallest prime dividing $\vert H\vert$?
Comment: Okay, so I need to show $hg$ also $\in Hg$. Using the same logic would I show this by saying: the orbit of $Hg$ would be $\{Hg\}$ and for any $h\in H$, $h(Hg)=Hg$. Then since $h(Hg)=\{hkg|k\in H\}$, $hg\in Hg$. So H is normal? Then $[G:H]=5$ implies 5 is the smallest prime diving $|H|$ since we can write $|H|=|G|/5$? But then I don't know how to tie this all together in the proof


Webform Module and Elements Module

Question: I have a hook that i wrote to include the elements fields (i.e, telfield) in a webform. The field doesnt take on the same css as the rest of the fields which means I probably need to add a style to the CSS for it. However, I'm trying to figure out a way to implement this globally so that I will be accepted as a regular form component since I have over 40 different themes that this will be applying to.
This is an attempt to avoid having to go into each them and adding the style.
Thanks,
Comment: If my answer was useful do not forget to mark it as acepted otherwise anybody in the comunity will help you again. Greetings
Comment: it wasnt that helpful. but thanks for the answer. how do i vote?
Comment: click the symbol √ at the left of my answer
Answer: there is no way to add a stylesheet and be global for all the themes you have inside sites/all/themes
The unic way is that all your different 40 themes were subthemes of one parent theme then you can have your styles in the parent theme and all your subthemes will inherit the styles of the parent, there is no other way...

Webform Module and Elements Module


Need jQuery Fancybox to refresh parent window

Question: I'm having a problem getting jQuery Fancybox to refresh the parent window once I'm done with it.  The fancybox opens and operates just fine, but the onClosed event won't work for me.
<code>$(document).ready(function() {
  $("a#add_document_type").fancybox({
    type: 'iframe',
    onClosed: function() {
      parent.location.reload(true);
    }
  });
});
</code>
For testing I've replaced parent.location.reload(true); with alert('Testing'); and had no luck there either so I'm at a bit of a loss.  Thanks for any help anyone can provide!
Answer: SOLVED: the trick is to use afterClose:, not onClosed: so the full code would be:
<code>$(document).ready(function() {
  $("a#add_document_type").fancybox({
    type: 'iframe',
    afterClose: function() {
      parent.location.reload(true);
    }
  });
});
</code>
Comment: `onClosed` is for fancybox v1.3.x while `afterClose` for v2.x
Comment: thank you very much. I was looking for this for hours. you are life saver :)


Can an algorithm be part of a proof?

Question: I am an undergraduate student. I have read several papers in graph theory and found something may be strange: an algorithm is part of a proof. In the paper, except the last two sentences, other sentences describe a labeling algorithm.
Can an algorithm be part of a proof? I do not understand why it can be part of a proof. I asked my supervisor but he did not explain it.

LEMMA$\,\,\,\bf 1.$ If $B(G)-b$, then $B(G+e)<2b$.  Proof:
  Let $f$ be an optimal numbering of $G$, and let $V(G)-\{v_1,\ldots,v_n\}$, numbered so that $f(v_i)-i$. Let $v_lv_m$ be the added edge. We define a new numbering $f'$ such that $|f'(x)-f'(y)|<2|f(x)-f(y)|$, and also $|f'(v_l)-f'(v_m)|-1$. Let $r-\lfloor(l+m)/2\rfloor$, and set $f'(v_r)-1$ and $f'(v_{r+1})-2$. For every other $v_i$ such that $|i-r|<\min\{r-1,n-r\}$, let $f'(v_i)-f'(v_{i+1})+2$ if $i<r$ and $f'(v_i)-f'(v_{i-1})+2$ if $i>r$. This defines $f'$ for all vertices except a set of the form $v_i,\ldots,v_k$ or $v_{n+1-k},\ldots,v_n$, depending on the sign of $r-\lfloor(n+1)/2\rfloor$. In the first case, we assign $f'(v_i)-n+1-i$ for $i<k$; in the second, we assign $f'(v_i)-i$ for $i>n-k$. The renumbering $f'$ numbers the vertices outward from $v_r$ to achieve $|f'(x)-f'(y)|<2|f(x)-f(y)|$. Since we begin midway between $v_l$ and $v_m$, we also have $|f'(v_l)-f'(v_m)|-1$.
Comment: The proof of the Four-Color Theorem is probably the most famous example of proof-by-algorithm.
Comment: I've seen proofs of this kind: To prove that there is an algorithm that solves some problem in polynomial, it is shown that it can be reduced, in polynomial time, to another problem for which there exists a known algorithm that solves it in polynomial time. I'd call the known algorithm part of such a proof.
Answer: Yep! Proofs sometimes involve elaborate calculations: presenting an algorithm to do the calculation is a good way to show that the calculation can be done, and to analyze the results of the calculation.
In some fields -- e.g. graph theory -- algorithms are used very frequently. Often, the easiest way to prove that something can be done is to actually write down an algorithm that does it, and prove the algorithm works.
You might think of this approach as a systematic and convenient way to develop and organize complicated inductive proofs. But I would actually think of it the other way: induction is just a rather simplistic kind of algorithm for generating a proof. i.e. the algorithm is "use the argument I called the "base case" to prove it for one $1$, then iteratively apply the argument I called the "inductive step" to prove it for each successive positive integer".
Comment: "Prove the algorithm works" is very, very important.
Comment: Moreover, there is a connection between algorithms and proofs, known as the [Curry-Howard correspondence](https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence).
Comment: But what is the mathematical definition of an algorithm ? How can it be translated into pure maths (using sequences I guess) ? Is there any rules ? How to be sure the translation of some given algorithm is well constructed ?

(Curry-Howard may lead to the answer but........)
Answer: I confess that I have not read the paragraph enclosed (which contains some unexplained notation; anyway I am not an expert on graph theory), so this is an answer to your general question.
Absolutely yes an algorithm can be part of a proof.  In certain situations (and for those with certain inclinations) an algorithm can be the best possible kind of proof.  Let me give a simpler example.
In my linear algebra class recently I told the students that any permutation of $\{1,\ldots,n\}$ can be obtained as a composition of transpositions -- i.e., swapping two elements at a time.  This is not an obvious fact if you haven't thought about it before.  What was my proof?  Well, I said that in fact you can choose the transpositions to be adjacent elements, and then I told the students that the easiest way to see this is to think about how to actually do it in practice.  It is easy to give an algorithm: start with the element that you want to go in the $n$th place.  If it's there already, great.  If it isn't, then keep making a sequence of adjacent swaps bringing it one step closer to the $n$th position every time.  Do this until it gets into the $n$th position.  Now we can view what we have left as a permutation of $\{1,\ldots,n-1\}$ and work by induction.
The above argument is definitely an algorithm: it is something that a CS student would have little trouble programming.  And it is a convincing proof.  What's convincing about it of course is that you can see why the algorithm is doing what it's supposed to do.  We could write it more formally if we wanted to, as a global induction argument, and then we could use the well-ordering principle to argue that moving the element one step closer each time to where it wants to go means that it will eventually get there, but that seems like overkill in the present case.
In summary: an algorithm can definitely be part of a proof, but except for completely trivial cases an algorithm -- written in the form that a computer would accept, for instance -- should not be the entirety of the proof.  The other important part is an explanation for why the algorithm is doing what it is claimed to do.  Sometimes that's simple; sometimes it isn't.  There are in fact some amazing theorems that say (roughly) in general it is impossible to figure out what an algorithm will do, so the algorithms that are part of proofs need to be of the relatively simple kind whose workings can be explained to a human being.
Afterthought: By the way, "When is an algorithmic proof preferred and when is a pure thought/existence proof preferred?" would be a fantastic question, in my opinion.
Comment: Hi, could you write it more formally ? I am not sure all math students know how to write it formally and it could be a good exercise to practice mathematical reasoning. Moreover, I am looking for a method (rules or something) to translate this kind of algorithms into more formal math, do u have any idea or references ?

Thank u for your consideration
Answer: The proof shows how to renumber the vertices with the integers $1,\ldots,n$ in such a way that $|f\,'(v_\ell)-f\,'(v_m)|=1$, where $e=v_\ell v_m$ is the new edge, and $$|f\,'(x)-f\,'(y)|\le 2|f(x)-f(y)|$$ for each edge $xy$ of $G$. You have to think through the construction to see that it actually does this, but that's not too hard to do. This shows that $G+e$ has a numbering $f\,'$ such that
$$\max_{xy\in E(G)\cup\{e\}}|f\,'(x)-f\,'(y)|\le 2\max_{xy\in E(G)}|f(x)-f(y)|\;,\tag{1}$$
where $E(G)$ is the set of edges of $G$.
I assume from the context that $B(G)$ is the minimum over all numberings $g$ of $$\max_{xy\in E(G)}|g(x)-g(y)|\;;$$ $f$ is a numbering that achieves this minimum. Thus, $(1)$ shows that $G+e$ has a numbering $f\,'$ such that
$$\max_{xy\in E(G)\cup\{e\}}|f\,'(x)-f\,'(y)|\le 2B(G)\;.$$
It follows that if $f''$ is an optimal numbering, meaning one that achieves the minimum possible value of
$$\max_{xy\in E(G)\cup\{e\}}|g(x)-g(y)|\;,$$
then
$$B(G+e)=\max_{xy\in E(G)\cup\{e\}}|f''(x)-f''(y)|\le \max_{xy\in E(G)\cup\{e\}}|f\,'(x)-f\,'(y)|\le 2B(G)\;,$$
which is what the lemma claims.
It's true that this renumbering scheme can be thought of as an algorithm, but that's really beside the point: the real point is that it makes clear to the reader why the lemma is true, which is precisely what a proof is supposed to do. It's also true that just describing the scheme doesn't fill in all of the details of the proof; as I said, you still have to convince yourself that it works as stated. But that's true of all proofs outside of the very limited realm of formal theorem-proving: you always have to fill in some of the details for yourself.
Comment: wow this is brilliant. Thank you Brian! (+1)
Comment: @DonAnselmo: You're welcome!
Comment: @RémyHosseinkhanBoucher: I don't, I'm afraid. To be honest, I've never had much interest in formal proofs; to me the important thing is to describe the reasoning clearly enough that others can follow it and judge its correctness for themselves.
Comment: Hi @BrianM.Scott, I am looking for a method (rules or something) to translate any kind of algorithms used in proof into more formal math, do u have any idea ? Do you think the way to translate it into formal math is case specific ? How to be sure our translation is true ? (for instance, how do you know the formal proof you have given is the true translation of the algorithm?)
Thank u for your consideration
Answer: Here is a short answer to the question in your title. Typically, when one gives a constructive proof, in essence, the constructive argument forms the algorithm. An example that comes to my mind is again from combinatorics: Stable marriage theorem. The easiest way to prove the existence of a stable marriage is to provide an algorithm to construct one.
Comment: +1, I was going to give this exact same example myself.
Comment: Of course, just the fact that a proof is constructive doesn't necessarily mean it results in an *efficient* algorithm.  One example: given $n$ distinct points in the plane, there exists an ordering such that the cycle has no intersection between its edges (other than the obvious ones at vertices).  Proof: a "travelling salesman" permutation which minimizes the total length of the cycle must work - otherwise, if there's a crossing, you can reverse a part of the cycle to make the total length shorter.  But since there's no known efficient solution to the travelling salesman problem,
Comment: the algorithm directly translated from the proof isn't going to be efficient.  (On the other hand, you can construct an algorithm which goes through and sees when the reversal operation can make things shorter, and iterates until it finds no such reversal.  That algorithm, at least in practice, seems to have reasonably good runtime performance.)
Answer: By the Curry-Howard correspondence, any logical proposition in intuitionistic logic can be taken as the type signature of a lambda calculus expression. Equivalently one might use combinators rather than lambdas, and have one combinator corresponding to each logical axiom or inference rule.
Lambda calculus with types is powerful enough to be a real programming language; indeed there are several programming languages in use today which are little more than lambda calculus with additional types such as machine integers and efficient data structures, and a healthy dose of syntactic sugar.
Lambda calculus is also turing complete, meaning you can use a turing machine for a proof of a logical statement too.
Therefore, an algorithm (which has been proven correct) is a proof.
Answer: If you ask me, I would say that everything can be part of a proof as long as you bring a convincing reasonable argument. When I listen to my colleagues topologist, they make a few drawings (generally sketches of knots) on the blackboard and they claim it's a proof. Thus, a drawing or an algorithm, there is no big difference, the most important at the end of the day is that you are sure of what you assert, and leave nothing in the darkness.
Have a nice day :-)

Can an algorithm be part of a proof?


Regex string match for swift function call

Question: What I need is to return whole line that contains the word 'func' and ends with '{'
I want to detect function declaration in a swift file and add a comment as first line of the function body.
For example:
<code>NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(-[^{]+\\{)" options:NSRegularExpressionAnchorsMatchLines error:&error];
</code>
This returns me every objective C function declaration in any .m file. I just want the pattern that will replace ^(-[^{]+\{). So that I can apply for .swift file to detect swift function call.
The program is written in Objective-C so if anyone can give me Objective C pattern that returns line containing 'func' and ends with '{' - that will meet my requirement.
Comment: What have you tried? The difference between your old and new requirements seem rather minimal.
Answer: I thnk this will search ur exact pattern u r looking.I've added to search one more word after func .So it will find a function declared like this

func add {

\b(w{4})\s(\w+\s[{])
Comment: Your pattern does not match a literal `func`. Would this not make it too general?


Problema ao enviar um projeto para o GitHub

Question: Olá, tudo bem ? Estava enviando um projeto para o github e acabei encontrando um problema que ainda não tinha acontecido comigo.
error: src refspec master does not match any
error: failed to push some refs to 'https://github.com/xxx/xxx'

Pesquisei para encontrar a resposta, inclusive há respostas no próprio stack overflow, porém em inglês, que eu tentei me basear neles e solucionar mas não tive sucesso.
Se alguém conseguir me ajudar, ficarei muito grato !
Answer: Tente inicializar o git primeiro dentro da paste que está o seu código.
git init

Depois adicione um arquivo qualquer, pode ser um README.md
e realize o commando git commit -m "seu commit aqui"
depois faça o comando "git push origin master"
provavelmente irá funcionar.
Comment: $ git push origin master
error: src refspec master does not match any
error: failed to push some refs to 'origin'
infelizmente apareceu esses erros, sabe me informar o que pode ter sido ?
Comment: Digite o comando 'git status', e veja o que retorna.
Comment: Deu certo, muito obrigado !!


Communicate Stack Navigation with Drawer Navigation to login

Question: I am trying to make an application where navigation is, if the user has not logged in then I have a stack navigation with 3 screens (Welcome, Login, Register).
If I already log in then I change navigation and now I use a drawer navigation to be able to show the drawer at all times with a close session button.
The decision to use one navigation or another is taken by App.js through its state.
The problem is that since navigation I cannot modify the state of app.js so that it is rendered again and take the corresponding action.
Before it was a navigation drawer that inside it composes a navigation of stack.
The problem was that the drawer had to show a QR code that consumed it from an API. The QR code was not shown the first time the session was started because the drawer had already been rendered since the application started. Therefore, I was forced to change the logic in which I was doing things.
export default class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      loading:true,
      isLogged:false
    }
  }

  render(){
    let loading = this.state.loading;
    let logged = this.state.isLogged;
    if(loading != false){
      return(<Bienvenida />)
    }else{
      if(logged){
        return(<Navigation />)
      }else{
        return (<UserNavigation />)
      }
    }
  }
}

Answer: In this case, i would suggest using a switchNavigator.
A switchNavigator let you navigate trough screens like they were web pages, destroying the latest screen it had before.
The structure would be something like:
createSwitchNavigator({
    StackNav: {
        screen: stackNav,
    },
    DrawerNav: {
        screen: drawerNav
     }
})

Your stack would handle all the parts when the user is not logged. Then, when the user has logged in, you can pass from the stack to the drawer.
Same for a later logout, from the drawer you navigate to the stack
For more infos: https://reactnavigation.org/docs/en/switch-navigator.html


#block-system-main with no content interrupting my layout

Question: I have a drupal page with three blocks beeing rendered and floated besides each other in a content area. In the middle of these, Drupal renders out a block called #block-system-main with an empty content div. It breaks my floats, and I have no idea where this div is coming from or how to remove it.
Any ideas as to what could cause this and how I can remove it?
Comment: Already asked here: http://drupal.stackexchange.com/q/17026/16495, and by the way, wouldn't it be simpler to fix your layout by CSS means?
Comment: No, I'm not rendering out anything with hook_page_alter(), atleast not as far as I know. Yeah I could remove it with CSS but it feels so dirty, it shouldn't be there.
Comment: The solution could also be moving the block rendered by Drupal after your blocks. How are you creating the blocks? If it is by code, it would help to see your code.
Answer: I dont know where it comes from. Probably best would be if you can find that. But if you want to quick fix it. You could unset it in page preprocess
<code>function YOURTHEME_preprocess_page (&$variables, $hook) {
  unset($variables['page']['some_region']['block_id']);
</code>


How to name multi-sites for different environments (dev and staging)?

Question: I have a Drupal project that is a multi-site setup. I currently have my sites named like so:
sites/site1.example.dev
sites/site2.example.dev
sites/site3.example.dev

This is fine for working locally in development, as I can point my browser to site1.example.dev, site2.example.dev, or site3.example.dev and it works. However, when I push this up to staging, I want to be able to access these sites at the following addresses:
site1.example.com
site2.example.com
site3.example.com

Is it possible to simply name these as "[specific_name].example" and configure it so that I don't need to rename/update depending on the environment?
Thanks.
Answer: I think you may be looking into aliases.
On your sites folder there should be a example.sites.php. It basically allows aliasing sites to different names.
You could create an if and based on some environment condition (maybe the output of hostname? or a file somewhere that contains prod vs dev), enable or disable the aliases.
More documentation:

https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x
https://api.drupal.org/api/drupal/sites!example.sites.php/7.x
Answer: You can modify the site names for staging site in the file sites/site.php
Also update the settings.php file with the credentials of staging site.
Also need to update the site url from the host settings.


process of coming up with a definition or axiom?

Question: I am not a maths student but am very interested in the mathematical processes. A major part of mathematics is proofs. The steps carried out on the proofs are all based on the initial axioms or definitions. So my question is, are the initial axioms based on common sense and real world observation? is this normally how the first initial axiom or definition of any mathematical concept is created? Secondly, can it be the case where the definition can be wrong(since it is kind of an assumption but a very good one) when we apply the proof to tell something about the world? I hope to get some insights possibly from the mathematics majors or professors who happened to glance at it. Thanks!
Comment: You might like http://www.dartmouth.edu/~matc/MathDrama/reading/Wigner.html
Comment: thank you for sharing the article. ill comment after reading.
Comment: i am still looking for a simpler explanation that a layman can understand? please avoid mathematical jargons.
Answer: There are different collections of initial axioms to choose from.
Today, the standard is Zermelo–Fraenkel set theory with axiom of choice. There is also some interest in Zermelo-Fraenkel set theory without the axiom of choice, but it's not the mainstream.
One thing that should be made clear is that there is a big difference between axioms and definitions. Axioms are extremely simple, super super super essential and basic things, like "two sets are the same if they contain the same things" or "there is a such thing as an infinite set". These are things that you really can't argue with if you want to have a system of mathematics that makes any sense. There are very few options when it comes to what kind of axioms are reasonable.
Definitions, on the other hand, are much more specific, and you have lots of options there. You ask whether a definition can be wrong-- well, it can't really be wrong, no, because it's something you're assuming. But a definition can fail to be useful, or it can fail to describe something that you think it ought to. For example, there is always some discussion as to why $1$ isn't considered a prime number. What you're really asking there is whether the definition of a prime can include $1$. Whether you decide that $1$ is a prime number or not doesn't change the actual truth behind mathematics, but it will mean you have to phrase things differently. If you were to say $1$ is prime, then most theorems about prime numbers would have to be about "prime numbers except for 1", so ultimately it makes more sense to not call $1$ a prime number. This is the closest one gets to a definition being "wrong." Definitions are ultimately just a linguistic issue.
Comment: Axiom of choice can sometimes allow one to prove the existence of something without explicitly constructing it. See this article about [nonconstructive proofs](https://en.wikipedia.org/wiki/Nonconstructive_proof) for example. Some find this uncomfortable, particularly when the object being constructed is very counter-intuitive and unimaginable, such as a well-ordering of the real numbers, for example. Thus some don't feel that axiom of choice "ought to" be true. On the other hand, the statement of the axiom of choice seems very reasonable and obvious, so many others feel it "ought to" be true.
Comment: thank you. can you also comment on the possibility of an axiom being wrong since i assume there is no way to prove the correctness of an axiom?
Comment: @AlexanderGruber   Well I am not a set theory specialist, but if I may ask what is the controversery  behind axiom of choice,  how would you reply in a way as simple as possile?Thanks sir.
Answer: I'll approach this topic from something like a Platonist perspective.
We all know that there is such a thing as a "counting number". If we have a discrete, finite collection of apples, we can describe the collection by saying there are 2, 3, or even zero of them. We also know that when we put three apples with seven, we always get ten apples. And similarly, when we have a collection of three pairs added to one of seven, we get a collection of ten pairs. This leads us to the intuition that there are some inherent properties about things like "seven" and "three" which are independent of apples and pears. That is, this leads us to the notion that numbers (and the addition operation) exist in their own right.
Since we've decided that there is a "collection" of "counting numbers", the next step is to describe its properties in the hopes of making deductions about these "counting numbers" from things we know to be true about them. Axioms are therefore viewed as a way of specifying logically what we're trying to describe.
Suppose I told you of a mathematical collection known as $\mathbb{N}$ which is the collection of "counting numbers". How could I mathematically convey to you what it is that I'm describing?
As I describe adding each axiom, I encourage you to visualise the "bad $\mathbb{N}$" examples I'm providing by drawing out $\mathbb{N}$ as a collection of dots with an arrow between $n$ and $S(n)$. The imagery will be clearer if you can visualise it.
I would probably begin by telling you that something called $0$ is an element of $\mathbb{N}$ and that for every $n$ which is an element of $\mathbb{N}$, we have some element known as $S(n)$ which is also in $\mathbb{N}$.
This doesn't tell you much of anything about $\mathbb{N}$. The collection could have as few as $1$ element (perhaps it contains only $0$, and $S(0) = 0$), or an arbitrarily large collection of elements.
So we add in the principle that for every $n$, $S(n) \neq 0$. What does this tell us about $\mathbb{N}$?
It tells us that $\mathbb{N}$ has at least two elements, $0$ and $S(0)$. But it could be that $S(S(0)) = S(0)$ - that is, $\mathbb{N}$ could have exactly 2 elements. Obviously, a set with two elements isn't what we mean by the collection of "counting numbers", so I will have to be more specific.
The next principle I would articulate is that for every $n$ and every $m$, if $S(n) = S(m)$ then $n = m$. This tells us that $\mathbb{N}$ must have infinitely many elements. But it does not necessarily describe what we're looking for. For example, we could have $\mathbb{N}$ consisting of two chains $0, S(0), S(S(0)), ...$ and $w, S(w), S(S(w)), ...$ where $w$ is not the successor of any $n$. This is obviously not what we're looking for.
We might try to add in an axiom that every $n$ is either $0$ or a successor. However, this still leaves the possibility in play that $\mathbb{N}$ could consist of sequence $0, S(0), S(S(0)), ... $ together with some $w$ such that $w = S(w)$. This is again obviously not what we mean.
We could try to add in another axiom that no $n$ can equal $S(n)$. But this still leaves open yet another possibility - a "single-ended chain" consisting of $0, S(0), S(S(0)), ...$ and a "double-ended chain" $..., S^{-1}(S^{-1}(w)), S^{-1}(w), w, S(w), S(w), S(S(w)), ...$. Again, this is not what we know "counting numbers" should look like!
In order to fully characterise the natural numbers, I would therefore need the Axiom of Induction. (For simplicity's sake, we'll gloss over differences in 1st and 2nd order logic). This says that for every property $P$ that a number might have (where $n$ having property $P$ is written as $P(0)$), if $P(0)$ and if for every $n$, $P(n)$ implies $P(S(n))$, then it must be the case that for all $n$, $P(n)$.
This axiom is enough to specify exactly what we mean by the "counting numbers".
In the same way, the axioms of Set Theory are designed to describe some abstract notion of "set". Generally, the notion of a set in ZFC is some kind of well-founded tree. However, we can prove interesting things about the logical system of ZFC by finding other collections which seemingly have little to do with the intuitive notion of a set but which nevertheless satisfy the axioms of ZFC. This is how one can prove, for example, the independence of the continuum hypothesis (though obviously, a lot of mathematical sophistication is required to understand this proof).
Can an axiom be "wrong"? According to the school of thought that axioms are there to describe mathematical things which exist in their own right, an axiom is "wrong" if it doesn't describe the objects you think it describes. This is obviously very subjective in practice - to some, the Axiom of Choice is a self-evident property of sets, while to others, it self-evidently cannot be.
There is one way to prove beyond a shadow of a doubt that an axiom is wrong. You could prove that the axiom is inconsistent - that is, that it's possible to derive a contradiction from it. Bertrand Russell famously gave set theory a frightful scare by using the widely accepted axioms of set theory to prove Russell's Paradox. After he did this, everyone agreed that since contradictions cannot exist, there's no way that the axioms leading to the contradiction could possibly all be true. This led to the revision of the axioms of set theory.
Interestingly, a similar paradox was found during the development of Martin-Lof type theory, a theory with very different characteristics from set theory, by considering a "type of all types" just as set theory once incorrectly considered a "set of all sets". This suggests that there are some deep underlying constraints on how "big" collections can be that are in some sense independent of foundation.
I myself lean more towards the Formalist view of axioms, which goes something like this:
When mathematicians prove something, they are just following a set of rules in a game to reach an outcome. There is not necessarily any philosophical significance at all in the fact that some theorem holds in ZFC other than the fact that, following the axioms of ZFC and the rules of first-order logic, it is possible to prove that theorem.  ZFC doesn't necessarily "describe" a "real collection of sets" or indeed any real collection at all; rather, it is a set of axioms which can apply to a wide range of mathematical constructions, many of which look nothing alike on the surface.
I do, however, tend to believe that there "really is" such a thing as $\mathbb{N}$. In that sense, I don't take the extreme positions of the finitists, who say that (in some sense, some kinds of) infinities do not exist and therefore, any mathematical theory dealling with infinite objects has value only insufar as it can tell us truths about finite objects.
As far as proofs being applied to things in the "real world", this ventures more into the realm of physics and the sciences than pure mathematics. Most scientists, like Feynman famously did, would say that the only test of a scientific fact is experiment. On this view, the fact that mathematics can help us make sense of the world is, at worst, a happy coincidence and at best a result of the fact that humans specifically developed math to try to understand the real world.
After all, the theory of "counting numbers" originally came about to understand such phenomena as putting three apples with seven, just as the theory of plane geometry came about to understand real physical surfaces and the theory of calculus came about to describe physics. It's no surprise that our mathematical tools do exactly what we designed them to.


Interpreting Cox regression

Question: My regression results are as follows.
<code>Variable    B          exp(B)
age        0.004575    1.004586
capital    0.2250      1.2524
year      -0.1026      0.9024
</code>
Can someone please help me to interpret these?
(eg: one year increase in age would increase/decrease the hazard by Xx%)
Answer: For two covariates ($x_1$ and $x_2$), the Cox model is written as (with standard notations)
$$
h(t; x_1, x_2) = h_0(t) \exp(x_1 \beta_1 + x_2 \beta_2).
$$
To interpret $\beta_1$, note that
$$
\frac{h(t; x_1 + 1, x_2)}{h(t; x_1, x_2)}
 = \exp(\beta_1).
$$
In words, the previous equation tells us that whenever $x_1$ increases by 1 unit ($x_2$ being held fixed), the hazard rate is multiplied by $\exp(\beta_1)$.
On the log-scale, we have
$$
\log(h(t; x_1 + 1, x_2)) - \log(h(t; x_1, x_2)) = \beta_1.
$$
Answer: For every unit increase in year, the hazard decreased by 9.8% assuming the other variables are held constant.

Interpreting Cox regression


EST time conversion with daylight saving time

Question: EST time conversion with daylight saving time it is coming wrongly
private void timeConversion() {
    String s = "2016-08-29 1:40:00 AM";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.ENGLISH);
    df.setTimeZone(TimeZone.getTimeZone("EST"));
    Date timestamp = null;
    try {
        timestamp = df.parse(s);
        df.setTimeZone(TimeZone.getDefault());
        System.out.println(df.format(timestamp));
    } catch (ParseException e) {
        e.printStackTrace();

    }
}

Comment: what is your expected output and what are you getting??
Comment: 1 hr is different bz daylight saving time is missing.
Answer: The time zone EST does not respect any daylight saving time offsets:
TimeZone estTz = TimeZone.getTimeZone("EST");
System.out.println(estTz.useDaylightTime()); // prints 'false'

That is the time zone EST will always have a -5:00 hour offset to UTC.
This is probably due to some locations in Canada, Mexiko and Central America (Panama) not using DST but using EST all the year.
If you want a time zone with DST offset, you should use something like US/Eastern or America/New_York, etc:
TimeZone usEasternTz = TimeZone.getTimeZone("US/Eastern");
System.out.println(usEasternTz.useDaylightTime()); // prints 'true'


Migrating Multiple Files in a Node

Question: I am trying to migrate files to a content type called educational activity. My issue is that some instances of this content type have more than one file attachment. So what I am trying to do is use concatenation to get all the file names in one field and then append them to the node like it's done with multi-value fields. However the migration outputs: "ltrim() expects parameter 1 to be string, array given". It seems that after the concatenation I end up with an array of arrays instead of an array with file names, but I can't figure out why.
This is the code:
<code>class EducationalActivityMigration extends EduMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

# Human-friendly description of your migration process. Be as detailed as you like.

$this->description = t('Migrate the Educational Activity content type along with its fields');

/**
 * We create the mapping in the database to be migrated instead of our default db.
 * Map Tables issue: http://drupal.org/node/1014558.
 */

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'nid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Node ID',
                       'alias' => 'n'
                      )
    ),
    MigrateDestinationNode::getKeySchema(), 'migrationDB');

$query = Database::getConnection('default', 'migrationDB')
           ->select('node', 'n');
$query->leftJoin('content_field_description', 'fd', 'n.nid = fd.nid');
$query->join('node_revisions', 'nrevi', 'nrevi.vid = n.vid');
//$query->leftJoin('node_revisions', 'nrev', 'n.nid = nrev.nid');
$query->leftJoin('content_field_age', 'fa', 'n.nid = fa.nid');
$query->leftJoin('content_field_target_group', 'tg', 'n.nid = tg.nid');
$query->leftJoin('content_field_rights_type', 'rt', 'n.nid = rt.nid');
$query->leftJoin('content_field_rights_holder', 'rh', 'n.nid = rh.nid');
$query->leftJoin('content_field_use_license', 'ul', 'n.nid = ul.nid');
$query->leftJoin('content_field_educational_stage', 'es', 'n.nid = es.nid');
$query->leftJoin('content_field_course', 'co', 'n.nid = co.nid');
$query->leftJoin('content_field_class', 'cl', 'n.nid = cl.nid');
$query->leftJoin('content_field_related_key_competence', 'rkc', 'n.nid = rkc.nid');
$query->leftJoin('content_field_filename', 'fi', 'n.nid = fi.nid');
$query->leftJoin('files', 'fil', 'fil.fid = fi.field_filename_fid');
$query->leftJoin('content_field_images', 'fim', 'n.nid = fim.nid');
$query->leftJoin('files', 'file', 'file.fid = fim.field_images_fid');
$query->addExpression('GROUP_CONCAT(DISTINCT fa.field_age_value)', 'age_list');
$query->addExpression('GROUP_CONCAT(DISTINCT tg.field_target_group_value)', 'target_list');
$query->addExpression('GROUP_CONCAT(rt.field_rights_type_value)', 'rights_list');
$query->addExpression('GROUP_CONCAT(DISTINCT rh.field_rights_holder_value)', 'holder_list');
$query->addExpression('GROUP_CONCAT(ul.field_use_license_value)', 'license_list');
$query->addExpression('GROUP_CONCAT(es.field_educational_stage_value)', 'edustage_list');
$query->addExpression('GROUP_CONCAT(DISTINCT co.field_course_value)', 'course_list');
$query->addExpression('GROUP_CONCAT(DISTINCT cl.field_class_value)', 'class_list');
$query->addExpression('GROUP_CONCAT(DISTINCT rkc.field_related_key_competence_value)', 'competence_list');
$query->addExpression('GROUP_CONCAT(fil.filename)', 'file_list');
//$query->addExpression('GROUP_CONCAT(file.filename)', 'image_list');
$query->fields('n')
        ->fields('fd', array('field_description_value'))
        ->fields('nrevi', array('body'))
        ->fields('fa', array('field_age_value'))
        ->fields('tg', array('field_target_group_value'))
        ->fields('rt', array('field_rights_type_value'))
        ->fields('rh', array('field_rights_holder_value'))
        ->fields('ul', array('field_use_license_value'))
        ->fields('es', array('field_educational_stage_value'))
        ->fields('co', array('field_course_value'))
        ->fields('cl', array('field_class_value'))
        ->fields('rkc', array('field_related_key_competence_value'))
        ->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
        ->fields('file', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
        ->condition('type', "educational_activity",'=')
        ->groupBy('n.nid');

# Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query);

# Set up our destination node as the Educational Activity node
$this->destination = new MigrateDestinationNode('educational_activity');

/**
 *  FIELDS WITH THE SAME NAME IN BOTH DBs
 *
 *  @nid: The primary identifier for a node.
 *  @title: General title of the node in plain text.
 *  @status: Boolean expression stating if the node is published.
 *  @created: Integer type timestamp of the node's creation.
 *  @changed: Integer type timestamp of the node's latest change.
 *  @promote: Boolean expression indicating if the node is present in the front page.
 *  @sticky: Boolean expression stating if the node should be at the top of the list wherever it appears.
 *  @comment:Shows whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write).
 *
 */

$this->addSimpleMappings(array ('title', 'status', 'created', 'changed', 'promote', 'sticky',
'comment'));

/**
 *  FIELDS WITH DEFAULT VALUES
 *
 *  @uid: value "36" corresponds to "grammateia" user.
 *  @language: default value set to "Ellinika".
 *  @translate: default value set to False.
 *  @tnid:The translation set id for this node, which equals the node id of the source post in each set.
 *  @revision_uid: The user id that shows which user did the revision.
 */

$this->addFieldMapping('uid')
  ->defaultValue($user);
  $this->addFieldMapping('language', 'language')
    ->defaultValue('el');
    $this->addFieldMapping('translate', 'translate')
    ->defaultValue('FALSE');
    $this->addFieldMapping('tnid', 'tnid')
    ->defaultValue('0');
    $this->addFieldMapping('revision_uid')
  ->defaultValue($user);

/**
 * FIELDS PENDING MIGRATION
 *
 * @vid: It means 'version id'. For every node in the node table, Drupal can save multiple versions in the node_revisions table.
 * The version id is the unique identifier in the node_revisions table.
 */

$this->addFieldMapping('vid', 'vid')
     ->description(t('Pending Migration Status'))
     ->issueGroup(t('What are gonna do with these?'));

/**
 * SOURCE FIELDS NOT TO BE MIGRATED
 *
 * @type: Shows the content type, not needed since we input the type in the MigrateDestinationNode constructor.
 * @moderate: Boolean expression showing if the node is under moderation. Moderation support has moved out of core.
 */

$this->addUnmigratedSources(array ('type', 'moderate', 'field_programma_ekpaid', 'field_syggrafiki_omada_ekp', 'field_schoolunit_ekp', 'fid','filepath', 'filemime', 'filesize', 'timestamp', 'file_fid', 'file_filepath', 'file_filemime', 'file_filesize', 'file_timestamp'), t('Source fields that we will not be migrating'));

/**
 * DESTINATION FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedDestinations (array('revision', 'log', 'is_new', 'field_rights_holder:language', 'field_keywords',
'field_keywords:source_type', 'field_keywords:create_term', 'field_keywords:ignore_case', 'field_knowledge_tree_category',
'field_knowledge_tree_category:source_type', 'field_knowledge_tree_category:create_term', 'field_knowledge_tree_category:ignore_case',
'field_tag', 'field_tag:source_type', 'field_tag:create_term', 'field_tag:ignore_case', 'field_related_item:language', 'field_body:summary',
'field_body:format', 'field_body:language', 'field_description:language', 'field_description:format', 'field_attachment:destination_file', 'field_attachment:description', 'field_attachment:display'),t('Destination fields that we will not be migrating'));

/**
 * FIELDS TO BE MIGRATED
 */

 $this->addFieldMapping('field_body', 'body')
      ->arguments(array('format' => 'full_html'));
 $this->addFieldMapping('field_description', 'field_description_value')
      ->arguments(array('format' => 'full_html'));
 $this->addFieldMapping('field_age', 'age_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_age_value'));
 $this->addFieldMapping('field_target_group', 'target_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_target_group_value'));
 $this->addFieldMapping('field_rights_type', 'rights_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_rights_type_value'));
 $this->addFieldMapping('field_rights_holder', 'holder_list')
      ->separator('--')
      ->arguments(array('source_type' => 'field_rights_holder_value'));
 $this->addFieldMapping('field_use_license', 'license_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_use_license_value'));
 $this->addFieldMapping('field_educational_stage', 'edustage_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_educational_stage_value'));
 $this->addFieldMapping('field_course', 'course_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_course_value'));
 $this->addFieldMapping('field_class', 'class_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_class_value'));
 $this->addFieldMapping('field_related_key_competence', 'competence_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_related_key_competence_value'));

 $this->addFieldMapping('field_attachment:file_class')
      ->defaultValue('MigrateFileUri');
 $this->addFieldMapping('field_attachment:language')
      ->defaultValue('el');
 $this->addFieldMapping('field_attachment:destination_dir')
      ->defaultValue('sites/default/files/educational_activity');
 $this->addFieldMapping('field_attachment:file_replace')
      ->defaultValue('FILE_EXISTS_REUSE');
 $this->addFieldMapping('field_attachment:preserve_files')
      ->defaultValue(TRUE);
 $this->addFieldMapping('field_attachment:source_dir')
      ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

 #Copy files (word etc)
 $this->addFieldMapping('field_attachment', 'file_list')
      ->separator(',')
      ->arguments(array('source_type' => 'filename'));

 #Copy Images
 //$this->addFieldMapping('field_attachment', 'image_list')
      //->separator(',')
      //->arguments(array('source_type' => 'filename'));

/**
 * We conditionally DNM these fields, so your field mappings will be clean,
 * whether or not you have path and or pathauto enabled.
 */

if(module_exists('path')) {

  $this->addFieldMapping('path')
       ->issueGroup(t('DNM'));
  if (module_exists('pathauto')) {
    $this->addFieldMapping('pathauto')
         ->issueGroup(t('DNM'));
  }

}//if ends

}//construct ends

}//class ends
</code>
Unfortunately, I didn't come to a working solution reading all the other questions.
Comment: *Update: Creating a separate table with all the information needed in order to avoid using one of the left joins, results in the same error. It seems that copying multiple files is not properly supported. Still investigating...
Comment: Did you try implementing prepareRow() function to transform your source field in an array?
Comment: No not yet, had it in mind though, but haven't had the time. I will certainly give it a try, thanks for the input.
Answer: So after managing to spend some time resolving this issue, I managed to migrate multiple files in a node like so:
To begin with this line:
<code>$query->addExpression('GROUP_CONCAT(fil.filename)', 'file_list');
</code>
becomes:
<code>$query->addExpression('GROUP_CONCAT(DISTINCT fil.filename)', 'file_list');
</code>
Cause we need to avoid migrating duplicates.
Secondly, this line:
<code>->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
</code>
became:
<code>->fields('fil', array('filename'))
</code>
We don't really need to migrate this info cause the migration process can discover these values by itself. If however anyone believes that these should be migrated please advise.
And last and more importantly these lines:
<code> $this->addFieldMapping('field_attachment:file_class')
  ->defaultValue('MigrateFileUri');
$this->addFieldMapping('field_attachment:language')
  ->defaultValue('el');
$this->addFieldMapping('field_attachment:destination_dir')
  ->defaultValue('C:/xampp/htdocs/testpaideia/sites/default/files/educational_activity');
$this->addFieldMapping('field_attachment:file_replace')
  ->defaultValue('FILE_EXISTS_REUSE');
$this->addFieldMapping('field_attachment:preserve_files')
  ->defaultValue(TRUE);
$this->addFieldMapping('field_attachment:source_dir')
  ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

#Copy files (word etc)
$this->addFieldMapping('field_attachment', 'file_list')
  ->separator(',')
  ->arguments(array('source_type' => 'filename'));
</code>
become:
<code>#Copy files (word etc)
$this->addFieldMapping('field_attachment', 'file_list')
      ->separator(',');

 $this->addFieldMapping('field_attachment:file_class')
      ->defaultValue('MigrateFileUri');
 $this->addFieldMapping('field_attachment:language')
      ->defaultValue('el');
 $this->addFieldMapping('field_attachment:destination_dir')
      ->defaultValue('sites/default/files/educational_activity');
 $this->addFieldMapping('field_attachment:file_replace')
      ->defaultValue('FILE_EXISTS_REPLACE');
 $this->addFieldMapping('field_attachment:preserve_files')
      ->defaultValue(FALSE);
 $this->addFieldMapping('field_attachment:source_dir')
      ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');
</code>
We need to map the primary field (in my case field_attachment) before its subfields (e.g. field_attachment:preserve_files, field_attachment:file_replace etc.), otherwise the migration fails. That's it hope it was helpful.

Migrating Multiple Files in a Node


xmlns declaration broke my xPath filter

Question: I have realized a really stupid xPath filter in MatLab:
% Construct the DOM.
docNode = xmlread('C:\Users\MATLAB\test.gpx');

% get the xpath mechanism into the workspace
import javax.xml.xpath.*
factory = XPathFactory.newInstance;
xpath = factory.newXPath;

% compile and evaluate the XPath Expression
expression = xpath.compile('gpx/AddressBook/Entry/PhoneNumber');
phoneNumberNode = expression.evaluate(docNode, XPathConstants.NODE);
phoneNumber = phoneNumberNode.getTextContent

With this XML (specifically a .gpx file) it works:
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
<gpx version='1.1' creator='TTTracklog V.1.13'>
    <AddressBook>
       <Entry>
          <Name>Friendly J. Mathworker</Name>
          <PhoneNumber>(508) 647-7000</PhoneNumber>
          <Address hasZip="no" type="work">3 Apple Hill Dr, Natick MA</Address>
       </Entry>
    </AddressBook>
</gpx>

and text (508) 647-7000 is returned.
Simply adding xmlns attribute to gpx node in this way:
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
<gpx version='1.1' creator='TTTracklog V.1.13'  xmlns='http://www.topografix.com/GPX/1/1'>
    <AddressBook>
       <Entry>
          <Name>Friendly J. Mathworker</Name>
          <PhoneNumber>(508) 647-7000</PhoneNumber>
          <Address hasZip="no" type="work">3 Apple Hill Dr, Natick MA</Address>
       </Entry>
    </AddressBook>
</gpx>

gave me error, and matlab report:

??? Attempt to reference field of non-structure array.
Error in ==> test at 12 phoneNumber = phoneNumberNode.getTextContent

Why? How can I avoid that error?
Comment: I don't know MatLab, but from an XML point of view, you have now placed your gpx (etc.) element in the http://www.topografix.com/GPX/1/1 namespace, and XPath is looking for it in the global namespace. You need to somehow make the namespace known to MatLab and then qualify the gpx element in the XPath expression.
Comment: @_Mariano: Was my answer useful?
Comment: Good question, +1. In case you don't have mechanisms in Matlab to register a namespace, you can alwys use an expression like this: `*[name()= 'gpx']
    /*[name()='AddressBook']
       /*[name()='Entry']
          /*[name() = 'PhoneNumber']`
Answer: In case you cannot register the default namespace with an associated prefix, use:
*[name()= 'gpx']
    /*[name()='AddressBook']
       /*[name()='Entry']
          /*[name() = 'PhoneNumber']

instead of:
gpx/AddressBook/Entry/PhoneNumber

Here is a complete, XSLT-based, verification:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
     <xsl:copy-of select=
     "*[name()= 'gpx']
    /*[name()='AddressBook']
       /*[name()='Entry']
          /*[name() = 'PhoneNumber']
   "/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
<gpx version='1.1' creator='TTTracklog V.1.13'  xmlns='http://www.topografix.com/GPX/1/1'>
    <AddressBook>
       <Entry>
          <Name>Friendly J. Mathworker</Name>
          <PhoneNumber>(508) 647-7000</PhoneNumber>
          <Address hasZip="no" type="work">3 Apple Hill Dr, Natick MA</Address>
       </Entry>
    </AddressBook>
</gpx>

the wanted element is selected and copied to the output:
<PhoneNumber xmlns="http://www.topografix.com/GPX/1/1">(508) 647-7000</PhoneNumber>

Comment: The code:
`e1 = xPath.compile('*[name()= "gpx"]/*[name()= "trk"]');
    s = e1.evaluate(gpx, XPathConstants.NODESET);
    sNumber = s.getLength;`
compile and return me exact value. While
`e2 = xPath.compile('*[name()= "gpx"]/*[name()= "trk[1]"]/*[name()= "trkseg"]');
    s = e2.evaluate(gpx, XPathConstants.NODESET);
    sNumber = s.getLength;`
always return 0 value. Why? Is this for '[1]' of the second expression?
Comment: @Mariano: Of course. Names can only contain alphanumeric characters (starting with alpha) -- not `[]`. You actually want: `*[name()='trk'][1]`
Comment: You are the man! Last thing: what about attribute? For example: how can I get latitude and longitude with this notation?
I have something like `gpx/trk[1]/trkseg[1]/trkpt[2]/@lat` that i need to rewrite using name().
Comment: @Mariano: There are no `lat` attributes (and also no attributes with names that could be for longitude, in your provided XML document. So this is just my *guess* having not seen the XML document alluded for -- use: `*[name()='gpx']/*[name()='trk'][1]/*[name()='trkseg'][1]/*[name()='trkpt'][2]/@lat`
Comment: Look this: http://en.wikipedia.org/wiki/GPS_eXchange_Format
Attributes "lat" and "lon" are written inside `trkpt` tag.

Anyway you was right! ;)
Comment: How I can select subling with name()?
Comment: @Cherry, `following-sibling::*[name() = 'xxx']`
Answer: Dabbler's comment above is correct. Since you have added a default namespace to your XML document, you must also alter your XPath expression to search for nodes in your new default namespace.
Unqualified names in XPath expressions (like AddressBook) are in the null XML namespace, not the default XML namespace of your document.
So you want to somehow register your new namespace with your xpath object. Like:
{"foo": "http://www.topografix.com/GPX/1/1"}

and then alter your XPath expression to:
foo:gpx/foo:AddressBook/foo:Entry/foo:PhoneNumber

There are docs on how to do this with the javax.xml.xpath API here:
http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html#N1022D
However, I'm not sure how this translates to Matlab, exactly.
Comment: You're right! I should declarate a path name. I've posted the question on matlab forum. I will report it as soon they will answer me.
Comment: Should translate exactly, because it's using the Java classes.
Comment: For a MATLAB-specific implementation, I posted an example in this blog comment: http://blogs.mathworks.com/desktop/2010/11/01/xml-and-matlab-navigating-a-tree/#comment-8353 You still need to use a java class for the NamespaceContext

xmlns declaration broke my xPath filter


Why is the exprected value of a sum of RV following a Z-distribution not equalt to 0?

Question: I am using R to draw a thousand of RVs from a Z-distribution.
I noticed that the expected value of their mean is as expected ~0 (magnitude 10^(-4)) sometimes positive, sometimes negative but; the sum of their mean is significatively far from 0. Why?
mean(colMeans(replicate(n = 1000, expr = rnorm(n = 1000, sd = 1, mean = 0))))
Or
$E((E[X])) = 0$
And
sum(colMeans(replicate(n = 1000, expr = rnorm(n = 1000, sd = 1, mean = 0))))?
Or
$\sum E[X] != 0$
Answer: You seem confused about what an expectation is. It's not the same thing as a sample mean.
What you have demonstrated is not that the expectation is different, but rather than the variability is different -- the expectation is actually 0 for both cases but the variance is much larger in the second case (indeed, the variance is a million times as big), so naturally the first is generally closer to zero than the second.
If you simulate each repeatedly you'll see that they both scatter around 0 but the sum one just has a bigger spread.

Zooming in on the upper one:

As we see they're both scattered around 0 but the sum is just more spread out.


Como criar e manipular listas em PHP?

Question: Em Java é possível criar e manipular lista de qualquer tipo de dado utilizando o List<E>, veja o exemplo abaixo:
List<String> lista = new ArrayList<>();
lista.add("Stack");
lista.add("Over");
lista.add("flow");

Criei uma lista de tipo String e adicionei três valores a ela através do método add().
Em PHP existe algum recurso semelhante ao Java para manipulação e criação de listas?
Comment: Bem no PHP você consegue manipular uma lista, mais ou menos desse jeito ai, mas não vai conseguir restringir os tipos de dados que a lista vai receber.
Comment: Relacionada:[Trabalhar com listas sem ser usando Array() em PHP](http://pt.stackoverflow.com/q/110132/28595)
Comment: Concordo com quase tudo que estão dizendo, mas, eu consigo sim criar uma enumeração sem `if` com tipo passado nos métodos (já acontecia isso em versão anteriores do PHP e agora fortemente na versão 7) com retorno também de um determinado tipo. Claro que não é `Generics` igual C# ou Java, mas, eu consigo criar a enumeração particular, que ao meu ver dependendo do caso não precisa, imagine criar um enumeração para cada `classe` seria ruim para o desenvolvimento.
Answer: PHP não é uma linguagem com muita disciplina de tipos.
Em PHP existe um recurso chamado array. O array pode ser uma lista numerada ou indexada - e pode também ser as duas coisas ao mesmo tempo.
Por exemplo:
 $arr = [];

 $arr[] = "Stack";
 $arr[] = "Over";
 $arr[] = "Flow";

Resultado:
[
  "Stack",
  "Over",
  "Flow",
]

Nesse caso, a ordem do array não depende da numeração/nomeação que um índice recebe, e sim na ordem que são exibidos.
Então isso abaixo daria certo:
 $arr[98] = "Stack";
 $arr['96'] = "Over";
 $arr[97] = "Flow";

[
  98 => "Stack",
  96 => "Over",
  97 => "Flow",
]

SplFixedArray - um recurso do SPL
Na minha opinião, o mecanismo do PHP mais próximo ao apresentando na pergunta é a classe SplFixedArray. Essa classe faz parte da biblioteca padrão do PHP, chamada SPL. Com essa classe, é possível determinar um objeto com uma lista, com um número limitado de elementos.
Veja:
 $arr = new SplFixedArray(3);

 $arr[] = 1;
 $arr[] = 2;
 $arr[] = 3;
 $arr[] = 4; // Lança uma exceção, pois o número é limitado.

Mas, voltando novamente ao início dessa resposta, o recurso que você precisa seria o array mesmo. O SplFixedArray garante o limite de elementos que serão adicionados, mas não tem restrição de tipos.
Você pode fazer uma implementação
No PHP existe duas interfaces especiais chamadas ArrayAccess e Iterator. Com essas duas, é possível criar uma classe, determinando o tipo de elementos que poderão ser adicionados à sua lista.
Veja um exemplo que montei para você:
class StringList implements ArrayAccess, IteratorAggregate
{
    protected $items = [];

    public function offsetSet($key, $value)
    {
        if (is_string($value)) {

            $key ? $this->items[$key] = $value : array_push($this->items, $value);

            return $this;
        }

        throw new \UnexpectedValueException('Essa é uma lista que aceita somente string');
    }

    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    public function offsetExists($key)
    {
        return isset($this->items[$key]);
    }

    public function offsetUnset($key)
    {
        unset($this->items[$key]);
    }

    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }
}

A utlização da classe seria assim:
$list = new StringList;
$list[] = 'Wallace';
$list[] = 'Maniero';
$list[] = 'Denner Carvalho';
$list[] = 1; // Se fizer isso vai lancar exceção

foreach ($list as $string) {
    var_dump($string);
}

Veja isso funcionando no Ideone.

Nota: A classe criada acima é apenas um exemplo. Fica a critério de cada um como implementar algum recurso, porém eu não creio que seja viável fazer como exemplificado, já que o PHP é uma linguagem fracamente tipada (nada de sair dando uma de master of OOP ;) ).

Ainda quer ir mais longe com isso?
No PHP 7, existe um recurso que te permite definir o tipo do argumento de uma função. Combinando isso com o operador ellipsis, você pode fazer um "hack" para criar um array (estilo lista) com tipos específicos.
Veja:
function int_list(int ...$strings)
{
    return $strings;
}

int_list(1, 2, 3, 4, 5);

Se você adicionasse uma string (que não fosse numérica), retornaria um erro:
int_list(1, 2, 3, 4, 5, 'x');

Erro retornado:

Argument 6 passed to int_list() must be of the type integer, string given

Outros recursos disponíveis no SPL
Além de você poder implementar, o PHP também oferece alguns recursos novos, como a classe chamada SplObjectStorage, que tem a finalidade de trabalhar com armazenamento de objetos.
Além do já citado, contamos também com:

SplDoublyLinkedList
SplStack
SplQueue
SplHeap
SplMaxHeap
SplMinHeap
SplPriorityQueue
SplFixedArray
SplObjectStorage

Além dessa listinha aí, talvez seja importante citar sobre os Generators.
É claro que esses recursos jamais se compararão com uma linguagem tipada, como no caso do Java ou C#.
Leia mais:

Pra que serve a classe SplStack?
The SplDoublyLinkedList class
Quais as vantagens de usar um "generator" (yield) no PHP?
Comment: Falou em SPL, morreu pra mim :D
Comment: @bigown concordo em parte, eu pessoalmente não uso, mas `spl_autoload` é quase fundamental XD PS: +1
Answer: É o array normal mesmo. O array do PHP não é um array de verdade, como conhecemos em outras linguagens. Eles são listas por definição.
Lembre-se que PHP é uma linguagem de script, ela não foi feita para ter a melhor robustez e performance na aplicação das estruturas de dados. Entretanto isso dá grande flexibilidade e facilidade de uso. Java prefere o caminho de especialização para obter o melhor resultado.
PHP é uma linguagem dinamicamente tipada, e as estruturas permitem colocar qualquer coisa. Então se quer saber se tem como restringir que a lista só aceite strings. Não dá. Teria que ter algoritmos para garantir isso.
Claro que você pode criar uma classe para abstrair esse tratamento se quiser. Tudo será resolvido em tempo de execução (em PHP é sempre assim mesmo), ou seja, vai ter um if na hora de adicionar o elemento que verificará se é string para permitir a inclusão ou não. As implementações normalmente serão ingênuas e terão performance de HashMap e não de Array, como acontece em listas no Java. Mas em PHP ninguém liga para performance.
Exemplo:
$lista = [];
$lista[] = "Stack";
$lista[] = "Over";
$lista[] = "flow";

Há quem prefira com aray_push():
$lista = array();
array_push($lista, "Stack");
array_push($lista, "Over");
array_push($lista, "flow");

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que o array do PHP pode assumir uma forma associativa, ou seja, pode se comportar como o HashMap, ou seja é um par de chave e valor. Você não tem muito controle sobre isso. Basta colocar um elemento que fuja de uma sequência e já é uma mapa.

Como criar e manipular listas em PHP?


Redirect non-www to www in .htaccess

Question: I have this in my .htaccess file:
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com$1 [R=301,L]

but whenever I access a file on my root like http://example.com/robots.txt it will redirect to http://www.example.comrobots.txt/.
How can I correct this so that it will redirect correctly to http://www.example.com/robots.txt?
Answer: Change your configuration to this (add a slash):
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

Or the solution outlined below (proposed by @absiddiqueLive) will work for any domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

If you need to support http and https and preserve the protocol choice try the following:
RewriteRule ^login\$ https://www.%{HTTP_HOST}/login [R=301,L]

Where you replace login with checkout.php or whatever URL you need to support HTTPS on.
I'd argue this is a bad idea though. For the reasoning please read this answer.
Comment: The first solution doesn't redirect enough, the 2nd seems to  redirect too much. For example `blog.example.com` becomes `www.blog.example.com`
Comment: ive been following everything on here but nothing is working. Im using a laravel setup. Does anyone have any idea why this isnt working for me? www.domain.com and domain.com both load properly but domain.com doesnt redirect to www.domain.com. Could this be a problem with my DNS?
Comment: This solution doesn't work when some pages (like login or sign up) use https protocol.
Comment: I've updated the post slightly to include some info. It's hard to both generically and correctly choose the protocol to use.
Comment: Could you please also add how to avoid the redirect while developing on localhost?
Comment: Could be? what do you have in your DNS? I typically make www a cname that points to the A record of domain.com -- also I notice typos are pretty common with these bugs.
Comment: Thank you .. First solution is simple and efficient
Comment: How can we set the same configuration for Spring boot applications? As we don't have any .htaccess file in it?
Comment: Why not use the [QSA flag](https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsa)?
Answer: Here's the correct solution which supports https and http:
# Redirect to www
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

UPD.: for domains like .co.uk, replace
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$

with
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+\.[^.]+$

Comment: If I am not mistaken, this wouldn't work for more than one dot. Examples: `yoursite.co.uk`
Comment: This is perfect, it also doesn't redirect subdomains to `www` like the other generic solutions do.
Comment: This is a best solution, works much better than the accepted answer, and takes care of HTTPS properly
Comment: Works perfectly! And in such few lines!
Comment: Doesn't work for me.

When I type domain.de it takes me to `https://domain.de`. But I want `https://www.domain.de`
Comment: @TrashyMcTrash, this is by design, I don't think it makes sense to prepend a 3rd level domain with "www". Usually it's used only for 2nd level ones.
Comment: @AlexeyKosov There are TLDs, where you can't set up a 2nd level domain, for example .au, .uk, .jp. I know it is easy to change the snippet accordingly, just noting this for people who will use it for one of those TLDs.
Comment: @AlexeyKosov This doesn't make sense to you? `www.domain.co.uk`
Comment: @reformed It does. I meant subdomains like static.domain.com. Those domains (.au, .uk, .jp) are exception.
Comment: I like this because it helps redirect `.co.ke`
Answer: RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

For Https
RewriteCond %{HTTPS}s ^on(s)|

RewriteRule ^(.*)$ http%1://www.%{HTTP_HOST}/$1 [R=301,L]

Comment: This solution is preferred to @ranman's as it will work for all domains thus minimizing human error either when you're implementing code for a new project or when you implement extra-domains to an existing project.
Comment: This is working for all domain its simple and effective! Thank you
Comment: I prefer this solution, but why `^(.*)$` instead of `(.*)`?
Comment: this solution is better but i have edited mine to contain yours as well.
Comment: you may follow RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}/$1 [R=301,L]
Comment: this is third ttime you save me ;) thank you
Answer: The following example works on both ssl and non-ssl and is much faster as you  use just one rule to manage http and https
RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

[Tested]
This will redirect
http

http://example.com

to

http://www.example.com

https

https://example.com

to

https://www.example.com
Comment: Just out of curiosity, why aren't you using R=301 here? It will use 302 (moved temp.) by default if no code specified.
Comment: Very close to what I came up with. Supports more than one dot in the HTTP host too, for example "mysite.co.uk".
Comment: Works perfectly. This should be the accepted answer.
Comment: it will also redirect blog.domain.com to www.blog.domain.com, which is not always desired
Answer: Try this, I used it in many websites, it works perfectly
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^bewebdeveloper.com$
RewriteRule ^(.*) http://www.bewebdeveloper.com/$1  [QSA,L,R=301]

Answer: I have tested all the above solutions but not working for me, i have tried to remove the http:// and won't redirect also removed the www it redirect well, so i get confused, specially i am running all my sites under https://
So i have combined some codes together and came up with perfect solution for both http:// and https:// and www and non-www.
# HTTPS forced
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

Hope this can help someone :)
Answer: Add the following code in .htaccess file.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file
Answer: This configuration worked for me in bitnami wordpress with SSL configured :
Added the below under  "RewriteEngine On" in file /opt/bitnami/apps/wordpress/conf/httpd-app.conf
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Answer: RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [L,R=301]

This will redirect your domain which is not started with WWW
It is not redirect your all sub domain.
It is useful.
Answer: I believe the top answer successfully redirects non-www to www (ex: mysite.com -> www.mysite.com), but doesn't take into account wildcard subdomains, which results in:
random.mysite.com -> www.random.mysite.com

Here's a solution with/without HTTPS
HTTP
RewriteEngine On

RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://www.mysite.com/$1 [L,R=301]

HTTP/HTTPS
RewriteEngine On

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=protocol:https]

RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=protocol:http]

RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ %{ENV:protocol}://www.mysite.com/$1 [L,R=301]

*note: I haven't tested https because I don't currently have a cert to test, but if someone can verify or optimize what I have that would be awesome.
Comment: What does the first $ do here: '^(.*)$'
Answer: If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.
<VirtualHost 220.127.116.11>
        ServerName example.com
        Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 22.214.171.124>
   ServerAdmin firstname.lastname@example.com
   ServerName www.example.com
   DocumentRoot /var/www/example
   .
   .
   . etc

So, the separate VirtualHost for "example.com" captures those requests and then permanently redirects them to your main VirtualHost. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.
Note, the trailing slash in Redirect permanent / http://www.example.com/.
Without it, a redirect from example.com/asdf would redirect to http://www.example.comasdf instead of http://www.example.com/asdf.
Answer: Two warnings
Avoid 301 and prefer modern 303 or 307 response status codes.
Avoid 301
Think carefully if you really need the permanent redirect indicated as [R=301] because if you decide to change it later, then the previous visitors of the page will continue to see the page of the original redirection.
The permanent redirection information is frequently stored in the browser's cache and, in general, it is difficult to eliminate (reload the page do not solve the problem). Your website visitors will be stuck in the previous redirect "forever".
Avoid 302 too
The new version of the HTTP protocol (v1.1) added two new response status codes that can be used instead of 302.

303 URL redirection but demanding to change the type of request to
GET.
307 URL Redirection but demanding to keep the type of request as initially sent.

You can still use the code 302 (non-permanent redirection) although it is considered ambiguous. In any case, most browsers implement 302 in the same way the new 303 code instructs.
Comment: regarding your warning about 301, this will apply even if we are talking about the same domain name? not so sure how this will apply in this case ... redirecting all URL's from `http://example.com/testing` to `http://www.example.com/testing`. Could be a bad approach in long term? Thanks,
Answer: Write in .htaccess :)
## Redirect from non-www to www (remove the two lines below to enable)
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Comment: Same as other answers

Redirect non-www to www in .htaccess


How to play A5-B5-C6 sequence on descant recorder?

Question: I'm a beginner at recorder and I'm having difficulty playing the sequence of notes A5-B5-C6, and this sequence comes up a lot!
The basic fingerings are given as follows:
A5: T12-----
B5: T1------
C5: T-2-----

Using these fingerings, is is very easy to jump from A5 to B5 because it involves only uncovering hole 2.  However, I have a hard time jumping from B5 to C6 because it involves simultaneous covering hole 2 while uncovering hole 1. B5 and C6 seem almost impossible to trill without there being some intermediate screeching sound for a tiny fraction of a second.
I've tried using the alternate fingering for B5:

B5: T-23----

This makes it easy to jump from B5 to C6, but difficult to jump from A5 to B5, so it's basically out of the frying pan into the fire.
How can I teach myself to play this sequence of notes on descant recorder: A5-B5-C6?
Comment: With practice comes ability.  No real way around that.
Comment: Can you give any pointers or suggestions as to the appropriate practice or technique?  I didn't ask to do this without practice.
Comment: The best practice for this is to simply do it over and over.  Keep your fingers as close to the instrument as you can without shading the holes, and keep them relaxed.  You will hear when it's smooth.  Start slow.
Answer: There's no easy solution here. One B fingering makes A-B easy, and the other makes B-C easy. You just have to pick which transition is more critical.
This 1/2 "flip" (going from 1-- to -2-) is very common in most woodwind instruments. Modern instruments have extra keys to partially alleviate the problem, but it's still something you want to practice so you can do it cleanly.
Comment: That's basically it. There's really no other trick to it.
Comment: I am a complete beginner with woodwind instruments.  Can you tell me anything more about how I might master this skill?  All I can see from my point of view is that I must cover one hole and uncover another at exactly the same time.
Comment: That really is it. If it was easy everybody would be a recorder virtuoso. Several changes of note involve multiple simultaneous finger movements, and the more you practice, the easier it will become.
Comment: Another thing that should be pointed out- the trill fingering T 2 3 for B, although it works very well on most soprano recorders, doesn't always work so well on larger instruments.  Thus, it should really be avoided except for trills or similar ornaments.  It's better to just get good at moving smoothly from T 1 to T 2.  Same goes, of course, for many other combinations of tones- E to F, for instance.
Answer: These fingering charts show an alternative fingering T-23 for the B, which give a "one-fingered" trill with T-2 for C.
http://www.dolmetsch.com/efingeringchart.pdf
http://www.dolmetsch.com/etrillchart.pdf
Comment: It looks like my question isn't being displayed properly.  I did mention the T-23 fingering for the B, but that fingering is difficult to trill with the A below it.
Comment: I'm seeing the second "gray box" in the OP with no text in it. But if your trill starts on the upper note (like most Baroque trills) why is A - C - alternative B a big problem? Your OP didn't ask about trilling A-B (only B-C), but that shouldn't be a problem with the standard fingering for B.
Comment: The alternate fingering T-23 for B is useful for trills and occasionally for certain other ornaments.  But there's no getting around the necessity for learning how to transition from T-1 to T-2 smoothly.


301 Redirect for a dynamic URL

Question: I've been working on a 301 redirect for a dynamic URL for the past couple days and have really been struggling.
I am looking to redirect example.com/?feed=podcast to example.com/feed/podcast
Here is my current .htaccess file:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^feed$ "http\:\/\/example\.com\/feed\/podcast" [R=301,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I am trying to add a redirect for a dynamic URL. I have been able to get this to work:
RewriteCond %{QUERY_STRING} ^pizza$
RewriteRule ^$ http://www.example.com/feed/podcast? [R=301,L]

But I can't get this to work:
RewriteCond %{QUERY_STRING} ^feed=podcast$
RewriteRule ^$ http://www.example.com/feed/podcast? [R=301,L]

It ends up redirecting back to example.com
Any help would be much appreciated!
Answer: This is working for me:
Options All -Indexes

ErrorDocument 403 /Forbidden

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

RewriteCond %{QUERY_STRING} ^feed=podcast$
RewriteRule ^$ http://www.example.com/feed/podcast? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

At first I thought that you had to escape the equal sign ("=") with a backslash (which did work, but as displayed above also does the redirect.
C:\Apache24\htdocs>curl -s --verbose http://localhost/?feed=podcast -o null
* Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 80 (#0)
> GET /?feed=podcast HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Date: Thu, 27 Aug 2015 21:43:43 GMT
* Server Apache/2.4.10 (Win64) PHP/5.6.4 is not blacklisted
< Server: Apache/2.4.10 (Win64) PHP/5.6.4
< Location: http://www.example.com/feed/podcast
< Content-Length: 243
< Content-Type: text/html; charset=iso-8859-1
<
{ [data not shown]
* Connection #0 to host localhost left intact

301 Redirect for a dynamic URL