Finding the explicit formula for the succession $x_0=2, x_{n+1} = 5x_n$ and proving it with induction

Question: I'm trying to learn about recursion, first with this exercise:

Find the explicit formula for the succession $$x_0=2, x_{n+1} = 5x_n$$

So, from what I've seen, I should test a bit. I see that the formula is pretty much the previous value by $5$:
$$x_0=2$$
$$x_1=5\cdot2$$
$$x_2=5\cdot(5\cdot 2)$$
$$x_3=5\cdot(5\cdot(5\cdot2))$$
It seems to me that a formula would be
$$x_n=5^n\cdot2$$
Now I have to prove it by induction, according to the exercise.
Test for $n=0$:
$$x_0 = 5^0\cdot2$$
$$2 = 2$$
I want to prove that it holds for $n + 1$, that is:
$$x_{n+1} = 5^{n+1}\cdot 2$$
Let's see:
$$x_{n+1}$$
This is where I'm getting a bit stuck, I had thought that the previous is equivalent to this:
$$x_n+5^{n+1}\cdot2$$
But that doesn't make any sense, because that would definitely be not equal to what I want to prove.
How should I had proceeded from this point?
Answer: You want to prove that $x_{n+1} = 5^{n+1} \cdot 2$. The induction hypothesis that you can use for this is $x_n = 5^n \cdot 2$. Now apply the recurrence relation and find $x_{n+1} = 5 x_n = 5 (5^n \cdot 2) = 5^{n+1} \cdot 2$.


Converting List to Map> in Java 8 when we have duplicate elements and custom filter criteria

Question: I have an instances of Student class.
class Student {
    String name;
    String addr;
    String type;

    public Student(String name, String addr, String type) {
        super();
        this.name = name;
        this.addr = addr;
        this.type = type;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", addr=" + addr + "]";
    }

    public String getName() {
        return name;
    }

    public String getAddr() {
        return addr;
    }
}

And I have a code to create a map , where it store the student name as the key and some processed addr values (a List since we have multiple addr values for the same student) as the value.
public class FilterId {

public static String getNum(String s) {
    // should do some complex stuff, just for testing
    return s.split(" ")[1];
}

public static void main(String[] args) {
    List<Student> list = new ArrayList<Student>();
    list.add(new Student("a", "test 1", "type 1"));
    list.add(new Student("a", "test 1", "type 2"));
    list.add(new Student("b", "test 1", "type 1"));
    list.add(new Student("c", "test 1", "type 1"));
    list.add(new Student("b", "test 1", "type 1"));
    list.add(new Student("a", "test 1", "type 1"));
    list.add(new Student("c", "test 3", "type 2"));
    list.add(new Student("a", "test 2", "type 1"));
    list.add(new Student("b", "test 2", "type 1"));
    list.add(new Student("a", "test 3", "type 1"));
    Map<String, List<String>> map = new HashMap<>();

    // This will create a Map with Student names (distinct) and the test numbers (distinct List of tests numbers) associated with them.
    for (Student student : list) {
        if (map.containsKey(student.getName())) {
            List<String> numList = map.get(student.getName());
            String value = getNum(student.getAddr());

            if (!numList.contains(value)) {
                numList.add(value);
                map.put(student.getName(), numList);
            }
        } else {
            map.put(student.getName(), new ArrayList<>(Arrays.asList(getNum(student.getAddr()))));
        }
    }

    System.out.println(map.toString());

}
}

Output would be :
{a=[1, 2, 3], b=[1, 2], c=[1, 3]}
How can I just do the same in java8 in a much more elegant way, may be using the streams ?
Found this Collectors.toMap in java 8 but could't find a way to actually do the same with this.
I was trying to map the elements as CSVs but that it didn't work since I couldn't figure out  a way to remove the duplicates easily and the output is not what I need at the moment.
Map<String, String> map2 = new HashMap<>();
map2 = list.stream().collect(Collectors.toMap(Student::getName, Student::getAddr, (a, b) -> a + " , " + b));
System.out.println(map2.toString());
// {a=test 1 , test 1 , test 1 , test 2 , test 3, b=test 1 , test 1 , test 2, c=test 1 , test 3}

Answer: With streams, you could use Collectors.groupingBy along with Collectors.mapping:
Map<String, Set<String>> map = list.stream()
    .collect(Collectors.groupingBy(
        Student::getName,
        Collectors.mapping(student -> getNum(student.getAddr()),
            Collectors.toSet())));

I've chosen to create a map of sets instead of a map of lists, as it seems that you don't want duplicates in the lists.

If you do need lists instead of sets, it's more efficient to first collect to sets and then convert the sets to lists:
Map<String, List<String>> map = list.stream()
    .collect(Collectors.groupingBy(
        Student::getName,
        Collectors.mapping(s -> getNum(s.getAddr()),
            Collectors.collectingAndThen(Collectors.toSet(), ArrayList::new))));

This uses Collectors.collectingAndThen, which first collects and then transforms the result.

Another more compact way, without streams:
Map<String, Set<String>> map = new HashMap<>(); // or LinkedHashMap
list.forEach(s ->
    map.computeIfAbsent(s.getName(), k -> new HashSet<>()) // or LinkedHashSet
        .add(getNum(s.getAddr())));

This variant uses Iterable.forEach to iterate the list and Map.computeIfAbsent to group transformed addresses by student name.
Comment: Like the use of `Collectors.collectingAndThen`.
Comment: Great. One small thins, append something to the key,
what if I need my output as `{student-a=[1, 2, 3],student-b=[1, 2], student-c=[1, 3]}`
Comment: @prime just change `Student::getName` by `s -> "student-" + s.getName()`
Comment: @FedericoPeraltaSchaffner great. One  thing, what if we need to exclude some elements from the `getNum`, like output will be `{a=[1, 2], b=[1, 2], c=[1, 3]}`

Now the `a`'s list does not has the `3` because it failed some condition in `getNum`, how can we handle a condition like that.

ex : If the type is `type 3` then we don't need to add that to the list.
Comment: @prime if you are on Java 9, change getNum so that it returns a stream, if the condition is true, return a one element stream, if it's false return an empty stream. Then, when collecting, use Collectors.flatMapping instead of Collectors.mapping. there are other ways, maybe you need to write another question for that case, linking to this question for context
Comment: @FedericoPeraltaSchaffner well it's on java 8 though
Comment: @prime there's a backport from Holger, search it here in SO, it's a small static utility method. Something like flatmapping collector in Java 8, but honestly I would ask a new question asking specifically about the conditional adding of elements to the downstream set. So this question remains clear for future readers as to mapping and grouping, while the new one is about filtering in this context.
Comment: @FedericoPeraltaSchaffner sure will ask a new one.
Comment: @prime just for my understanding... Please confirm... You want to exclude some results returned by `getNum` based on a condition, but what would this condition be and what would it depend on?
Comment: @FedericoPeraltaSchaffner Sure, consider this ex : If the type is type 3 then we don't need to add that to the set (in the map).
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164700/discussion-between-federico-peralta-schaffner-and-prime).
Answer: First of all, the current solution is not really elegant, regardless of any streaming solution.
The pattern of
if (map.containsKey(k)) {
    Value value = map.get(k);
    ...
} else {
    map.put(k, new Value());
}

can often be simplified with Map#computeIfAbsent. In your example, this would be
// This will create a Map with Student names (distinct) and the test
// numbers (distinct List of tests numbers) associated with them.
for (Student student : list)
{
    List<String> numList = map.computeIfAbsent(
        student.getName(), s -> new ArrayList<String>());
    String value = getNum(student.getAddr());
    if (!numList.contains(value))
    {
        numList.add(value);
    }
}

(This is a Java 8 function, but it is still unrelated to streams).

Next, the data structure that you want to build there does not seem to be the most appropriate one. In general, the pattern of
if (!list.contains(someValue)) {
    list.add(someValue);
}

is a strong sign that you should not use a List, but a Set. The set will contain each element only once, and you will avoid the contains calls on the list, which are O(n) and thus may be expensive for larger lists.
Even if you really need a List in the end, it is often more elegant and efficient to first collect the elements in a Set, and afterwards convert this Set into a List in one dedicated step.
So the first part could be solved like this:
// This will create a Map with Student names (distinct) and the test
// numbers (distinct List of tests numbers) associated with them.
Map<String, Collection<String>> map = new HashMap<>();
for (Student student : list)
{
    String value = getNum(student.getAddr());
    map.computeIfAbsent(student.getName(), s -> new LinkedHashSet<String>())
        .add(value);
}

It will create a Map<String, Collection<String>>. This can then be converted into a Map<String, List<String>> :
// Convert the 'Collection' values of the map into 'List' values
Map<String, List<String>> result =
    map.entrySet().stream().collect(Collectors.toMap(
        Entry::getKey, e -> new ArrayList<String>(e.getValue())));

Or, more generically, using a utility method for this:
private static <K, V> Map<K, List<V>> convertValuesToLists(
    Map<K, ? extends Collection<? extends V>> map)
{
    return map.entrySet().stream().collect(Collectors.toMap(
        Entry::getKey, e -> new ArrayList<V>(e.getValue())));
}

I do not recommend this, but you also could convert the for loop into a stream operation:
Map<String, Set<String>> map =
    list.stream().collect(Collectors.groupingBy(
        Student::getName, LinkedHashMap::new,
        Collectors.mapping(
            s -> getNum(s.getAddr()), Collectors.toSet())));

Alternatively, you could do the "grouping by" and the conversion from Set to List in one step:
Map<String, List<String>> result =
    list.stream().collect(Collectors.groupingBy(
        Student::getName, LinkedHashMap::new,
        Collectors.mapping(
            s -> getNum(s.getAddr()),
            Collectors.collectingAndThen(
                Collectors.toSet(), ArrayList<String>::new))));

Or you could introduce an own collector, that does the List#contains call, but all this tends to be far less readable than the other solutions...
Comment: @FedericoPeraltaSchaffner Yes, `replaceAll` (which I admittedly did not have on the screen until now) may be an alternative, depending on which type information you want to have for the map values (`Collection` vs `? extends Collection` - and maybe it *must* be a `List`...?). But this is only one of many degrees of freedom in the answer to this question. I think that when these degrees of freedom show up as different options of deeply nested `Collector` implementations, one should consider breaking it down into a `for` loop with simple, *named* operations, for the sake of readability...
Comment: Upvoted! This is a very complete answer. I think you could have used `replaceAll` on each map's values instead of streaming on the entry sets and then collecting to new maps.
Comment: Agreed, downstream collectors tend to become unreadable after the 2nd level, that's why I'd stay with the `Map.computeIfAbsent` solution. And using `Collectors.collectingAndThen` has always seemed too verbose to add a simple finishing transformation...
Answer: I think you are looking for something like below
   Map<String,Set<String>> map =  list.stream().
           collect(Collectors.groupingBy(
                    Student::getName,
                    Collectors.mapping(e->getNum(e.getAddr()), Collectors.toSet())
                ));

   System.out.println("Map : "+map);

Answer: Here is a version that collects everything in sets, and converts the final result to array lists:
/*
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
import java.util.function.*;
*/

Map<String, List<String>> map2 = list.stream().collect(groupingBy(
  Student::getName, // we will group the students by name
  Collector.of(
    HashSet::new, // for each student name, we will collect result in a hash set
    (arr, student) -> arr.add(getNum(student.getAddr())), // which we fill with processed addresses
    (left, right) -> { left.addAll(right); return left; }, // we merge subresults like this
    (Function<HashSet<String>, List<String>>) ArrayList::new // finish by converting to List
  )
));
System.out.println(map2);

// Output:
// {a=[1, 2, 3], b=[1, 2], c=[1, 3]}

EDIT: made the finisher shorter using Marco13's hint.
Comment: @Marco13 there's always something I can learn from Marco13 :] Thank you for the hint! I updated the answer.
A separate variable declaration for the collector does not seem to be necessary. A `(Function, List>)` cast seems to be enough to select the right constructor of `ArrayList`. So, it's not a cast, it's rather some kind of type ascription, to be more precise.
Comment: OK, then I'll delete the distracting comment. But I also was a bit irritated why pulling it out into a variable (or "casting" as in your case) seemed to be necessary. I wonder whether this is expected, why the type inference seemed to hit a limit there, or whether there is a "nicer" solution, and consider asking this as a separate question (if I can't figure it out on my own, but I'll first have to take a closer look at that)
Comment: I had another look at this. The reason of why it cannot infer the type of the finisher is likely related to the fact that the return type cannot be derived from the `Collector.of` call alone: None of its arguments defines `R`, the return type, and it seems like it is not able to hand the target type information from the `map2` declaration through the `collect` and `groupingBy` calls up to the `Collector.of` call. Related: https://stackoverflow.com/a/24798163/3182664  (BTW: The current code issues an "unchecked" warning, which can be avoided with  `ArrayList::new`)
Comment: @Marco13 openjdk version "1.8.0_144" issues nothing, compiles just fine even with -Werror ?..
Comment: You're right. I tried it in Eclipse Neon (pretty old...) and it issued a warning, but with the latest (Eclipse Oxygen) everything is fine. Seems to be a ECJ bug that has been fixed in the meantime.


Is it true that a quasiconvex, increasing and continous function, is convex?

Question: Let $f:\mathbb R^n \to \mathbb R$ be a continuous and increasing function.
Let $f$ be quasiconvex.
Let $f(0)=0$.
Can we say that $f(x)$ is convex ?
If yes, how do we prove it ?
Thank you very much for your help !
Comment: What does $x\ge y$ mean when $x,y\in\mathbb R^n$?
Comment: What do "quasiconvex" and "increasing" mean? (This is probably standard notation, but not for me at least.)
Comment: Increasing just means that f(x)>=f(y) implies x>=y; whereas quasiconvex implies a harder def. Unfortunately I haven't fully understood it. It means that if f(x)>=f(y), then f(ax + (1-a)y) >= f(y). Sorry for the typos in Latek, I'm new to this language
Comment: @GiuseppeNegro see [here](http://lmgtfy.com/?q=quasiconvex), for example (the [wiki page](http://en.wikipedia.org/wiki/Quasiconvex_function) is fairly thorough)
Answer: Every continuous increasing function on the real line is quasiconvex, but not every such function is convex, so there are tons of counterexamples, e.g., $f(x) = x^3$.
Comment: What happens if I impose n>1, can you still find counterexamples ? Thanks for your reply
Comment: Then you first have to define what increasing means for functions in $\mathbb{R}^n$, i.e., with respect to what kind of (partial) order on $\mathbb{R}^n$. But with just about any definition, you can get basically the same counterexample by defining $f(x_1, \ldots, x_n) = x_1^3$.
Comment: Yes, right answer.
Comment: Dear Lukas Geyer, I am waiting to your comments in my question. Thank you for your kind help. http://math.stackexchange.com/questions/1220706/constructing-a-quasiconvex-function


preg_replace... remove string from string

Question: What I want to do is remove all instances of c_*/ where * could be any digit or character of any length.
$cano = 'www.example.com/example/example2/c_3/example4/';
$cano = preg_replace('c_*/', '', $cano);

I've always been bad with these cause I hardly use them...
Comment: Did my answer help at all? I can alter it if it's not what you're looking for.
Answer: I think this will do the trick.
$cano = preg_replace('#c_[^/]+/#', '', $cano);

The [^/] matches any character that is not a forward slash, and the + means "one or more" characters.
Comment: thanks... worked great... threw it into an array with some others and working as expected.
Answer: Try this:
$cano = 'www.example.com/example/example2/c_3/example4/';
$cano = preg_replace('#(?:c_.[^/]/)+#', '', $cano);


I am trying to print the elements of linked list after adding it but it doesn't seem to work

Question: I am trying to show the items in my linked list after inserting them with the function Add, and view function to print but it doesn't seem to work.
class Node():
    def __init__(self,value):
        self.value = value
        self.next = None
class Linked_List():
    def  __init__(self):
        self.head = None
        self.tail = None
    def Add(self,value):
        if(self.head == None):
            n = Node(value)
            if(self.head == None):
                self.head = n
            else:
                self.tail.next  = n
            self.tail =  n
def view(head):
        curr = head
        while (curr):
                print(curr.value,"-->")
                curr = curr.next

newlist = Linked_List()
newlist.Add(5)
newlist.Add(6)
newlist.Add(56)
view(newlist.head)

It only shows the first element 5 and doesn't show the rest. I can't seem to understand the reason even if I have done acc. to the algorithm?
Comment: What does "i have done acc. to the algo" mean?
Answer: If head is not Null, Add doesn't do anything, which even the most rudimentary debugger would have made clear.


Why does log likelihood function for a model use SSE/n and not SSE/df?

Question: I'm trying to find out how log-likelihood function works for linear regression. I found the formula here and here. Making some experiments with it (see code below), I was quite surprised that the likelihood uses SSE/n instead of MSE (SSE/df). MSE was used everywhere up to now! I thought MSE is much better estimator of $\sigma^2$ mentioned in the formula in the 1st resource (page 6) - the actual residual variance. But the 2nd resource and my experiment clearly states that $\sigma^2$ is defined as SSE/n (where n is length of the outcome variable vector).
Here is the code to play with:
set.seed(128)
y = c(rnorm(200, 20, 4), rnorm(300, 30, 4), rnorm(400, 40, 4), rnorm(500, 50, 4))
cat1 = as.factor(c(rep(1, 200), rep(2, 300), rep(3, 400), rep(4, 500)))
rand_order = sample(1:length(cat1))
cat2 = cat1[rand_order]
cat2y = c(rep(1, 200), rep(-2, 300), rep(3, 400), rep(-4, 500))
y = y + cat2y[rand_order]
m1 = lm(y ~ 0 + cat1 + cat2)

# logLik using residual degrees of freedom (-3941.94):
-length(m1$model$y)/2*log(2*pi) - length(m1$model$y)/2*log(sum((m1$residual)^2)/m1$df.residual) - 1/2*m1$df.residual

# logLik using N (-3941.931)
-length(m1$model$y)/2*log(2*pi) - length(m1$model$y)/2*log(sum((m1$residual)^2)/length(m1$model$y)) - 1/2*length(m1$model$y)

# real logLik (-3941.931)
logLik(m1)

Answer: The same situation happens in the simplest Normal means model: $Y=\mu + \epsilon$, with $\epsilon$ ~ N(0,$\sigma^2$).
The MLE of $\sigma^2$ is the sum of squares about the mean divided by n: $$S^2=\sum \frac{(Y_i-\bar{Y})^2}{n}$$.
However, this quantity is a biased estimator: $E(S^2) \neq \sigma^2$. Dividing the sum of squares by $n-1$ instead of $n$ gives an unbiased estimator of the variance.
Furthermore, $\sum \frac{(Y_i-\bar{Y})^2}{\sigma^2(n-1)}$ has a $\chi^2$ distribution with $n-1$ degrees of freedom. And ratios of independent mean squares will have the F distribution.
Statistical inference offers several criteria for "bestness" in estimators: these include unbiasedness, minimum variance, minimizer of a loss function and (increasingly) predictive accuracy. Being the maximum likelihood estimator is also considered desirable, because the likelihood (supposedly) contains all relevant information about the model (this is debatable and has been debated). The MLE usually manages to be asymptotically unbiased and efficient. What this means for a finite sample depends on the model.
Linear regression with Normal errors works much like the simple normal means model that I gave here: the unbiased estimator for the variance is not the MLE.
The unbiased estimator is preferred because of its nice distributional properties. Geometrically, you are partitioning $R^n$ into two linear subspaces: one to contain the model and one to contain the residuals. The dimension of the residual space is the degrees of freedom.
Comment: I guess it is counter-intuitive! At least, that's the big shocker for students of statistical inference: there are a number of reasonable criteria for choosing estimators and no one estimator is superior by all criteria. The important thing is to understand what your estimator is giving you. Maximum likelihood gives you an estimator that respects the probability model of the data and that has good asymptotic properties.
Comment: Tomas, did you really try to *derive* the MLE from the first principles -- by writing down the likelihood and maximizing it? When you say "uses", it sounds like there is a choice; there is not, as the MLE is uniquely defined (thank God) in this situation. The MLE **boils down** to this estimator -- I can't say it **uses** it.
Comment: Better in what way? See my post.
Comment: And another thing: the distribution of the MSE is skewed - being $\chi^2$. This means that its mode, median and mean are all different. To say that the MSE is unbiased is to say that the mean of that distribution is $\sigma^2$. But in a skewed situation, the mean is not the only (or always the best) measure of central tendency.
Comment: Thanks for your answer, but what I stil don't understand: why the MLE doesn't use the unbiased estimator. Wouldn't that be better for finite sample sizes?
Comment: @StasK, no I didn't try, I'm not that clever :) However it sounds contra-intuitive when the unbiased estimator is better for finite samples...
Answer: To expand on a very good answer that Placidia gave:

Unbiasedness is not necessarily the best possible property for an estimator. Shrinkage estimators applied in situations of multiple collinearity or with many possible regressors (lasso) are intentionally biased, and this is done to improve their other properties (easier interpretation of the results). Any Bayesian posterior mean or posterior mode estimator with an informative prior is biased; it does not mean that we want to dismiss this whole area of statistics.
As far as other criteria of performance of a statistical estimator go, the mean squared error (MSE) is a popular criterion: by how far the estimator is off, on average, disregarding whether it is biased or not. The best estimator of the population $\sigma^2$ is then the one that has not $n-1$, not $n$, but $n+1$ in the denominator. So if your inferential target is the population variance, you might want to use the estimator that divides the sum of squared errors by $n+1$.
The observation that the MLE $S^2$ does not appear to make much sense in regression context has been made earlier, of course, and corrections have been proposed to force it to use the "right" degrees of freedom. This is the idea of restricted maximum likelihood (REML), where the estimators are defined conditioning on the residual subspace that has the "right" dimension.
Yet another useful property of the ML is transformation invariance. If $S^2$ is the MLE of $\sigma^2$, then automatically $S$ is the MLE of $\sigma$, and $\ln S$ is the estimator of $\ln(\sigma)$. This comes handy in software code: maximizing with respect to $S$ or $S^2$ is being complicated by the quantity being non-negative, while maximizing with respect to $\ln S$ does not involve any constraints. (You'd observe that by Jensen's inequality, unbiasedness of an estimator $$s^2 = \frac1{n-1} \sum (Y_i - \bar Y)^2$$ is easily destroyed by any transformation: $s$ is not an unbiased estimate of $\sigma$. In fact, the unbiased estimator of $\sigma$ is pretty difficult to construct, and I won't be too much ashamed to admit that I don't know one off the top of my head.)
Comment: Thanks for answer! "*Any Bayesian posterior mean or posterior mode estimator with an informative prior is biased*" - but in 99% times you use uninformative prior.. and then it is unbiased I guess?
Comment: Ad 3) - so in REML it is as I expected, i.e. it uses the `SSE/df` instead of `SSE/n`?


Splitness of a short exact sequence on a curve

Question: Let $C$ be a curve with genus $g > 1$. Consider the product $C \times C$, with natural projections $p_1$ and $p_2$ (from the first and second factor, respectively) to $C$.
Consider the following short exact sequence of sheaves on $C \times C$:
$$0 \rightarrow p_2^* K_C^{\otimes 2} \rightarrow p_2^* K_C^{\otimes 2} \otimes \mathcal{O}_{C \times C}(\Delta) \rightarrow K_C \rightarrow 0$$
where $K_C$ is the canonical bundle of $C$, $\Delta$ is the diagonal in $C \times C$, and the map $p_2^* K_C^{\otimes 2} \otimes \mathcal{O}_{C \times C}(\Delta) \rightarrow K_C$ is the restriction map to $\Delta$. The last entry $K_C$ is a line bundle on $\Delta$, which is a sheaf on $C \times C$ supported on $\Delta$.
Now consider the projection ${p_1}_*$ of this sequence. Is the resulting sequence on $C$ split?
Comment: I think I understand, but maybe it would be good to say what the maps are and how $K_C$ can live on $C\times C$.
Comment: @Hoot Good point. Clarifications added.
Answer: The answer is still negative, though I feel the previous answer is incorrect. Let $L=p_1^*K_C, M=p_2^*K_C$ and  then saying $0\to p_{1*}M^2\to p_{1*}M^2(\Delta)\to K_C\to 0$ (the last is surjective, since the corresponding $R^1$ is zero) splits is same as sayining after twisting by $K_C^{-1}$, the section $1$ can be lifted. This implies in particular $H^0(L^{-1}\otimes M^2(\Delta))\neq 0$. But $p_{2*}(L^{-1}\otimes \mathcal{O}(\Delta))=0$ since $g>1$ and thus the $H^0=0$ which proves that the sequence that you need is not split.
Comment: One has $p_{1*}M^2(\Delta)\otimes K_C^{-1}\to \mathcal{O}_C\to 0$, by twisting the above sequence by $K_C^{-1}$. If the first sequence splits, so does the second and then one has an inclusion $\mathcal{O}_C\subset p_{1*}M^2(\Delta)\otimes K_C^{-1}$, which means the latter has a non-zero section. By projection formula, this is same as saying $H^0(L^{-1}\otimes M^2(\Delta))\neq 0$. Looking at the other projection, we see that $H^0(K_C^2\otimes p_{2*}(L^{-1}\otimes\mathcal{O}(\Delta))\neq 0$. I do not understand your confusion about the last part.
Comment: When you wrote $p_{1*}p_2^*M^2$, did you mean $p_{1*}M^2$?
Comment: Yes, that is what I meant. Will edit it.
Comment: Could you provide some more details? For example, when you said "section 1 can be lifted", why does that imply that $H^0(C \times C, L^{-1} \otimes M^2(\Delta)) \neq 0$? Also, what did you mean by ${p_2}_*(L^{-1} \otimes \mathcal{O}(\Delta)) = 0$?
Comment: Forgive me for being slow on this. So by projection formula we obtain $H^0(C, {p_1}_*M^2(\Delta) \otimes K_C^{-1}) = H^0(C, {p_1}_*(M^2(\Delta) \otimes p_1^*K_C^{-1})) \neq 0$. But how is this related to the conclusion? We are not considering the splitness of ${p_2}_*$ of the original sequence, so how do we draw a contradiction?
Comment: You are confusing where these are. The second term above is $H^0(C\times C, M^2(\Delta)\otimes L^{-1})$. This again by projection formula (using $p_{2*}$) is $H^0(C, K_C^2\otimes p_{2*}(\mathcal{O}(\Delta)\otimes L^{-1}))$, which is zero since  $p_{2*}(\mathcal{O}(\Delta)\otimes L^{-1})$ itself is zero.
Comment: I see. What was missing in my mind was the isomorphism $H^0(C, {p_1}_* (M^2(\Delta) \otimes L^{-1})) = H^0(C \times C, M^2(\Delta) \otimes L^{-1})$.
Answer: I came up with an alternative answer. Let $\mathcal{M}_{g,n}$ be the moduli space of Riemann surfaces of genus $g$ with $n$ marked points. Then our sequence
$$0 \rightarrow {p_1}_* p_2^* K_C^{\otimes 2} \rightarrow {p_1}_* (p_2^* K_C^{\otimes 2} \otimes \mathcal{O}_{C \times C}(\Delta)) \rightarrow K_C \rightarrow 0$$
is in fact the same as
$$0 \rightarrow H^0(C,K_C^2) \otimes \mathcal{O}_C \rightarrow T^*\mathcal{M}_{g,1}|_{C} \rightarrow K_C \rightarrow 0$$
which is dual to
$$0 \rightarrow T_C \rightarrow T\mathcal{M}_{g,1}|_{C} \rightarrow H^1(C,T_C) \otimes \mathcal{O}_C \rightarrow 0$$
This last sequence is maximally non-split.


What is the numerically greatest or magnitude wise greatest term in the expansion?

Question: I am just a beginner to Binomial Theorem and I want to find out the numerically or magnitude wise greatest term in the expansion of $(3-5x)^{11} $ when $ x=\frac{1}{5} $
I know some methods, but they are quite confusing. And I want a simple method. So if anyone has any idea they are welcomed.
Answer: Note that the general term of the expression $(3-5x)^{11} $ is $$T_r = \binom {11}{r}3^r (-5x)^{11-r} $$ When $T_r $ is the largest term then: $$\frac {T_{r+1}}{T_r} \leq 1$$ $$\implies \frac {\binom {11}{r+1}}{\binom {11}{r}} \times 3 \times (-5x)^{-1} \bigg \lvert_{ x = \frac15} \leq 1$$
Ignore the negative sign as we want the greatest numerical value.
Surely you can take it from here.
Answer: When $x = \frac15$, we just have $(3-1)^{11}$. Then the question is basically "what is the largest $n$ such that $3\binom{11}{n-1}\leq\binom{11}{n}$", since the change from one term to the next is that the "denominator" of the binomial coefficient increases by $1$, and the exponent of $3$ decreases by $1$, and we want to know at what point the change in the binomial coefficient doesn't outweigh the change in the exponent of $3$ (ignoring sign).
(Alternatively, one may derive this inequality from "one term is larger than the previous if their ratio is larger than $1$" as the other answer does. Arguably, that's easier to follow than the above paragraph.)
We have that
$$
3\binom{11}{n-1}\leq\binom{11}{n}\\
3\leq\frac{\binom{11}{n}}{\binom{11}{n-1}}\\
3\leq\cfrac{\frac{11!}{(n)!(11-n)!}}{\frac{11!}{(n-1)!(11-n+1)!}}\\
3 \leq \frac{11-n+1}{n}\\
3n\leq12-n\\
4n\leq12\\
n\leq3
$$
So we actually get that $n = 3$ is the largest $n$ for which the previous term isn't larger (again, ignoring sign), and that term is
$$
3^{8}(-1)^3\binom{11}3 = -1\,082\,565
$$
Since the inequality gave $n\leq$ an integer, the previous term is actually equal in absolute value, and has positive sign, so numerically, that's the largest. In general, if one term is negative, but in absolute value the strictly largest (i.e. the inequality you get from the above argument is $n\leq$ some non-integer), then you will have to compare the term before and the term after to see which one is numerically larger, but it will necessarily be one of those two.


Javascript - How can I change scope and access method without 'this'

Question: I want to port domjs for browser.
var mytemplate = function () {
  header(
    h1('Heading'),
    h2('Subheading'));

  nav(
    ul({ 'class': 'breadcrumbs' },
      li(a({ href: '/' }, 'Home')),
      li(a({ href: '/section/'}, 'Section')),
      li(a('Subject'))));

  article(
    p('Lorem ipsum...'));

  footer('Footer stuff');
};

But I don't know how to attach some methods like 'header' 'h1' 'h2' to 'mytemplate'.
How can I use header() without 'this' keyword.

Failed Case:
   template.apply($funcs),
   template.bind($funcs)(),
   template.call($funcs),

I can't use header(), in template. (In this case, 'this.header' was available)
Answer: First you should check the documentation:
var domjs = require('domjs/lib/html5')(document);
// Execute mytemplate with h1, h2 etc. functions attached
var mydom = domjs.build(mytemplate);
console.log(mydom.firstChild.nodeName); // header

If you're asking how does it work (?) as you have some custom handling in mind -
It works by polluting the global scope for the time of function being called. You can see how it's done here -> https://github.com/medikoo/domjs/blob/v0.2.3/lib/dscope.js#L32-L36
btw. at all times you can access all those functions on domjs.map as domjs.map.header, domjs.map.h1 etc.
Method of using global scope, is controversial and has it's downsides (e.g. functions are not available after function returns) and in upcoming version of domjs this method would no longer be used. As an alternative Webmake (and possibly Browserify) plugins would be provided, so domjs templates can be bundled with those functions assured in local scope, then things will work natural way.


Dúvida em LINGUAGEM C

Question: Galera, boa noite.
Estou aprendendo C na faculdade e nos foi pedido um exercício para ler o salário de um funcionário.(até peço perdão pq perto dos mais experientes, meu código deve estar um lixo, mas tamo ai né...)
(O proprietário desta empresa determinou um reajuste salarial de 7,5% a todos os seus funcionários. Além disto, concedeu um abono de R$ 150,00 para aqueles que recebem até e, inclusive R$ 1750,00. Dado o valor do salário líquido de um funcionário, informar o salário final do colaborador.)
Eu consegui montar o código no devC++ MAS ele não está lendo o IF e o ELSE. Alguém consegue me ajudar ?
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ra;
    char nome[50], empresa[40];
    float sal_hoje, sal_total, sal_reajuste;
    printf("Ola, seja bem vindo a Boxbacon \n");
    printf("Digite o seu nome completo : \n");
    scanf("%s",&nome);
    printf("Digite o seu RA : \n " );
    scanf("%d", &ra);
    printf("Digite o seu salario : \n ");
    scanf("%f", &sal_hoje);
        if(sal_hoje <= 1750)
            {
                sal_reajuste=sal_hoje * (0,075);
                sal_hoje= sal_hoje + 150 + sal_reajuste;
                sal_total=sal_hoje;
                printf("tera um salario total de : , "sal_total);
            }
        else
            {
                sal_reajuste=sal_hoje * (0,075);
                sal_total=sal_reajuste + sal_hoje;
                printf("tera um salario total de : " sal_total);
            }

    return(0);

}
O que aparece é só isso

Tipo, ele não retorna o salário corrigido em nenhuma das hipóteses e eu gostaria de entender o que está errado.
Answer: O seu código caso não estivesse lendo os If e Elses, não imprimiria o

tera um salario total de :

Logo, o erro do código está nesta mesma frase, você não colocou o %f para a impressão do float, mas declarou a variável. E um outro erro no seu código é não colocar virgula depois da frase no printf, o correto seria:
 printf("tera um salario total de: %f",sal_total);

E um outro "erro", seria a utilização da virgula ao invés do ponto, no 0.075
Código plenamente corrigido:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ra;
    char nome[50], empresa[40];
    float sal_hoje, sal_total, sal_reajuste;
    printf("Ola, seja bem vindo a Boxbacon \n");
    printf("Digite o seu nome completo : \n");
    scanf("%s",&nome);
    printf("Digite o seu RA : \n " );
    scanf("%d", &ra);
    printf("Digite o seu salario : \n ");
    scanf("%f", &sal_hoje);
        if(sal_hoje <= 1750)
            {
                sal_reajuste=sal_hoje * (0.075);
                sal_hoje= sal_hoje + 150 + sal_reajuste;
                sal_total=sal_hoje;
               printf("tera um salario total de: %f",sal_total);
            }
        else
            {
                sal_reajuste=sal_hoje * (0.075);
                sal_total=sal_reajuste + sal_hoje;
                printf("tera um salario total de: %f",sal_total);
            }

    return(0);
}

Comment: Hmmm, tem isso ai também.
Corrigi aqui, mas testando novamente ele para no mesmo lugar. Ele não le o salario total
Muito estranho
Comment: De fato havia mais um erro, corrigi e enviei o código completo
Answer: Primeiramente nao precisa pedir para o usuario inserir o nome  da empresa, nem o R.A e o nome completo.
Primeiro: Você vai criar um nome fictício, o R.A tem que ser o seu e o nome completo tambem.
Segundo: Não vejo necessidade de usar #include <stdlib.h> mas, use #include <locale.h> setlocale (LC_ALL, "Portuguese"); para acentos se preferir.
As variáveis do float estão corretas. Acredito que você deveria criar nomes mais sugestivos para elas se preferir. Já as demais não há necessarias ter.
Seguindo o que voce ja fez segui uma ideia para resolução.
#include <stdio.h>
#include <locale.h>
int main(){
setlocale (LC_ALL, "Portuguese");
float sal_hoje, sal_total, sal_reajuste;

printf("\nDigite o seu salario : \n ");
    scanf("%f", &sal_hoje);

        if(sal_hoje <= 1750)
            {
                sal_reajuste=sal_hoje * (0.075);
                sal_total= sal_hoje + 150 + sal_reajuste;

            }
        else
            {
                sal_reajuste=sal_hoje * (0.075);
                sal_total=sal_reajuste + sal_hoje;

            } //obs: Nessa parte voce vai colocar a impressão das informações: sal_hoje,sal_total, sal_reajuste.

  printf(" \nO salario liquido é %2.f",sal_hoje );
obs: Os demais printf segui a mesma sequencia.
}

Dúvida em LINGUAGEM C


Conditional distribution of trivariate normal

Question: Consider three non-independent normally distributed random variables $(T,S,C)$. I am interested in the distribution of $T$ conditional on $S=s$ and
$C=c$.
I know that, for $\mu_T=\mu_S=\mu_C=0$ and $\sigma_T=\sigma_S=\sigma_C=1$, the conditional mean is given by
$E[T|S=s, C=c]=\beta_{TS;c} s+\beta_{TC;s} c$
where the betas are the regression coefficients: $\beta_{ij;k}=\frac{\rho_{ij}-\rho_{ik}\rho_{jk}}{\sqrt{1-\rho_{ik}^2}\sqrt{1-\rho_{jk}^2}}$
Is there a similar way to parameterise $Var[T|S=s, C=c]$?
NB. I'm not interested in a step-by-step derivation – I'd be equally happy with an expression derived from the symbolic integrals in Mathematica.
Answer: Assuming by "three non-independent normally distribution random variables" you mean that $(T,S,C)$ has a trivariate normal distribution with mean vector $(\mu_T,\mu_S,\mu_C)$ and covariance matrix
$$\Sigma=\left(
\begin{array}{ccc}
 \sigma_T^2 & \rho_{TS} \sigma_S \sigma_T & \rho_{TC} \sigma_C \sigma_T \\
 \rho_{TS} \sigma_S \sigma_T & \sigma_S^2 & \rho_{SC} \sigma_C \sigma_S \\
 \rho_{TC} \sigma_C \sigma_T & \rho_{SC} \sigma_C \sigma_S & \sigma_C^2 \\
\end{array}
\right)$$
Using Mathematica the conditional CDF for $T|S=s,C=c$ is
conditionalCDF = Probability[T <= t \[Conditioned] S == s && C == c,
  {T, S, C} \[Distributed] MultinormalDistribution[μ, Σ]];

Then the conditional PDF is
conditionalPDF = D[conditionalCDF, t]

We see from inspection that the conditional pdf is that of a normally distributed random variable with mean

and variance

which can be simplified to
$$\mu_T+\frac{\sigma_T (\sigma_C (s-\mu_S) (\rho_{SC} \rho_{TC}-
\rho_{TS})-\sigma_S (c-\mu_C) (\rho_{TC}-\rho_{SC} \rho_{TS}))}
{\left(\rho_{SC}^2-1\right) \sigma_C \sigma_S}$$
and
$$\frac{\sigma_T^2 \left(\rho_{SC}^2-2 \rho_{SC} \rho_{TC} \rho_{TS}+\rho_{TC}^2+\rho_{TS}^2-1\right)}{\rho_{SC}^2-1}$$
respectively.


How to add custom class in body tag on form submit?

Question: I have created custom module with custom form, in which I have added input type select. Form submission is working fine, but I wanted set select option value as custom class for BODY tag.
Comment: As per @samzha suggestion I used **Switch Theme** module and it's work fine for me, the only thing I need to create different themes for that.
Answer: You can add through custom hook.
<code> function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}
</code>
OR
<code>function YOUR_THEME_preprocess_html(&$vars) {
  $path = 'your-drupal-page';
  if (drupal_match_path($_GET['q'], $path) || drupal_match_path(drupal_get_path_alias($_GET['q']), $path)) {
    $vars['classes_array'][] = 'page-my-css-class';
  }
}
</code>
If you have any query related how to create then you can check this LINK.
Comment: Thanks for quick reply, but how do I get value of Selected option instead of 'new-class'?
Comment: Means you want to select any option default SELECTED ???
Comment: I am trying to create option for user to change theme color using select list.
Comment: Ok now I understand. You have some themes (Color) in your site & you want a select option & through this select option you need to jump one theme to another. Am I right ??
Comment: Yes, but instead of changing theme I want add class in Body tag
Comment: Try to use **Switch Theme** module or you have to use JS.
Comment: Another question is when do you want the change to take place? After form submit or before form submit?
Answer: Seems a pretty odd request and there might be a better way, please explain exactly what you're trying to achieve so a better solution could be offered.
Based upon your original post this could probably be achieved with the combination of Webform, Webform Rules, Rules, Context Rules & Context


Import CSV file in node-sqlite3

Question: I'm using the npm sqlite3 package in my web application for a mock-up restaurant. When my local server is started I'm creating a menuItems table:
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
  db.run('CREATE TABLE menuItems ('
          + 'itemName VARCHAR(255),'
          + 'itemDescription VARCHAR(255),'
          + 'unitPrice REAL'
          + ');')
  .run("INSERT INTO menuItems (itemName, itemDescription, unitPrice) VALUES"
          + " ('Fish Filet', 'Yummy fish in a sandwich.', 9.95)")
});

I would like menuItems table to be separate from this js file. Options I can think of:

Use current hard-coded commands to insert individual items into the table.
Use SQLite3 to import the CSV file and insert it into the table.
Read items from a CSV file and insert them in a loop.
Establish database before server starts and pass it into sqlite3.Database() constructor.

I'd like to go with option 2. However, I am open to any suggestion. There are ways to import the CSV file using SQLite. I'm trying to do this but from sqlite3 npm package. When I try to import the file via the same command (which seems to be sqlite3-specific) from the linked page:
db.run('.import "C:/Users/path/to/csv/file.csv"'
      + 'INTO TABLE menuItems'
      + 'FIELDS TERMINATED BY ","'
      + 'ENCLOSED BY "\'"'
      + 'LINES TERMINATED BY \'\\n\''
      + 'IGNORE 1 ROWS'
      + ');');

I receive:
events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: SQLITE_ERROR: near ".": syntax error

Trying normal SQL syntax:
.run('BULK INSERT menuItems'
      + 'FROM "C:/Users/path/to/csv/file.csv" '
      + 'WITH '
      + '{ '
      + 'FIRSTROW = 2,'
      + 'FIELDTERMINATOR = ","'
      + 'ROWTERMINATOR = "\n",'
      + 'ERRORFILE = "C:/Users/path/to/csv/error_file.csv" '
      + 'TABLOCK'
      + '}')

I receive:
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: SQLITE_ERROR: near "BULK": syntax error

Is my syntax incorrect? Is there a better way? Option 3 I haven't tried.
Answer: I ended up going with Option 3. Namely, I used the fs package to read in the CSV file, did some parsing, returned the results within a Promise object, and did the database insertions within the then of said Promise object.
Comment: Hi @NikhilAgarwal, the implementation can be found [here](https://github.com/natn2323/parzival/blob/master/public/javascript/DBManager.js) in the private `getCSV` function.
Comment: Can you share the code of the implementation? I have been doing this but still getting the errors..
Answer: try
db.run('.import "C:/Users/path/to/csv/file.csv"'
      + 'INTO TABLE menuItems'
      + 'FIELDS TERMINATED BY ","'
      + 'ENCLOSED BY "\'"'
      + 'LINES TERMINATED BY \'\\n\''
      + 'IGNORE 1 ROWS'
      + ')');

commands beginning with . don't need semicolon at end
Answer: There is a little example for read your csv into sqlite3 db.
const sql3 = require('better-sqlite3');
const   db = new sql3( 'memory.db' );
const  csv = require('csv-parser');
const   fs = require('fs');

// create table
db.exec( 'CREATE TABLE IF NOT EXISTS menuItems ( itemName TEXT, itemDescription TEXT, unitPrice REAL );' );
//db.exec( 'DROP TABLE menuItems;' );

const insrow = db.prepare( 'insert into menuItems ( itemName, itemDescription, unitPrice ) VALUES (?, ?, ?)' );

fs.createReadStream('C:/Users/path/to/csv/file.csv')
  .pipe(csv({"separator":";"}))
  .on('data', (row) => {

    insrow.run( row.itemName, row.itemDescription, row.unitPrice );
    console.log(row);
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
    db.close();
  });

The database in example is memory.db, and the csv format is not comma-separated, but semicolon separated, change separator, if it necessary.
The csv in this case must be started with itemName;itemDescription;unitPrice header, and a row looks like Fish Filet;Yummy fish in a sandwich.;9.95 and so on.
Answer:
create file.csv file for example, the header is the column names, rows are records, separated by ; and strings in "string" format:
itemName;itemDescription;unitPrice
"Fish Filet";"Yummy fish in a sandwich.";9.95

2.1 If the column types are not so important, you can import the csv file to the db, with a file.sql3:
.mode csv
.separator ";"
drop table if exists menuItems;
.import "file.csv" menuItems

2.2 run import from nodejs:
const { exec } = require('node:child_process');

exec('sqlite3 "memory.db" < "file.sql3"', (error, stdout, stderr) => {
    if (error) {
        console.error(`exec error: ${error}`);
        return;
    }
});

3.1 If the column types are important, you can import the csv file to the db, into a temporary tmp table, with this tmp.sql3:
.mode csv
.separator ";"
drop table if exists tmp;
.import "file.csv" tmp

3.2 run import from nodejs:
const { exec } = require('node:child_process');
const sql3 = require('better-sqlite3');
exec('sqlite3 "memory.db" < "tmp.sql3"', (error, stdout, stderr) => {
    if (error) {
        console.error(`exec error: ${error}`);
        return;
    }
    const db = new sql3('memory.db');

    db.exec( "CREATE TABLE IF NOT EXISTS menuItems(" +
                        + 'itemName VARCHAR(255),'
                        + 'itemDescription VARCHAR(255),'
                        + 'unitPrice REAL'
                        + ');');
    db.exec("INSERT INTO menuItems " +
          + "select itemName, itemDescription, unitPrice from tmp;");
});

Import CSV file in node-sqlite3


Azure active directory application registration for localhost and production

Question: I successfully registered my ASP.NET MVC application to work with Azure AD. Currently the Sign-on URL parameter (Azure Active Directory->App registrations->New Application Registration) looks like https://localhost:44302/
But for production it apparently will be another (say, https://mycoolapp.com)
How should set up the application so that I could use Azure AD locally (for ex. for debugging) and in production.
Changing the Sign-on URL parameter every time doesn't seem to be a good option.
Answer: Firstly, you can make it work easily without changing sign-on URL every time. You just need to make sure that both URLs.. i.e.  https://localhost:44302/ as well as https://mycoolapp.com are available in the Reply URLs for this application.
The value for Sign-on URL that you give at the time of creating app registration goes into two places. It becomes the Home Page URL under Properties for your web application and it also gets added as the first URL in the Reply URLs collection for your web application. Just make sure to add a the second URL to the Reply URLs collection after your app is registered and that's all.

On a side note, even though you can make things work with a single app registration for both production and localhost debugging, you may want to think about having two separate application registrations for production v/s local development and give permissions to production application only for administrators/dev ops if it makes sense.
Imagine any sensitive settings, like if you are using a secret key for your web application, you may not want your development team to have access to secret key for your production app registration even while debugging code. You can always change which app registration gets used in dev v/s production code based on configurations.
It's some of the headaches like these where Managed Service Identities are very appropriate, but whether that makes sense or not is a little different discussion than this one.
Comment: do you mean to change ClientId and RedirectUrl by use of web.config transformation?
Comment: 1. Simple way to make it work - Just go to "Reply URLs" for your application settings and make sure both production and localhost URLs are available there. Whichever is missing right now, add it and then click save. Look at the 2nd screenshot that I have in my answer
Comment: 2. Longer route (only if you want to keep separation between your local development app registration v/s your production app registration) - Only in this case.. you can create two separate application registrations.. one with Production sign on URL and another with Local sign on URL.. then as you said.. decide which ClientID gets used by the web.config transformation. This isn't the only approach, just an option and hence I say that you can choose either one.. 1 (simple way) or 2 (Longer route) depending on what makes sense for your application scenario..
Comment: I did make sure that both production and localhost URLs are available there, But production still redirects to localhost after signing in. https://www.screencast.com/t/L2ScpuZWx
I wonder how production (or localhost) environment should know which reply url to choose?
Comment: ok got it. I guess that might be because of a fixed redirect URL that is getting read from the configuration like in the ASP.NET MVC sample here https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-aspnet-webapp. If that is the case for you as well, make sure to use config transformations to set different values for Production ("https://mycoolapp.com") vs Local ("https://localhost:44302"). Now since you have both of them as valid reply URLs in your App Registration's reply URL collection.. it will work for both production and local. Try it out.
Comment: This is the code that I'm referring to in sample...

https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-aspnet-webapp

public class Startup
{
    // The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
    string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

    // RedirectUri is the URL where the user will be redirected to after they sign in
    string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];
Answer: I would specify the production URL as the Sign-on URL and the production + localhost as the redirect-URL (since you can add multiple redirect-urls!).
See: Register a new application using the Azure portal
Comment: I've checked: If I add https://localhost:44302 to reply URLs on the portal it redirects me to localhost after signing in (production, xyz.azurewebsites.net)
I didn't get what you mean under _and the production + localhost as the redirect-URL_
Comment: You can add multiple reply-urls
Comment: I did add multiple urls


How do you modulate between modes?

Question: I'm confused about how to switch modes in song. When you switch modes, will it switch like this (C Ionian -> C Mixolydian) or like this (C Ionian -> G Mixolydian)?  Also, how will you formulate chords that fit with the song when switching modes?
Also, there is this song that involves chords outside of the G Ionian Scale:
G Bm Em Dm G7 C Bm A D7
So what method did the artist use to create this chord progression?
Answer:
will it switch like this (C Ionian -> C Mixolydian) or like this (C Ionian -> G Mixolydian)?

Both; depends on what you want to do and where you want to go from the mode you are on. Let's look closely at these two examples.

We are in C Ionian mode (C major); if you go to C Mixolydian, you'll find yourself in the V mode of the F Ionian mode.
We are in C Ionian mode; if you go to G Mixolydian, you find yourself in the V mode of the C Ionian mode. If you want to stay in the C major scale, you can use G mixolydian. If you want to go to F major, you can use C Mixolydian. You can also use other Mixolydian chords to lead to other scales.

So, both of these examples are correct. In order to see which one to use in your song, just see where you want the harmony to lead to.
In this progression:
G Bm Em Dm G7 C Bm A D7
It uses chords from the G major scale:

G Bm Em all belong to the G major scale as I,iii,vi.
Dm G7 C belong to the C major scale as ii,V,I; C is the IV of G, so this is a ii V which leads to a chord in the scale we were in. This is really common in Jazz songs.
Bm A D7 belong to the G major scale again, as iii,V/V, V.

V/V means that A is the V of D, which is the V of G; so V of V or V/V.
The progression ends on D7 which is the V of G and leads back to the starting chord, which is G.
Comment: The only thing I would add is the distinction between borrowing chords and changing key/mode. This song doesn't really modulate, but takes advantage of  two secondary dominants (G7-> C and A -> D7) and the only other chord not native to G major (Dm) can be viewed as borrowed from the relative minor (or C major if you want to think in C) to make the G7 to C more convincing. Everything else is squarely in G major.
Comment: @Dom - 'borrowed from the parallel minor'?
Comment: @Tim it depends if you want to look at it tonaly, modally, or part of the sequence. If just a Dm popped up in the key of G I'd go with it being borrowed from the parallel minor or mixolydian mode (C major in this case).  It's typically not that big of a difference in how you look at it, but looking at it more like C major makes sense although then you kind of loose sight of it being from G.
Comment: It's probably wisest to see this as G Major with a tonicisation of the subdominant, which is immediately contradicted by iii of G minor and V of V (which directly "cancels" C as a potential tonic). The use of secondary degrees on B and E gives it a slight Aeolian feel, but not enough to challenge the very strong cadential movements to C and G.
Comment: Correct; ii V which leads to IV of G and the secondary dominant are the only chords that don't belong in G
Comment: @Dom - thanks, it was just that Dm doesn't belong to the relative of G - Em - or does it, given the melodic / natural minor notes?
Comment: @Tim while not used often v can show up in a minor key although V is much more popular due to it leading better to I.
Comment: @Dom - I've mostly seen v used in major keys to lead to IV. A sort of rootless 9th, I guess.
Answer: It seems to me that playing 7 chords make mixo easy and a flat 7. I like bouncing modes/ in more of a chord tone type of way. It's like having what I would call pivot points in a song. You can pivot to another mode without traveling. I may start on e minor and pull a major swing out and float on down to mixolydian by using seventh chords and making sure to play a d7. While in ionian you should keep it vague bouncing between the 2 and the 3 chromatically because nothing else is shown it is able to be almost anything. All of this must be fit in the context of a groove of some sort but they are great ways to play melodically without resolving your lines. I find the minors easy too with aeolian and dorian. It seems that the odd modes are phrygian and lydian. The maneuvers are achievable with them but they're harder to do because they are so distinctive. If you pull out Dorian flat 2 or lydian dominant I find that's the easiest branch but I'm sure there are other ways

How do you modulate between modes?


Feeds: How to import images using CSV Node Import?

Question: I try to use Node Import clone with an extra image field to import nodes with images attached.
Without success, I try to upload content from a local file (s).
I use CSV parser and Node Processor.
My content type has a image field called Photo I mapped to the csv format using the mapper.
I am using Windows as a local feeds source and Drupal 7 as a server.
How to import images using CSV Node Import ?
What should be exactly the image file path in the csv file ?
Comment: I use the latest dev of feeds module, Drupal 7.10 and I got error "Download of C:\file.jpg failed with code -1003."
Comment: Any reason you don't want to use http://drupal.org/project/migrate?
Comment: Your question mentions CSV parser and Node Parser. Are you referring to "Feeds Self Node Processor"?  If so, it has not been updated since February.  Are you sure the module is working correctly?
Comment: @MotoTribe the reason I'd prefer to use Feeds is that there is no UI for the Migrate module or at least I am not aware of any UI for setting up Migrate scripts.
Comment: @Ashlar , no, I didn't refer to Feeds Self Node Processor. I referred to Feed 4 edit options: Basic settings, Fetcher, Parser, Processor.
Comment: yeah, I prefer a UI myself. But there is good documentation and if you have to import more data in the future it might be worth using migrate.
Answer: I don't think it will work based on local files. The way I understand it, feeds is made to work off CSV data, with files that are already on the server.
It will take a bit of playing around on your part, but your best bet is to upload a single product/node with an image.  Find the path to that image. Once you find the folder where your image is being stored, upload your images to that folder.
Then give the direct path to the image on your server in your CSV file, in the image section. The path will probably look something like this, depending on the how you configured the image field. This example is from a Drupal Commerce site:
example.com/sites/default/files/styles/uc_product_big/public/image-you-want-to-use.jpg
If your server runs some sort of post processing (image-resizing, cropping, scaling), and then saves in multiple folders, I'm afraid you're out of luck with this method.
Answer: I am not entirely clear on what you are doing, but I had similar problems trying to read a text file in a custom module.  Any file used in Drupal must be imported using drupals api using file_save_upload or file_save ( I believe this puts the files in the database for handling by Drupal).  These files are saved within the Site directory structure (your download error message suggests yours are not). You may want to check the modules you are using to see if Drupal is saving the file. This process is necessary because browsers do not let outside sites access a users files without their permission.
Answer: To extend upon commercebythegradeo's answer.
There's a module available called:
Feeds Image Grabber
https://drupal.org/project/feeds_imagegrabber

What this module does is allow you to import the specified image from the URL into the node, rather than simply referencing it. This way all your post processing can be one, which as I see it was the only real flaw in the answer provided by commercebythegradeo.
Comment: This only works for HTML, not XML.


Choosing a piece to analyse

Question: I have to write an essay which consists in analyzing a piece of Jazz/Pop/Rock music or a short Classical piece or part of a Classical music score (all between 16 and 32 bars of length). I really don't know what piece can I analyse, does anyone have recommendations on what to look for in a piece which I can analyze (knowing that I am absolutely not an expert in music theory but I know the basics, such as chord progressions, brief harmonic analysis) ? This essay must be between 1400 and 1600 words. Any help would be appreciated,
Comment: "does anyone knows a piece which I can analyze" That is asking for specific recommendations, not advice on how to choose, which might be closer to being on-topic. Lists make poor answers for SE.
Comment: Just pick something at random.  Pick something you like.  Is this for a music appreciation class or something else?
Comment: Sorry, but this is far too broad to be answered, & cannot have any definitive answer, only a series of opinions. At best you will get a list of differing options, none of which can be "correct" & all equally valid.
Comment: yes that is what I want, opinions and ideas, not a specific answer
Comment: for a Musical Improvisation Class, so this will be graded
Comment: I'm voting to close this question because finding music is off topic.
Answer: Without giving you a specific recommendation because I think you should pick the piece yourself, I suggest you pick something you are familiar with, enjoy listening to, and understand and can analyze the harmony to without too much trouble.
I think American Songbook tunes (standards) or pieces from the 19th century classical/early romantic era are a good pool to draw from for this assignment. They tend to have rich and interesting melodies and harmonies that are easier to understand and analyze than most modern jazz and classical music and more interesting than the majority of rock and pop music, from an analytical point of view.
Answer: I'd use a jazz standard, I think they are ideal for the purpose. Which one depends on different factors you haven't described (degree of difficulty, whether the harmony is "functional", etc.) Summertime, All the Things You Are, So What... they are all very different, but the changes are really easy to get hold of, their length is suitable, they are used for studying these things, their chords are not strange (7th, mostly), their melodies are intuitive, etc.

Choosing a piece to analyse


How do you add space between characters except for a word?

Question: I have a string:
string = "abc(word)def(word)oiu"

I need the output as:
spaced = "a b c (word) d e f (word) o i u"

Comment: And what have you tried?  You either need to do a character at a time, or use `split` and process the pieces.
Comment: I have tried " ".join(string) but that puts a space between all characters. I am looking to have space between except the string (word)
Comment: What I mean is `x.split("(word)")`, then expand the parts, the rejoin them.
Comment: except a word, or except anything within brackets?
Answer: One way using re.sub:
s = "abc(word)def(word)oiu"
re.sub("\(.+?\)", lambda x: x.group(0).replace(" ", ""), " ".join(s))

Output:
'a b c (word) d e f (word) o i u'

This will first put spaces in between all characters, and remove spaces that are between brackets.
Answer: Keep it simple and avoid regex trickery for a basic situation
like this:
s = "abc(word)def(word)oiu"
w = '(word)'

spaced_out = f' {w} '.join(' '.join(text) for text in s.split(w))

Answer: You can use the pattern '\(.+?\)|.' to separate the input into substrings that should be joined by spaces, and then use ' '.join() to insert those spaces.
We look for a (, followed by one or more characters, followed by a ). We use ? so that we stop at the next closing parenthesis we see, rather than the last ) in the string. If we can't match that pattern, we just take the next character:
import re
data = "abc(word)def(word)oiu"
result = ' '.join(re.findall(r'\(.+?\)|.', data))
print(result)

This outputs:
a b c (word) d e f (word) o i u

Answer: This can work for any given string.
string = "abc(word)def(word)oiu"
skip_word= "(word)"
spaced_string = " ".join([char for char in string])
spaced_word =  " ".join([char for char in skip_word])

spaced = spaced_string.replace(spaced_word, skip_word)


How to move from some arbitrary "distance" to a probability distribution?

Question: I'm doing some object recognition, and when I compare two images, I get some unbounded "distance" between the two images, representing how similar they are.  This is somewhat useful, but it seems like it would be more useful if I could move from this "distance" space into a probability space, where instead of " The distance between image A and image B is X ", I could get " P(image is of class B | image A) = X' ".
What is a reasonable way to move from a distance space to a probability space?
Answer: Distance immediately makes me think of multivariate Gaussian variables because the probability density is a function of the norm of the vector $(x_1, x_2, ..., x_n)$. But I guess in your case it seems that you want to associate a probability with a distance $d$ and not an $n$-tuple of coordinates.
I am afraid there is not a single solution. As @Emre points out, you only need a  one-to-one mapping from $R^+$ to $(0,1)$, which will be your cmulative density function, but you won't know how well that mapping will discriminate your object/images.
Here are a couple of suggestions:

The exponential distribution
The symmetrized Gaussian
The Gamma, log-Normal or Weibull distribution (the mode is away from 0, so this assumes that there is a typical distance between two random images).
Answer: If you want to merely constrain the output to a bounded range, use a continuous transformation like $d \to 1-\exp(-d)$, where $d$ is the distance.


What is the domains folder used for in Glassfish?

Question: I was getting inside the folders of Glassfish, I found a folder named domains and inside it I found domain1.
My questions are:

what is domains and what is it used for?

seeing the folder domain1 make me understand that we can have domaine2, domaine3 and so on

what is the rule, do we have to have many domains?
when should we create another domain folder ?
Answer: A domain in GlassFish is basically a set of configurations that are used together in a single environment. Usually, you would need a single domain folder and it's safe to use the stock domain1. Inside a domain you can define multiple isntances and even multiple clusters so you don't need to have more than one domain at a time.
More domains are useful when you want to switch between different configurations frequently, or as templates for varioius environments. You could have a development domain, test domain, production domain, each tuned for specific environments.
For example, Payara Server, which is derived from GlassFish, adds additional payaradomain, which is tuned for production, while the default domain1 is tuned for development as it's in GlassFish. Therefore you may easily choose  the best default configuration for your needs just by switching the domain when you start the server.
Another usecase would be if you develop 2 or more unrelated applications and you want to keep them separate in the server. Then you would create a separate domain for each of them and run GlassFish with the appropriate domain so that the applications are isolated. The second domain can be configured to a different set of ports so that the servers don't collide.
Comment: Using Netbeans, you can create a new domain in UI. You have to "Add Server...", even if you already added Payara before. Continue to add Payara Server again, but in the **Domain location** dialog, type in the name of a new domain in the **Domain** field instead of selecting an existing one. Netbeans will create a new domain and use it with this server configuration.
Comment: having these 3 domains `development, test and production` seems as a best practice is it the case?
Comment: Yes, I would say it's best practise to have a separate configuration for development, test and production. However, they don't need to be present in the same GlassFish/Payara installation. Alternatively, you can have 3 different installations of GlassFish and always use domain1 with different configuration, it's up to you whether having multiple configuration domains is convenient.
Comment: can you please tell how can we work with different domains technically (in netbeans and glassfish)? any link that explains this?
Comment: In Netbeans, you simply specify the name of the domain when you add a new server instead of the default `domain1`. For each domain you need a separate server configuration (add new server). Here's [a detailed guide](http://blog.payara.fish/adding-payara-server-to-netbeans) If you want to start from command line, just add the domain name as a parameter ot the `asadmin start-domain` command
Comment: thank you for the valuable information, I make your answer a correct one  =) . But I still need one more information if you can be "more" kind, I've created a new domain in glassfish server interface, but the folder of the new domain was not created in the domains folder, how is it possible to create a new domain (ofcourse not in the CMD but in a UI, netbeans or glassfish server)
Comment: The only way to create a new domain is using the command line as I described. If you create a domain using the UI, it's a different thing. You maybe created a new instance or a new virtual server bound to a HTTP domain. But there's no way to create a new domain in UI because UI only modifies the current domain of the running server.


How to stop the display of the native context menu on ios when using the QML TextInput

Question: I am using Qt5.7.1
In iOS long press on the QML TextInput displays the native context menu with Select/Select All/Paste items. How do i prevent this menu from showing, while allowing the TextInput to still be editable.
If i use Qt 5.6.2 the TextInput displays no such menu.
With the below code i am able to prevent the context menu from displaying in 5.7.1, however the cursor position always ends up at the end of the text.
import QtQuick 2.5
import QtQuick.Window 2.0

Rectangle
{
 color: "yellow"
 width: 100; height: 100

 Rectangle {
     color: "white"
     width: 100; height: 50
     anchors.centerIn: parent

     TextInput{
         id:tip
         text:"test123"
         anchors.fill: parent

         onActiveFocusChanged: {
            console.log("tip onActiveFocusChanged")
         }
         onCursorPositionChanged: {
             console.log("onCursorPositionChanged:" + tip.cursorPosition )
         }

         MouseArea {
             id:ma
             anchors.fill: parent
             propagateComposedEvents:true

             onPressed: {
                 console.log("ma onPressed:" + tip.cursorPosition )
                 mouse.accepted = true
                 tip.focus = false;

             }

             onClicked: {
                 console.log("ma onClicked:" + tip.cursorPosition )
                 mouse.accepted = false
                 tip.forceActiveFocus();

             }

             onPressAndHold:{
                 console.log("ma onPressAndHold")
                 mouse.accepted = true
                 tip.focus = false;
             }
         }
     }
 }
}

I wonder if there is some better way i could do this and also have a fully editable TextInput.
Answer: I could stop the edit menu from displaying on ios with the hack below :\
import QtQuick 2.5
import QtQuick.Window 2.0

Rectangle
{
    color: "yellow"
    width: 100; height: 100
    Rectangle {
         color: "white"
         width: 100; height: 50
         anchors.centerIn: parent

         TextInput{
             id:tip
             text:"test123"
             anchors.fill: parent
             MouseArea {
                 id:ma
                 anchors.fill: parent
                 propagateComposedEvents:true

                 onPressed: {
                     mouse.accepted = false
                     tip.focus = false
                     tip.focus = true
                 }
             }
             onSelectedTextChanged:tip.deselect()

         }
     }
}


Mongo query for newest and oldest data in months in a range of dates

Question: I have in mogo data:
    {_id: 1, value: 4.0, date: ISODate("2024-01-01T00:00:00.000Z")}
    {_id: 2, value: 6.0, date: ISODate("2024-01-03T00:00:00.000Z")}
    {_id: 3, value: 9.0, date: ISODate("2024-01-08T00:00:00.000Z")}
    {_id: 4, value: 11.0, date: ISODate("2024-01-14T00:00:00.000Z")}
    {_id: 5, value: 16.0, date: ISODate("2024-01-28T00:00:00.000Z")}
    {_id: 6, value: 20.0, date: ISODate("2024-02-03T00:00:00.000Z")}
    {_id: 7, value: 24.0, date: ISODate("2024-02-07T00:00:00.000Z")}
    {_id: 8, value: 30.0, date: ISODate("2024-02-19T00:00:00.000Z")}
    {_id: 9, value: 37.0, date: ISODate("2024-02-25T00:00:00.000Z")}
    {_id: 10, value: 40.0, date: ISODate("2024-03-02T00:00:00.000Z")}
    {_id: 11, value: 44.0, date: ISODate("2024-03-06T00:00:00.000Z")}
    {_id: 12, value: 52.0, date: ISODate("2024-03-10T00:00:00.000Z")}
    {_id: 13, value: 60.0, date: ISODate("2024-03-17T00:00:00.000Z")}
    {_id: 14, value: 60.0, date: ISODate("2024-03-26T00:00:00.000Z")}
    {_id: 15, value: 68.0, date: ISODate("2024-03-29T00:00:00.000Z")}
    {_id: 16, value: 40.0, date: ISODate("2024-04-04T00:00:00.000Z")}

I want to receive in query result two values (value nearest the begining of month, and value nearest to the end of month) for each month form range of date.
example: I want data form range 2024.01.01-2024.04.30 then I want to receive:
    {_id: 1, value: 4.0, date: ISODate("2024-01-01T00:00:00.000Z")}
    {_id: 5, value: 16.0, date: ISODate("2024-01-28T00:00:00.000Z")}
    {_id: 6, value: 20.0, date: ISODate("2024-02-03T00:00:00.000Z")}
    {_id: 9, value: 37.0, date: ISODate("2024-02-25T00:00:00.000Z")}
    {_id: 10, value: 40.0, date: ISODate("2024-03-02T00:00:00.000Z")}
    {_id: 15, value: 68.0, date: ISODate("2024-03-29T00:00:00.000Z")}
    {_id: 16, value: 40.0, date: ISODate("2024-04-04T00:00:00.000Z")}

Answer: You can create an auxiliary field named dayOfMonth using $dayOfMonth to get the respective day in the month. Then, use $setWindowFields to compute the respective ranking in the partition of the month with $dateTrunc. After that, select either ascending ranking or descending ranking. In case of 2 entries sharing the same day, replace $rank with $denseRank to fetch both records.
db.collection.aggregate([
  {
    "$match": {
      date: {
        $gte: ISODate("2024-01-01"),
        $lte: ISODate("2024-04-30")
      }
    }
  },
  {
    "$set": {
      "dayOfMonth": {
        "$dayOfMonth": "$date"
      }
    }
  },
  {
    "$setWindowFields": {
      "partitionBy": {
        "$dateTrunc": {
          "date": "$date",
          "unit": "month"
        }
      },
      "sortBy": {
        "dayOfMonth": 1
      },
      "output": {
        "ascOrder": {
          $rank: {}
        }
      }
    }
  },
  {
    "$setWindowFields": {
      "partitionBy": {
        "$dateTrunc": {
          "date": "$date",
          "unit": "month"
        }
      },
      "sortBy": {
        "dayOfMonth": -1
      },
      "output": {
        "descOrder": {
          $rank: {}
        }
      }
    }
  },
  {
    "$match": {
      "$expr": {
        "$or": [
          {
            $eq: [
              1,
              "$ascOrder"
            ]
          },
          {
            $eq: [
              1,
              "$descOrder"
            ]
          }
        ]
      }
    }
  },
  {
    "$unset": [
      "ascOrder",
      "dayOfMonth",
      "descOrder"
    ]
  }
])

Mongo Playground


How many people can "cut down the net"?

Question: It's traditional for winning college basketball teams to "cut down the net" when they reach the Final Four. But just how many people (players, coaches, staff) are allowed to cut down the net?
That is, can assistant coaches cut down the net?
Comment: Are there ncaa rules regarding post-game celebrations?
Answer: There isn't a rule stipulating who "can" cut down the net.  In terms of numbers, there are typically 12 connections of the net to the rim (which could be cut 24 times if they needed more).  Normally, the players on the team (up to 12 per NCAA rules) will cut off a piece of one of the connecting strings as a momento.  However, if there are honorary people who helped the team in some way, they usually are also given an opportunity to cut a piece as well (read the following article for such a case).
Typically, the head coach cuts down the last string which brings down the net, but in the case of the 2013 NCAA championship, Louisville's Kevin Ware cut down the last 3 "connections" to bring down the net. (Kevin Ware had a gruesome injury during the Elite 8 and wasn't able to play in the Final Four or Championship game).
Whether assistants or staff do/can, it's really up to the team.  This is largely a ceremonial event to celebrate the champions, so it's at their discretion.  In my experience, they typically leave it to the players and head coach to do the cutting, but others may get a piece of the net later.
As a matter of history, you can check out this article detailing the origin of the tradition.  It wasn't always as ceremonial as it is today.

How many people can "cut down the net"?


Armazernar valor e quantidade array PHP

Question: Preciso varrer o primeiro array e armazenar o valor e a quantidade desse valor em outro array. Não estou conseguindo pois estou com dificuldade na hora de armazenar os valores em outro array.
Array:
array(5) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "12"
  }
  [1]=>
  array(1) {
    [0]=>
    string(2) "13"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "100"
  }
  [3]=>
  array(1) {
    [0]=>
    string(3) "12"
  }
  [4]=>
  array(1) {
    [0]=>
    string(3) "13"
  }
}

Array com o valor e quantidade que preciso:
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "12"
    int() "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(2) "13"
    int() "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "100"
    int() "1"
  }
}

Comment: Você quer contar a quantidade de itens no array? O `count()` não traz resultado?
Comment: Traz sim só não consigo armazenar em outro array, gostaria de um novo array que nem citado acima. Não somente um `count` mostrando a quantidade de itens do array.
Answer: Oi, Kevin
Acredito que você pode resolver essa questão utilizando a função array_count_values(). Documentação aqui.
Ao fim do uso dessa função, seus valores se tornarão chaves do outro array. Com um foreach ($array as $valor => $ocorrencias) você consegue percorrer o array produzido e colocá-lo no formato desejado. ;)
Answer: Para complementar a resposta do Macário Martins, primeiro teria que transformar a array multidimensional em uma array simples... Usei o exemplo do SO
$dados_unidimensional = call_user_func_array('array_merge', $dados_bidimensional);

isso vai transformar sua array
[ [ "12" ], [ "13" ], [ "100" ], [ "12" ], [ "13" ] ]

em
[ "12", "13", "100", "12", "13" ]

Com isso você consegue usar o array_count_values()
$resultado = array_count_values($dados_unidimensional);

E $resultado será algo do tipo
["12" => 2, "13" => 2, "100" => 1]

Answer: O seu array parece ser um multi-dimensional. Tente dessa forma:
<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
}

Em $ar1[] troque pelos seus arrays

Armazernar valor e quantidade array PHP


Electric guitar amp won't switch to distortion channel

Question: I have a Peavey Classic 30 combo amp (tubed). There's a channel switch button on the amp that is meant to toggle between the clean and distortion channels. However when I attempt to toggle from clean to distorted, I get no distortion. The tone stays clean. I've had the amp for about 5 years now and it used to work with no problems. How can I get the amp to properly switch to the distortion channel? Is it something I can do myself, or will I need to take it to a music shop?
Comment: @Dom - Yes, all the tubes seem to be good judging by the looks. Some tubes are more illuminated than others, but it seems like that has always been the case.
Comment: Is there maybe a knob on the distortion channel (Gain or something) that isn't turned up enough?
Comment: @Shevliaskovic - Yes there is a Gain knob but I've tried twisting all combinations of controls to no avail.
Answer: With a couple of my smaller Peaveys, the amp. switch works in conjunction with the footswitch. When the amp. switch is 'on', the footswitch will then toggle between clean/dirty. You may have inadvertently switched the footswitch, which you may or may not usually use.Check the instructions (downloads available) before doing anything drastic. Do not swear at it - amps are very sensitive ...
Comment: Until you plug in to that socket, you won't know.It's a TSR (stereo) jack.
Comment: So are you saying the amp could "think" that there's a footswitch plugged in?
Comment: I'm saying that if the footswitch is in, it may need switching on.
Comment: I don't own a footswitch.
Comment: Well, it can't be that then ! Lots of Peavey amps have a socket in the back to connect a footswitch for channel change and reverb.
Comment: It does have a port to connect a footswitch, I just don't have one. That's what I meant from my earlier comment. It could be that the amp is acting as though a footswitch is plugged in, even though one isn't. Possible? Maybe? Not sure.
Comment: AFAIK, you can test it with a stereo plug by shorting the tip to ground. Google "peavey classic 30 footswitch schematic"


How to reset simulators for specific Xcode version using fastlane?

Question: Within gitlab-ci.yml I have:

test:
  stage: test
  before_script:
    - killall "Simulator" || true
  script:
    //how can I select proper xcode here?
    - bundle exec fastlane snapshot reset_simulators --force
    - bundle exec fastlane test
  after_script:
    - killall "Simulator" || true
    - rm -rf ~/Library/Developer/Xcode/Archives || true
  artifacts:
    name: "Staff_${CI_PIPELINE_ID}"
    paths:
      - fastlane/output/coverage
  when: on_success
  tags:
    - iOS

Why do I need to do that?
Because reset_simulators --force resets simulators for different xcode version than I use;) How can I force it to select good xcode version?
Answer: If you want this for scan or run_tests
It now supports
reset_simulator

Enabling this option will automatically erase the simulator before running the application
SCAN_RESET_SIMULATOR

just call
xcversion(version: 11.0)
run_tests(
    reset_simulator: true
)

Answer: It looks like you have your own Fastfile which has your test lane. I would suggest that you reset the simulators in there. Then add the xcode_select call before the reset.
For example:
lane :test do
  xcode_select('/Applications/Xcode9.4.1.app')
  Snapshot::ResetSimulators.clear_everything!(nil, true) # what reset_simulators ends up calling
  # your other code
end

Answer: Have you tried the fastlane action "reset_simulator_contents"
This will reset all simulators running on the test machine.


Drush Update to a patched module?

Question: What happen when you drush up update a module with Drush because of security issue and the module contain few patches for other features?
The reason why I'm asking is because I have patched few modules and now they have security update which does not contain the features that I wanted.
What is the best practice to update a module that have a security updated and you have patch this module ?
Answer: The best practice is to find some way to implement your feature that does not require patching the original module.  Sometimes this is not possible due to lack of available hooks to provide the functionality that you want.
In these instances, you can try out some of the patch-management solutions, such as bandaid or drush-patchfile, which might help you out here.
Sometimes, though, the changes made in the security update will prevent your patch from applying cleanly; in this case, you have no choice but to re-roll the patch, and figure out what changes need to be made to get it working again.  This makes your site maintenance much less convenient, so it's always best to try to work with the module maintainer, and see if you can get your feature added as a standard part of the module, or, failing that, perhaps get the maintainer to add the hooks that would be needed to add in the feature without patching.

Drush Update to a patched module?


Open Atrium 2 or Drupal Commons or Simple Drupal with OG

Question: What will be the best option to build a fully functional social collaboration and community website in Drupal? Open Atrium 2 or Drupal Commons or new install of Drupal 7 with Organic groups?
I am good in Organic groups but redoing everything will be tricky though considering already existing distributions like Open Atrium and Drupal Commons.
Comment: We need a bit more to go on. What are you trying to accomplish?
Answer: Drupal Commons has a terrible track record or maintainability and upgrade path.  I only recommend using Drupal Commons or Open Atrium when they fit your needs out-of-the-box.   If you have very custom needs, definitely go with a custom D7 & OG build.
If you find that Drupal Commons or Open Atrium have features that you would like to replicate, then install them somewhere else and use them as a guide for creating your own features.
The best answer is to say you need to try them all and determine their strengths and weaknesses according to your project, but from personal experience, I have regretted every project I've used Drupal Commons on, and won't do it again.
One project I did, we started with Drupal Commons, and eventually realized that it was not a good fit.  So we just copied all the features we wanted into a normal D7's sites/all/modules directory.
Answer: Have a look at the (fairly new) alternative for the Organic groups module, which is the Group module. Some more details about it (from its project page):

Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
Groups instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" OG module.


How to theme a view block

Question: I'm a drupal beginner. I'm using drupal 7 and views. I created a block using views in order to list my latest projects. I'm displaying the block in my home page. I would like to know how to override HTML and Css in order to display something like this:
I want to use this code:

Projects One

                                On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire

                            more details

Answer:
Open the view which you've created, expand Advanced Option column
open Theme:Information
copy the last theme suggestion from Row style output row
go ahead to the theme(project theme) folder and create that file,
example, views-view-fields--docs---page-1.tpl.php (this is how my
template looks like, this is just for an example), rescan the templates, and save the view.
debug $fields array (better install Devel module, it provides useful functions, like dpm(), dsm()..)
Copy the code from the sample template and put into this template.
Lastly, put the output of fields (e.g. something like this <?php print $fields['SOME_FIELD']->content; ?>) to the desired html blocks..

Don't forget to clear the cache;
Answer: The solution presented by @xurshid29 is good.
For me i use view modes, with that you can design the list as you want with a tpl file that you create and associate it with your view, you can also make more than one design for the same block.
This is a helpful link to see more details about this solution : 3 Easy Ways to Create View Modes in Drupal 7

How to theme a view block


Is zero (Integer) treated as blank or empty in Django?

Question: I tried integer zero in a input field (IntegerField), however that zero never appears to be show after submit.
This is part of my template:
{{user_date_table.june_11}}
{% if not user_date_table.june_11_steps %}
 <form action="/steps_count/index/{{ username }}/table/" method="post">
  {% csrf_token %}
  <input type="text" autocorrect="off" autocapitalize="off" name="june_11_steps"/>
  <input type="submit" value="Add"/>
 </form>
{% else %}
 {{user_date_table.june_11_steps}}
{% endif %}

I think that if not user_date_table.june_11_steps throws "True", i.e. it is blank if I use zero as input. Is this correct, and can I overcome this?
Answer: In python, all of the following are evaluated as False:
'', "", 0, [], {}, (), False, None

So, user_date_table.june_11_steps is 0, then {% if not user_date_table.june_11_steps %} will be evaluated True and that block will be executed.
UPDATE: For solution,

If user_date_table do not take place in your context while you display the form, or if it is empty, you can use
{% if not user_date_table%}

Pass another value to your template, like display_result, and use that to check which fieldset will be displayed.

views.py:
if request.POST: #saving the post data
    display_result = True

template.html
{% if not display_result %}
    <form action="/steps_count/inde...

But the first approach is always better.


is CPU actually occupied during iowait (%wa in top) on Linux / EC2?

Question: On an 8-way Amazon EC2 instance (running Linux 2.6.21) with 8 EBS volumes and a lot of disk traffic, we see high %wa in top (30-40%), and high load average (8-9). My understanding is that processes waiting on I/O from the EBS volumes are counted in the load average (a ps shows several processes in the D state, about as many as the load average).
However, it's not clear what %wa means. Is a CPU actually occupied waiting for a response from the EBS volume, or does the kernel schedule another process on it? I would expect that another process would be scheduled; but then I don't understand why iowait time would be expressed as a percentage of total CPU time (unless the percentages add up to more than 100%).
So long as we don't max out the I/O capacity of the EBS volumes I'm not concerned, but if the CPUs get tied up waiting for I/O I think our machine will run out of CPU capacity before running out of I/O capacity.
Answer: The CPU can and will be used for other processes, provided there is at least one process that is ready to receive CPU time.  There's the rub - you can have an I/O-bound system with every process waiting for I/O to complete, and as there is nothing waiting for CPU time, there is no reason to schedule (and utilize) CPU for anything other than the kernel's activities...hence the term, I/O wait.
Try running vmstat 1 and see if there are numbers greater than 0 in the "b" column (2nd column) on a regular basis.  If so, you're probably I/O-bound.  Seeing it occasionally isn't a big deal, seeing it all the time with numbers in the 2-3 range is tolerable but not desireable, and seeing more than 5+ means you're probably way too busy (although that depends on how much I/O your system can accomodate, so it can be more or less, depending).  The "b" means "processes blocked", as in, "the number of processes scheduled to run, but were blocked, pending the completion of an I/O".

Follow-up:
There is a known bug with heavy I/O and the newer schedulers on the 2.6 series of kernels.  Try changing your scheduler to see if it has an impact.
Comment: I still don't quite understand what %wa measures. Suppose a processor starts out in the idle state, then runs a process that needs I/O. It is then in the iowait state until the I/O completes or there is another runnable process?
Comment: Whichever comes first.  If another process shows up, it gets the CPU.
Answer: man vmstat states:  "wa: Time spent waiting for IO. Prior to Linux 2.5.41, included in idle."


What are these octave like shapes used in popular indie rock?

Question: I've got 2 octave(?) related questions. One about starting on the A string and one about starting on the E string.

Regarding the A string: there's a specific part of a Strokes song called "Reptilia". What are the octavey things that are being played during this video at 1:08?

 (its the first break in the song with one isolated guitar before the chorus starts) They're not traditional octaves as they're more than a single string apart. What would you call these?
Regarding the low E string, I've been messing around with the following pretty shapes that were inspired by fingering the above shapes. They all follow a similar pattern (just moving the bass note around):

3rd fret on the E string and 4th fret on the G string
5th on the E string and 6th fret on the G string
9th fret on the E string and 10th fret on the G string

Similarly I can find other spots on the fretboard that seem to fit (the 7th fret E string for example) but I have to adjust my finger so that the G string is also on the 7th fret.
Thanks guys. Hopefully that made sense. I hear these types of voicings in songs from Foals, Daughter, Frightened Rabbit, and The Strokes. If you need more examples let me know.
Answer: These shapes in both your E string and A string questions are minor and major tenths. A 10th is a 3rd interval but with an added octave separating the two notes.

The TAB helps and shows the starting pair of notes is, low to high, B and D so it is a B with a minor 10th above it. The second pair is F# and A, another minor 10th. Even though they are not complete chords because they don't have a 5th they sound like B minor and F# minor chords. The third and fourth pair are major tenths, G and B, then A and C#. These two sound like G and A major chords. The rest of the pattern is made up of the same 4 shapes in a different order, 3,4,2,1.
Regarding the E string shapes, they too are 10ths, in your case G and B, A and C# and C# and E#, all major 10ths. The one where both notes are on the 7th fret is a minor 10th, with B and D notes.

The 10ths are fingered differently with the low note on the E string as opposed to the A string because of the major 3rd tuning between the G and B strings. The guitar part on Blackbird by the Beatles is made up almost entirely of major and minor 10ths alternating with the open G string, it's worth a listen.
Comment: @Tim, That has the 10th sound for sure, it's actually both upright and fretless basses overdubbed. Classic recording.
Comment: Somewhat reminiscent of Walk on the Wild Side?
Answer: They are not octaves, because they are not playing the same note.
They are thirds (spanning more than one octave of course), a type of dyad for the purists. They are used in countless riffs and songs (Scar Tissue by RHCP and Blackbird by The Beatles, first that I can think of besides what you mentioned).
Among with power chords and already mentioned octaves, they are staples of the rock and metal rhythmic repertoire because they are easy to strum with energy, leaving enough space for other instruments.
While you can have just one type of octave (i.e. perfect or just), you can have minor and major thirds - like in chords, because it's the third that gives a chord its major or minor quality.
You can see how they are a portion of the corresponding bar chord:
<code>Minor shape

-x------
---o----
-----x--
-----x--
-o------
--------

Major shape

-x------
-----o--
-----x--
-----x--
-o------
--------
</code>
Apply same reasoning to question 2 : ))
You may ask: how to write a meaningful sequence of thirds? It's exactly like chords, harmonised major scale is the keyword for starting (full of resources on this site already).
Comment: "not playing the same note" – better say _pitch class_. And, the standard term for that interval is _tenth_, though they are of course very related to thirds.