Looping through Mongo Results in NodeJS and adding field or using virtuals

Question: I'm somewhat new to Node and MongoDB and I'm running into a really odd problem. I'm trying to add a new field to a json being printed out from a MongoDB. But for whatever reason, it doesn't show up. Anyone know what I'm doing wrong?
Here is an example
app.Event.find({},['_id','dateStart']).where('status').equals(1).where('dateStart').gte(searchDate).sort('dateStart', -1).exec(function(err, events) {
    for (var i=0; i< events.length; i++){
        var url = 'http://localhost/' + events[i]._id;
        events[i].url = url;

        //Printing here does not show the new URL
        console.log('Looking at event... ' + events[i]);

        //But printing here does show it...
        console.log('Address should be ' + events[i].url);
    }

    //And printing here does not as either...
    res.json(events);
});

I know that I can add the field to my schema, which isn't really what I want. When I add a virtual field URL to my schema, I still don't see it in the results:
Event.virtual('url').get(function() {
    return 'http://localhost/' + this._id;
});

Event.set('toJSON', {
    virtuals: true
});

Event.set('toObject', {
    virtuals: true
});

Comment: Is there data? Use the console to verify.
Answer: Your solution with the virtual should work, provided that you create the model after you created the virtual on the schema (which is named the same as your model, correct?).
So this doesn't work:
var Schema = new mongoose.Schema(...);
var Model  = mongoose.model('Model', Schema);
Schema.virtual('url').get(...);

But this should:
var Schema = new mongoose.Schema(...);
Schema.virtual('url').get(...);
var Model  = mongoose.model('Model', Schema);

(the configuration of toJSON and toObject are still required)


Genymotion Struck in black screen

Question: My Genymotion strucks in the black screen as shown below .When I restart my MAC, the genymotion starts and works perfectly but it quits automatically (after an hour). When I try to start the Genymotion from Virtual box I get the error "cannotfind 'system/bin/install-recovery.sh' disabling 'flash_recovery;". Please see SS below for error from Virtual Box. Thanks in Advance !!
Comment: maybe try checkout out this answer, is for a similar problem http://stackoverflow.com/questions/39547907/genymotion-stays-on-black-screen-when-loading-emulator/39547908#39547908
Answer: This problem was because of connecting to VPN.If I disconnect from VPN things work perfect. Posting it here so that it may be useful to someone else. Thanks !!

Genymotion Struck in black screen


Getting command line argument that stores in a variable

Question: I am writing a bash script to finger the first three line of user's info.
ex:
<code>$ ./c.sh bob unknown
Login: bob                           Name: Bob
Directory: /u1/h7/bob                Shell: /bin/tcsh
Office: AA 044, x8361                   Home Phone: 000-000-0000

unknown: no such user.
</code>
Here is my code so far
<code>#!/bin/bash

if [ $# == 0 ]; then
  echo "Usage: ./c.sh Login/Username"
  exit
else
  i=$#
  j=1
  while [ "$j" -le "$i" ]; do
    finger ${$j} | head -n+3
    echo
    j=$(($j+1))
  done
fi
</code>
instead of giving what user types for the command line arguments, ${$j} is giving me the the value of $j, any suggestion and help for how to get the login/username? I've tried $($j), $((j)), ${$j}....
Answer: The easy answer: stop using unnecessary indirection:
<code>#!/bin/bash
if (( $# == 0 )); then
  echo "Usage: ./c.sh Login/Username"
  exit
else
  while [[ $1 ]]; do
    finger "$1" | head -n+3
    echo
    shift
  done
fi
</code>
or…
<code>…
for user; do # equivalent to `for user in "$@"; do`
  finger "$user" | head -n+3
  …
done
</code>
You could write it this way:
<code>i=$#
j=1
while [ $j -le $i ]; do
  finger "${@:j++:1}" | head -n+3
  echo
done
</code>
…but you don't need to work that hard.
Comment: Just use `for user; do` to iterate over the script arguments.
Comment: @EtanReisner matter of style. There's nothing wrong with `while [[ $1 ]] … shift` IMO
Comment: Other than only being able to loop over the arguments once and requiring extra processing to shift the entries down (as trivial as that effort may be), no there's nothing wrong with it. It just doesn't give you any benefits either since you don't even get the benefit of current argument count from that loop (that you would from the manual `++` counting version).
Comment: @EtanReisner but all of the things you mention are things that are not needed in this program. There are cases where the `shift` version is better suited over the `for` loop version, too. In this case, it just doesn't matter.
Comment: That doesn't make it a matter of style though. And yes, there are times when `shift` is exactly what you want, this isn't one of them as far as I'm concerned but ultimately this is bike-shedding at this point.
Answer: <code>#!/bin/bash
if [[ $# -eq 0 ]]; then
    echo "Usage: $0 Login/Username"
    exit
else
    for ARG in "$@"; do
        finger "$ARG" | head -n 3
        echo # If you want a newline
    done
fi
</code>
As simple as it can be.


AngularJS REST call to another server

Question: I'm using the Yeoman generator for AngularJS and I would like to interact with a REST server (who uses Spring Boot).
In my computer:

AngularJS app starts with Grunt on http://localhost:9000/
Spring Boot app is on http://localhost:8080/

In my AngularJS app I have a service like that :
angular.module('myApp')
  .factory('User', ['$resource',
    function($resource){
      return $resource('http://localhost:8080/poc/hello', {}, {
        query: {method:'GET'}
      });
  }]);

And here is the controller :
angular.module('myApp')
  .controller('RegisterCtrl', ['$scope', 'User', function($scope, User) {
      $scope.hello = User.query();
}]);

In my Java app :
@RestController("poc")
public class PocController {

    @RequestMapping("hello")
    public String getHello() {
        return "Hello World !";
    }
}

But when I want to do the call, I'm being blocked by "CORS"...
What is the best way to do what I want to do ? Not only for GET request, but POST, etc...
Is it possible to "configure" the REST server URL (http://localhost:8080/) once and make all AngularJS call (like /poc/hello) redirected to http://localhost:8080/poc/hello ? If yes, how ?
Comment: Read this [Guide](https://spring.io/guides/gs/rest-service-cors).
Answer: set headers in your rest server, following is some data I set on my node server but the details should help:
'Access-Control-Allow-Origin': 'http://localhost:9000'
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE'
'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
'Access-Control-Allow-Credentials': false

AngularJS REST call to another server


Simple way to fit large number of single factor logistic regression models in R - automatically

Question: I have a dataset with one binary target variable called "target" and many many factors "F1", F2"… "F200". I'm trying to come up with code to fit 200 single factor logistic regression models and return the model summaries. Here is what I have so far
single <- function(df, factor){
    s <- summary(glm(as.formula(paste('target ~ ', factor, sep='')), family=binomial, data=df));
return(s);
}
single(data, c("F1", "F2", "F2"));

but this gives me only a summary of the first model. Am I missing something obvious here?
Answer: Here's a solution using lapply. It will return a list of model summary objects.
lapply(c("F1", "F2", "F3"),
       function(x) summary(glm(df[["target"]] ~ df[[x]], family=binomial)))

Your codes does not work because you run paste('target ~ ', c("F1", "F2", "F2"), sep='') which results in "target ~ F1" "target ~ F2" "target ~ F2". Converted to a formula, it returns target ~ F1.
Update
A solution which returns a matrix of regression results.
An example data frame:
set.seed(42)
df <- data.frame(target = sample(0:1, 10, TRUE),
                 F1 = rnorm(10), F2 = rnorm(10), F3 = rnorm(10))

predictors <- c("F1", "F2", "F3")
fits <- sapply(predictors,
               function(x) {
                 tmp <- try(coef(summary(glm(as.formula(paste("target", x, sep = "~")),
                                             family=binomial, data = df)))[2, ], TRUE)
                 if (class(tmp) == "try-error") NULL else tmp})

The result (fits):
                   F1         F2        F3
Estimate   -0.1864527 -1.2242511 0.6751601
Std. Error  0.8259677  1.0915999 0.8770035
z value    -0.2257384 -1.1215200 0.7698488
Pr(>|z|)    0.8214049  0.2620666 0.4413896

Comment: Brilliant. Is there an easy way to summarise results (from the list) into a data.frame so it is easier to see which factors are the strongest predictors? I accepted the solution BTW. This could only be an extra +
Comment: Also another minor thing. The summary(glm)) stuff is a little bit criptic as it shows something like "data[[x]]" instead real factor name F167 for example.
Comment: @user13467 See the update of my answer.
Comment: thanks. Your code works well, but when I run it against my real data half way through I'm getting the "subscript out of bounds" error. I presume this is happening because if model can not be fit there is no [2,] part to select from summary glm summary. I suppose I need to find a way to check if model was fit and THEN look up coefficients
Comment: @user13467 I added error handling. See update.
Comment: You are amazing. Never heard of this function....where did you dig it from... very useful indeed! Thanks a million.


Degree sequence on graphs

Question: I think I'm doing something wrong in the following exercise, but I don't know what it is.
Let the degree sequence of a graph be: $\vec{d}=(d_1,d_2,\dots,d_n)$, where $d_1\ge d_2\ge...\ge d_n\ge 0$, where $d_i$ is the degree of vertex $i$ in the graph. Obviously there are $n$-vertices in the graph.
Show that there's a loopless graph with degree sequence $\vec{d}$ if and only if $\sum_{i=1}^n d_i$ is even and $d_1\leq\sum_{i=2}^n d_i$.

Part $(\Rightarrow)$: In a loopless graph, $d_1\leq m$, where $m=\frac{1}{2}(\sum_{i=1}^nd_i)$. Therefore: $d_1\leq \sum_{i=2}^nd_i$.
Part $(\Leftarrow)$: I have no idea. For example, $n=3$, I know that $d_1\leq d_2+d_3$. I can prove by example that there's a loopless graph, but not for a general case.
Comment: You're given the ordering, so I don't know that you need to prove it. I find it strange that you're given that "$\sum_{i=1}^n d_i$ is even" when that's required for _any_ graph, but you aren't given any limits on that sum (eg. $n(n-1)$)
Comment: It's true, the order (I was ignoring this, dammit) is given and by construction, if you like, the sum over the degrees is even, so these two things are checked. The exercise is from Graph Theory, Bondy, 1.1.16. So there can be a loopless graph with these conditions, although I just really need the fact that the sum over the degrees is even. A graph with loops may have degree odd in one of its vertices (for example de graph $V=\{1,2\}$, $E=\{(1,1),(1,2)\}$. What do you think?
Comment: Ah... I was thinking we were talking about simple graphs, and took "loops" to mean cycles, and a loopless graph to mean a tree. If not, then the proposition is false I think, or requires a multigraph.
Comment: The tip given by the authors is: Sufficiency, induction on $\sum_{i=2}^n d_i-d_1$. I cannot find a suitable argument to apply this.
Comment: This theorem can also be found in the book "Graph Theory" of Bondy and Murty (2008), p.10, exercise 1.1.16.
Answer: The part you are missing can be proved by induction on $\sum d_i$.
The base case $\sum d_i=0$ is realized by $n$ isolated vertices.
Assume $\sum d_i>0$, so at least $d_1\geq1$.
Case 1: $d_1=d_2+\ldots+d_n$. Then take the graph with vertices $v_1,\ldots,v_n$,
and $d_i$ edges from $v_1$ to $v_i$ for all $i=2,\ldots,n$.
Case 2: $d_1<d_2+\ldots+d_n$. The difference between the two sides must be at least 2, since
the total sum is even. Since $d_1\geq1$ and $d_1$ is the largest value,
there must at least be two nonzero values after $d_1$.
Now subtract 1 from the two lowest nonzero values
and apply the induction hypothesis. In the resulting multigraph
add an edge between two vertices whose degrees correspond with the values you reduced in the previous sentence.
Comment: There is no requirement to prove that ONLY loopless graphs can be constructed satisfying the conditions. You only need to show there is at least one loopless graph satisfying them.
Comment: Nice. You could make the inequality into an equality with the addition of a $2k$ term (justified as even in the same way),  $d_1=d_2+\ldots+d_n+2k, k \ge 0$ to give your proof a more familiar induction look.
Comment: Thanks for the answer. Just one comment that still confuses me (I'm not mathematician but physicist). I will take the case $d_1 < d_2 + \dots + d_n$. Think in the star-loop graph, such that $d_1$ is the center of the star (and therefore has $n-1$ vertices). Now think that every tip of the star has a loop, so the sum over $d_j,\;j\ge 2$ will be $2(n-1)$. In this way, I have created a loop graph with the second part of the proof, apparently contradicting the loopless requierement.

Degree sequence on graphs


Negative Latent Factors in Factorization Machines

Question: I'm studing a specific implementation of a recommendation system leveraging on a factorization machine algorithm. For each person_id and item_id combination, I have an implicit rating of 1 or 0 depending on if the user downloaded the content or not. In the base model, I have just utilized as input variables the person_id and the item_id. I selected a latent factor number equal to 5. In the model output, some of the 5 the latent factors associated to some person_id and item_id are negative, and some predictions of the rating for the combination person_id/item_id are negative too. I have searched for some theoretical explanations but not found much material, so here I am.
How a negative latent factor can be explained in this setting?
Being the training dataset provided with the target variable equal to 1 or 0, how the model end up with negative predictions for the implicit rating?
Answer: Found after some digging many concepts related to Non-Negative Matrix Factorization, which if properly setup constrain a FM algorith to come up with non negative factors (and therefore predictions.). Many useful material here:

https://en.wikipedia.org/wiki/Non-negative_matrix_factorization
https://towardsdatascience.com/parts-based-learning-by-non-negative-matrix-factorisation-1279ffd29618


Thunderbird 15.0.1 cannot use Exchange 2003 SMTP

Question: I'm having the strangest time getting a Thunderbird email client to connect to my Exchange 2003 server.
I got the incoming IMAP account set up no problem, and I can receive mail. However sending mail will not work no matter what SMTP settings I enter. After checking the server, the proper settings should be port 25 with no authentication or connection security, which I have entered. I can ping the hostname of the server from the client machine in question. The Thunderbird error message I get is:

"Sending of message failed. The message could not be sent because the
  connection to SMTP server -hostname omitted- was lost in the middle of
  the transaction."

So I went to the server and double checked the settings for Exchange's SMTP stuff. I have it correct. I tried to telnet (on the server) to localhost 25. It appears to connect and then disconnect immediately, no message, no nothing. When I telnet to other ports (POP-110 for example) I get proper connection messages and a stable connection. There are no firewalls on either the client or the server. There's a firewall on the network but LAN->LAN traffic is unrestricted.
I can reproduce the Thunderbird error on a second client, and I can't get any client to be able to telnet in.
EDIT: I'm having the same problem with Zimbra Desktop.
Anyone have any ideas?
Comment: Disable the Connection filter on the properties of the SMTP Virtual Server and try both the Thunderbird and Telnet test again.
Answer: In Exchange System Manager, Org/Servers/ServerName/Protocols/SMTP/ Properties on your Virtual Server.
Access tab....
Authentication - Anonymous should be checked
Connection Control - All except...
Relay (key) - Make sure bottom "allow those that authenticate" is checked. I would also, for grins, add the IP of your client to the lest. At least this way you have something to test with.
N
Comment: Thank you! It was the Connection Control that I had missed. For some reason the subnet had been added as a single computer entry (eg. 10.0.0.0 instead of 10.0.0.0 (255.0.0.0)) and 127.0.0.1 wasn't in the list at all. When I deleted the single entry for the subnet and readded it properly as a group of hosts, everything began to work. I'm not sure if adding 127.0.0.1 is actually necessary, but I added it as well.


Prove a norm inequality by Lagrange multipliers

Question: I would like to prove that $\left \| x \right \|_1 \le \sqrt{n} \left \| x \right \|_2$ for all $x \in \mathbb{R}^n$ using Lagrangian multipliers.
Thank you all for your help!
Answer: Hint: Minimize $(\left \| x \right \|_2)^2$ under the constraint $\left \| x \right \|_1=C$ where $C$ is a constant.
Note that the optimal $x$ may either be at a point of non-differentiability of $\|x\|_1$ or where the contour of $(\|x\|_2)^2$ is tangent to $\|x\|_1=C$. The local optimum in the latter case can be found using Lagrange multipliers. In the former case show that if some $x_i=0$ then $(\|x\|_2)^2$ is not minimal (by deleting the zero components of $x$ and thereby reducing to the Lagrange Multiplier case).


How to copy Data from a data class to an object in C#.(Unity)

Question: I want to define a method to copy data from another data class to  a new defined object and then return it. For example:
public GameData Gett() {
    point pt = new point();
    return pt;
}

public class point : GameData
{
    public int TouchGround;
}

So what should I do to copy the data from TouchGround to pt and then return it as an object?
Answer: If your objects basically have some primitive type properties, your data classes like Point (should be uppercase!) could implement the ICloneable interface. That means mapping the data by hand:
class Point : ICloneable
{
    public int TouchGround;

    public object Clone()
    {
        return new Point
        {
            TouchGround = this.TouchGround
        }
    }
}

If you have to copy alot of properties on different classes, you could utilize a framework like automapper (http://automapper.org/).
It allows you to do something like:
Mapper.CreateMap<Point, Point>();
var point = new Point();
Mapper.Map<Point, Point>(existingPoint, point);

Another option would be creating your data objects as structs. Structs are copied on assignment.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/structs
Answer: For shallow copy, you can use MemberwiseClone() method available in C#  ICloneable interface. So, your point class should be changed to this.
public class point : GameData,  ICloneable
{
    public int TouchGround;

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

For shallow copy, you can use this.
    point a = new point();
    a.TouchGround = 1;

    // Next lines, create a shallow copy of a and put into b.
    point b = (point)a.Clone();
    b.TouchGround = 20;

    Console.WriteLine(a.TouchGround);
    Console.WriteLine(b.TouchGround);
    Console.ReadLine();

For deep copy, you would need to serialize this class and then de-serialize as another object of same type. You can do this using Newtonsoft.JSON. Your class should be serializable. Check this for similar details. You can also use DataContractSerializer.
    point x = new point();
    x.TouchGround = 35;

    point y = JsonConvert.DeserializeObject<point>(JsonConvert.SerializeObject(x));
    y.TouchGround = 40;

    Console.WriteLine(x.TouchGround);
    Console.WriteLine(y.TouchGround);
    Console.ReadLine();


The constructor is undefined. (Working with an Array here)

Question: So the goal of my school assignment is to print the elements of the Array through a constructor that is in my Dwarves class.
The array should contain objects, and each of those objects should have their own name.
But when I try to create an object in the main, the object wants me to put a string value in the default constructor of the object... so how can I print my Array data with a constructor in the main?
For my Dwarves class.
package prac11;

public class Dwarves {
Dwarves[] speler;{
    speler = new Dwarves[8];
}
public String name;

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

    speler[0] = new Dwarves("Muir");
    speler[1] = new Dwarves("Buith");
    speler[2] = new Dwarves("Gort");
    speler[3] = new Dwarves("Coll");
    speler[4] = new Dwarves("Duir");
    speler[5] = new Dwarves("Quert");
    speler[6] = new Dwarves("Nion");
    speler[7] = new Dwarves("Gus");

//  name[0] = "Muir";
//  name[1] = "Buith";
//  name[2] = "Gort";
//  name[3] = "Coll";
//  name[4] = "Duir";
//  name[5] = "Quert";
//  name[6] = "Nion";
//  name[7] = "Gus";

}
public void identify() {
    for (int i = 0; i < speler.length; i++) {
        System.out.println("I am " + speler[i]);
    }
}
public void killDwarf(String name) {

}

}

For my main
package prac11;

public class SnowWhite {

    public static void main(String[] args) {

        Dwarves figure = new Dwarves();
        figure.generate();
        figure.identify();
    }

}

edit: didn't know how to embed code. :)
Code is written in Java.
Comment: please include the code don't use screenshots. it makes it tedious for potential answerers to hae to retype your code in order to help you... read [ask]
Comment: i'm wondering wich version of PHP is that. initialize the parameter with default value or pass one into the construktor
Answer: The code looks more like java.
You have a single class trying to accommodate a single dwarf and a dwarf collection. This is not working.
The class should be Dwarf() which represents a single dwarf. For this, the constructor is correct; it accepts the name of the dwarf.
The generate() function should be outside the class. This function will create the collection of dwarf instances. You can create a new class for this, but java already has several collection classes you can use.
Comment: So it kind of work right now, for the object part.
But for the output i get this:

I am prac11.Dwarves@7852e922
I am prac11.Dwarves@4e25154f
I am prac11.Dwarves@70dea4e
I am prac11.Dwarves@5c647e05
I am prac11.Dwarves@33909752
I am prac11.Dwarves@55f96302
I am prac11.Dwarves@3d4eac69
I am prac11.Dwarves@42a57993
Comment: You're printing the class names. You should print the dwarf name: `System.out.println("I am " + speler[i].name);`
Comment: Thank you very much!! :)


How to notate two nested repeat loops (||: and :||) that finish on the same repeat finish sign :||?

Question: I have made a transcription of a song with the following structure:
Intro, A, B, A, B, A, Coda
The score that I created is the following (the content of the bars was replaced by whole notes for simplicity):

But after some thought, I don't think that the repeat finish sign :|| on bar 15 is considered valid notation in this case. First of all, it does not have a matching repeat start sign ||: (because these are already matching some other repeat finish sign :||). But assuming (as I did) that it is supposed to loop back to the beginning of section A to achieve the structure mentioned above, I noticed that I would have written the exact same score if the piece had the following different structure:
Intro, A, B, B, B, Coda
What notation can be used in this case to achieve the intended structure (besides writting notes on the score or duplicating sections A or B in the score)?
EDIT 1:
I found a new reason to think that the score that I show above is wrong for this case. I thought that the repeat finish sign :|| on bar 15 had precedence over the Dal Segno al Coda navigation mark. But then I found in other post (in the accepted answer, by Aaron) an example where there is a repeat loop with two different endings X and Y (bars 11 and 12, respectively), where:

Ending X is played on the first and second times (1 and 2);
Ending Y is played on the third time (3).

Inside ending X, there is a Dal Segno that is taken on the first time. I thought we would only jump to Segno on the second time (i.e., the last time on ending X, but it turns out that we jump on the first time already. Similarly, I see that the D.S. al Coda on my score must mean that we jump to Segno also on the first part, which would correspond to the following structure:
Intro, A, B, A, Coda
In other words, the x3 notation on the repeat finish sign :|| is irrelevant.
EDIT 2:
Clarification: I'm asking for a solution that is not writing notes on the score or duplicating sections A or B in the score because I am using Guitar Pro 8 for two things at the same time:

Write this score to then export it to a PDF. For this reason, duplicating is not desired because I wish to have a compact sheet;
Generate an audio file (based on the score). For this reason, manual notes won't work for sequencing the different parts for the audio file generating.

I'm trying to have a single Guitar Pro 8 file for both of these things so that I don't need to edit in two different places if changes need to be made in the future.
EDIT 3:
I posted a follow-up question to this one with a different attempt to write the score for this piece of music.

Related threads:
I found some very informative posts about nested repeats and their mixed usage with Segno/Coda navigation marks, but none of them refer to this specific case where the the outer and inner repeat loops end in the same repeat finish sign :||. The posts I read are:

Is there a good way to denote nested repeats?
Is there a way to
notate the repeat of a larger section that itself has repeats in it?
[duplicate]
Priority of Da Coda vs. Repeat sign
Dal Segno al Coda and repeats in Guitar Pro. This last one really confirms what I already suspected, which is that Guitar Pro makes its own assumptions when navigation marks such as Da Segno/Da Coda are mixed with repeat signs and sometimes the playback of the audio is unexpected when compared to the sheet. But I'm not going to talk about Guitar Pro on this question.
Are there established good practices for how to use musical navigation markers correctly?
Repeat sign without a match
Comment: Regarding this and your follow up question, from my experience, complicated road maps like this are just begging for reading errors and wasted time in rehearsals. It's better to minimize repeats, repeat endings, D.S. and coda signs or even eliminate them. With digital notation one no longer has to write everything out, just copy/paste. I would much rather read a linear 5 page chart than a 2 page chart and have to jump back and forth from section to section.
Comment: With @JohnBelzaguy on this one.  Most definitely just write the whole thing out.  This gave me a headache and when it's just whole notes.  Save your rehearsal time for musicality instead of roadmap questions.  Or, the happy medium would be write out the entire A/B section with no internal repeats.  Your printed music would be intro, A/B with just ONE repeat and "3x" text, and the coda.
Comment: @John Belzaguy I tend to agree with you, but this is a very short transcription of a [piece](https://www.youtube.com/watch?v=biLeC5D4S48) for one guitar mainly for my own playing, but I still want it to be readable to others. I wanted to erase duplicate bars because each bar is very hard and intricate (3 voices + wild left hand fingerings). Even if I write sections A and B without inner repeats (which I actually did before posting this question), the question still stands, as it regards the outer structure, which is quite simple but seemingly difficult to notate with standard notation.
Comment: @nuggethead The solution you provide does not correspond to the intended structure, as it would play B a third time which is not intended. If B were to be played a third time, this would indeed be a much simpler case to solve, as you mentioned. I could write Intro, then A and B inside a repeat, then a duplicate of A and then the Coda, but one other reason I am so focused on a compact sheet is that this one fits into a page the way I posted it, and I intend to do a collection of around 15 or 20 transcriptions of the same soundtrack, so space is one of the dominant factors.
Comment: @AntónioCharana If you are using computerized notation then the complexity of the bars is insignificant as you can copy/paste bars. What I'm seeing here is ||: A B :|| A coda. Rewriting A makes life much easier for everyone. Every "solution" I've seen makes me scratch my head, and I do this for a living!  :)
Answer: The simplest solution would be to include a note at the beginning of the A section to the effect of "Play A B A B A; take all repeats."
However, since the score must work both written and for playback, I can offer the solution in MuseScore, short of knowing if this will work in Guitar Pro.

The key features are:

A section break must be placed at the end of the B section (hard to see here, because it overlaps the D.S.).
For both the D.S. and D.S. al Coda, the Play Repeats property must by checked.
Comment: What I meant to ask is if there is any solution using only repeat signs/navigation markers/other navigation notation and no notes or writing duplicates of sections A or B? I edited the post accordingly
Comment: @AntónioCharana No. Standard notation does not allow for this. Conceivable you could use nested repeat signs, where the outer signs use a clearly different format — say, with brackets, rather than "simple" double bar lines.
Comment: Okay, it is as I though then. Also, supposing that the *D.S. al Coda* was missing from the score, is there any convention to where the repeat finish sign `:||` on bar 15 should loop back to? Or is it plainly incorrect notation to have it there in the first place?
Comment: @AntónioCharana I'm not sure I'd go as far as "incorrect," but for certain it's ambiguous. Absent the D.S, I would presume B.
Comment: On a given bar, Guitar Pro 8 only allows to put one D.S. (al Coda/Double Coda/fine) and one D.S.S. (al Coda/Double Coda/fine). It does not allow to put two D.S. marks on the same bar. I also searched for the section break feature, but found no evidence that it exists on Guitar Pro 8.
Answer: It's easy to write this in a way that a human player can read (and at least some notation programs, for example Finale).
The repeat in measure 15 is ambiguous. Leave it out and write "2x D.S. (con rep.)" (or "with repeats" instead of "con rep.") so you go back to the segno twice. Then make it clear that the coda is to be taken the third time through and not the second: "3.x al Coda".
The result: intro A B A B A coda.
A lot of musicians will assume that repeats are not made after a "Dal Segno", so it's always safer to make it explicit whether the repeats are to be taken ("con rep."/"senza rep.").
Comment: Thank you, this would be a good and clear solution. Unfortunately I think Guitar Pro 8 does not provide a good way to do this while preserving the correct audio playback and not polluting the sheet with additional D.S. marks or manual text notes.
Comment: I marked this answer as the accepted one even though the only way to do it in Guitar Pro 8 is to add manual text notes (which do not affect the playback audio). This seems the most clear solution. Although, for future readers of this question, the conclusion I got from all answers in this thread is that my question *does not have a solution using pure standard notation*.
Comment: @AntónioCharana Whether it's "pure standard notation" or not, I very often see parts written exactly the way I describe, and bands have no trouble reading them. If you are constantly pushing the limits of what Guitar Pro can do, you might want to consider changing to a more complete notation program e.g. MuseScore.
Comment: I was not very rigorous when I said "pure standard notation". Let me ractify: there is no solution using **only** (Dal) [Segno | Segno Segno | Coda | Double Coda | Capo] navigation markers (without manual 2x/3x/no rep. indications) and repeat signs. I believe you in that much music is written this way and that makes sense and is valid. I learnt with this post that "pure standard notation" does not provide a solid way of notating simple structures like the one I mentioned. But I found no source/textbook teaching these manual notes as part of standard notation, hence my comment.
Answer: There is no way to unambiguously specify what you want without either adding text instructions or adding at least some more music to the score. You could add third and fourth time bars to the end of section B, using DS at the end of the 2nd time bars, a repeat sign at the end of the third time bars (which would be read as going back to the start of section B) and DS al coda at the end of the 4th time bars. However this does not guarantee that a performer will automatically play all the repeats in section A on the second and third times through them - there are styles of music where omitting these repeats would be expected.
Your bars 3 and 6 are both played 6 times. If the first time bars (bars 4 and 7) are both marked 1, 3, 5 instead of 1, and the second time bars (bars 5 and 8) are both marked 2, 4, 6 instead of 2, this would clearly indicate that the repeats are to be played on each pass through. It would however be clearer to write out section A in full without using repeats.
Comment: I'm not sure I understood what you meant by adding the third and fourth time bars at the end of section B. You mean adding two additional bars after bar 15? Or you mean representing bar 15 not just as ending `2.`, but as ending `2. 3. 4.`? The first case would add long rests. If you meant the second case, I meanwhile posted a new follow-up [question](https://music.stackexchange.com/questions/132531/can-dal-segno-and-dal-segno-segno-appear-on-the-same-bar/132533#132533) where I tried something similar with _D.S._ and _D.S.S. al Coda_ but without the additional third and fourth time bars.
Comment: I meant that you have a 1st time section, a 2nd time section, a 3rd time section and a 4th time section. The notes in the 1st and 3rd would be the same, and the notes in the 2nd and 4th would be the same. You could, if you wished, use `1. 3. ` on the first time section and only have 3 sections there `1, 3`,  `2` and `4`. The separate 2nd and 4th time sections are needed to ensure that the right thing happens on the right occasions when they are reached. This is all based on printed scores; some things may not be supported by various notation programs.


How to get indices of valid values of numpy masked array

Question: I have a netCDF4 dataset representing multiple matrices of the same dimension (551, 146), one matrix (M1) contains longitude values, another matrix (M2) contains latitude values. Each matrix is a numpy masked array.
Given a lon/lat tuple, (A, B), I want to get the matrix indices (lon, lat) where value A matches in M1 and value B matches in M2.
I thought I could represent the indices with:
lon_idx, lat_idx = np.mgrid[:lon.shape[0], :lon.shape[1]]

and two matrices of same shape where one have all values set to A and the other have all values set to B.
Then I am hoping to somehow combine these matrices and end up with an array of lon, lat indices where the values matched.
What is the idiomatic way to do this in numpy?
Comment: .. Try `np.ix_`?
Comment: Please include a [MCVE], including the output you're looking for.
Comment: @Divakar I think I would need more than that hint to understand how to solve my problem. I've tried using `np.ix_`, but it takes 1-d arrays, and I have matrices, i.e 2d arrays..
Comment: Try printing `np.where(M1 == A)` and see what you get. You should get the indices you need.
Answer: Thanks to SnoopJeDi on #python @freenode who found the solution for me:
In [58]: np.argwhere((lon == lon[250][145]) & (lat == lat[250][145]))
Out[58]: array([[250, 145]])


What are the actual notes of each natural harmonic?

Question: So I know that if you play a natural harmonic at the 12th fret, this is just the same note as fretting the 12th is. Also, when I play my electric guitar and listen to lots of metal music in particular, I can hear that some natural harmonics sound really good after certain chords etc. while others do not. Does anyone have any theory or a resource that could reveal the notes the natural harmonics along the fretboard produce because I really like using them in my playing but often just don't know if they're going to sound good or not at that time.
And if you can answer the same for pinch and touch harmonics, that would also be useful.
Answer: Harmonics occur at the whole-number ratios of the length of the string, e.g. 1/2 the length of the string, 1/3 the length of the string, 2/3 the length of the string, 1/4, 3/4, etc.  The lower the numbers involved, the easier the harmonic will be to play.  So for example, theoretically there's a harmonic at 6/19 the length of the string, but it will be much harder to play than the one nearby at 1/3 the length of the string.
To determine the pitch of the harmonic, just divide the open string's frequency by the harmonic's string-length ratio.  For example: the 7th fret is 1/3 of the length of the string (from the nut), so if the open string's frequency is X, then the frequency of the harmonic at the 7th fret is X/(1/3) = 3 X, which is an octave-and-perfect-fifth above X.  Two harmonics who's string-length ratios have the same denominator (when in lowest terms) have the same pitch, so for example the harmonic at 2/3 the length of the string will also be an octave-and-perfect-fifth above X.
The most common harmonics occur at:

12th fret (ratio 1/2): an octave above the open string
7th fret (ratio 1/3): an octave plus a fifth above the open string
5th fret (ratio 1/4): two octaves above the open string
4th fret (ratio 1/5): two octaves plus a major third above the open string
9th fret (ratio 2/5; equivalent to 1/5): same as at the 4th fret, since the ratios have the same denominator.

Those are all I can think of right now; feel free to mention other common harmonics in the comments and I'll add them.
All of this works for pinch and touch harmonics as well, since when you fret a string, you're basically making it into an open string with a shorter length.  The harmonics will all be in the same places relative to the length of the fretted string.  In practical terms, to determine the fret at which a fretted string's harmonics occur, all you have to do is add the fret number to the harmonic's fret number.  For example, if you fret a string at the 4th fret, then the "12th fret harmonic" will now occur at the 4 + 12 = 16th fret, so there will be a harmonic at the 16th fret with a pitch one octave higher than the fretted note.
Comment: Adding to this great (and old) answer, there is a 3rd fret harmonic, but it doesn't coincide with the fret cleanly (differences between Pythagorean and equal temperament tuning systems), and it produces a note two octaves and a major third higher. The second fret harmonic also exists, but it takes quite a touch on a well-made guitar, and produces a harmonic two octaves and a dominant seventh above the open, but is very flat by equal-temperament standards. Jaco used it sometimes on bass solos like Portrait of Tracy, I'm not aware of too many other notable examples.
Answer: 5th fret harmonics are the same note as the open string, 7th fret harmonics are the same as the 7th fret notes (low to high - b,e,a,d,f#,b).  Touch and tapped harmonics are the same as the fretted note assuming you are touching, tapping one octave higher and pinch harmonics change depending on where you pick/pinch the note.  For pinch harmonics if you pick one or two octaves higher up the fretboard you will get the same note.  You can usually get a clear harmonic a fifth (7frets) higher as well. eg press on the third fret and perform a pich harmonic on the 22nd fret.  The harmonic will be a fifth higher than the fretted note.  I would suggest getting a tuner and experimenting for yourself, its more fun that way and you might find something cool.  Have fun.
Answer: Be aware, too, that the guitar is a tempered instrument.  In order for all keys to sound close to in tune, some compromises are made, so that thirds for example are not exactly tuned to a whole number ratio.  This means that the further up the harmonics go (the higher the numbers in the whole number ratios others describe), the less guarantee you have that the harmonic will match its tempered equivalent.  Check out Musical Temperament on Wikipedia for a discussion.


Custom javascript file not working in mobile browsers

Question: I have added a custom jQuery file to my theme with the theme.libraries.yml. In my laptop and fullscreen browsers the added javascript is working without any issues. But it seems the javascript does not have any effect in mobile browsers(I'm testing with ipad and iphone browsers in both safari and chrome). My custom_theme_libraries.yml is as following
global-scripts:
  js:
  js/jqueryfile1.js: {}
dependencies:
- core/jquery

And my jqueryfile1.js is as following
(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

Is there any additional configurations to be considered to get the code works in mobile browser also?
Comment: No - JavaScript is JavaScript, if the file is in the source then the code will be executed, there's no mobile v non-mobile distinction unless your JS code checks the viewport/user agent. You can easily tell by adding test code, e.g. an alert, at the top of the file. By the by, the use of `ready` is redundant, behaviours are already delayed until DOM ready
Comment: Yes, the difference is not mobile, probably logged in or not. The error could be the missing spaces before the dependencies in the yaml file.
Comment: Thanks i will take these into consideration and and will update you the result soon
Comment: You don't need to add document ready, that is redundant within a behavior.
Answer: It seems like your code is the problem. You have extra });
Should be
(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      $(document).ready(function() {
        // code goes here
      });
    }
  };
})(jQuery);

But it is nonsense to use $(document).ready as it is already handled by Drupal.behaviors.
So the proper way is.
(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      // code goes here
    }
  };
})(jQuery);

The attach() method is called when the DOM has loaded both initially and after any AJAX calls.
See this doc for more info. https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


Como comparar instâncias de LocalTime?

Question: Como faço para comparar duas variáveis de LocalTime no Java? Não consigo usar os padrões.
import java.time.DayOfWeek;
import java.time.LocalTime;

public abstract class CorrespondenteBancario {

    private DayOfWeek diasDeFuncionamento[];
    private LocalTime horarioDeAbertura;
    private LocalTime horarioDeFechamento;

    public CorrespondenteBancario(DayOfWeek diasDeFuncionamento[], LocalTime abertura, LocalTime fechamento) {
        LocalTime horarioAtual = LocalTime.now();

        if (horarioAtual>abertura && horarioAtual<fechamento) {
            ...
        }
    }

    public void depositar(double umValor, ContaBancaria umaConta) {
        // TODO Auto-generated method stub

    }

}

No qual estou mandando um três parâmetros para outra classe chamada CorrespondenteBancario.
Answer: A classe java.time.LocalTime possui os métodos isBefore e isAfter para você comparar, respectivamente, se um horário ocorre antes e depois de outro.
Ou seja, em vez de fazer t1 > t2, você faz t1.isAfter(t2), e em vez de usar t1 < t2, usa-se t1.isBefore(t2):
public CorrespondenteBancario(DayOfWeek diasDeFuncionamento[], LocalTime abertura, LocalTime fechamento) {
    LocalTime horarioAtual = LocalTime.now();
    if (horarioAtual.isAfter(abertura) && horarioAtual.isBefore(fechamento)) {
        ...
    }
}

Algumas linguagens permitem que se use operadores como > e < com instâncias de várias classes, mas não é o caso do Java.

Atenção, se quiser fazer a comparação >=, a lógica é um pouco diferente. Nesse caso ficaria:
if (! horarioAtual.isBefore(abertura) && ! horarioAtual.isAfter(fechamento)) {
    ...
}

Agora eu usei ! isBefore (não é antes), o que significa que o horário pode ser depois, ou pode ser o mesmo horário (ou seja, maior ou igual). Não basta usar isAfter porque ele não verifica o caso em que são iguais. Uma lógica similar foi usada para <=, que se torna ! isAfter.

Uma outra alternativa é usar compareTo, que retorna um valor negativo se o horário é menor que outro, zero caso sejam iguais, ou um valor positivo se o horário é maior que outro:
if (horarioAtual.compareTo(abertura) > 0 && horarioAtual.compareTo(fechamento) < 0) {
    ...
}

Mas nesse caso eu prefiro usar isBefore e isAfter, pois na minha opinião deixa o código mais claro e fácil de ler e entender (a única "vantagem" seria que fica mais fácil mudar o código acima para >= e <=).
Answer: Utilize o CompareTo. Como no exemplo:
brightness_4
// Java program to demonstrate
// LocalTime.compareTo() method
import java.time.*;
public class GFG {
    public static void main(String[] args)
    {

        // create a LocalTime Objects
        LocalTime time1
            = LocalTime.parse("17:52:49");
        LocalTime time2
            = LocalTime.parse("13:08:00");

        // apply compareTo()
        int value = time1.compareTo(time2);

        // print LocalDateTime
        System.out.println("Int Value:" + value);

        if (value > 0)
            System.out.println("LocalTime1 is greater");
        else if (value == 0)
            System.out.println("LocalTime1 is equal to"
                               + " LocalTime2");
        else
            System.out.println("LocalTime2 is greater");
    }
}

Como comparar instâncias de LocalTime?


Using SVD to express the normalized norm of the output of a linear map

Question: This is probably trivial, but it's been quite some time since my Linear Algebra exam, and my SVD skills are rusty.
1) Let $T$ be a linear map from $\mathbb{R}^n$ to $\mathbb{R}^n$, and $M$ the associated square matrix in the canonical basis.
$$\forall x\in \mathbb{R}^n,\ T(x)=Mx=U\Sigma Vx$$
I want to express
$$\frac{||Mx||}{||x||}$$
in terms of the singular values of $M$ ($||x||\neq0$ obviously). In a presentation, I read that
$$\frac{||Mx||}{||x||}=\sqrt{\frac{\sum_i\sigma_i^2}{\sum_ix_i^2}}$$
where the $\sigma_i$ are the singular values of $M$. This is clearly wrong (e.g., consider an isotropic $M$). What's the correct expression? I would really like to see the passages of the proof, so that next time I can derive the correct expression myself.
2) If $T$ is from $\mathbb{R}^m$ to $\mathbb{R}^n$, i.e., $M$ is not square, is it still possible to express $\frac{||Mx||}{||x||}$ in terms of the singular values of $M$?
Answer: Let $\{\sigma_1,\dots,\sigma_r\}$ be the nonzero singular values of $M$ (where $r$ is the rank of $M$). As you pointed out (assuming the matrix $M$ has real entries) there exists an $m\times m$ orthogonal matrix $U$, an $n\times n$ orthogonal matrix $V$, and a diagonal $m\times n$ matrix $\Sigma$ (whose nonzero diagonal entries are the singular values $\sigma_1,\dots,\sigma_r$) such that
$$
M=U\Sigma V.
$$
Let $\{v_1,\dots,v_m\}$ denote the rows of $V$ and $\{u_1,\dots,u_n\}$  the columns of $V$ (both of which are orthonormal bases). In particular, it holds that $v_i^Tv_j = 0 $ for indices $i\neq j$ and $v_i^Tv_i=1$ for all $i$. (An analogous statement holds for the vectors $u_i$.)
We can expand $x$ in the basis $\{v_1,\dots,v_m\}$  as
$$
x= x_1v_1+\cdots+x_nv_n
$$
where $x_1,\dots,x_n\in\mathbb{R}$ are the coefficients of the vector $x$ in this basis such that
$$
\lVert x\rVert = \sqrt{\sum_{i=1}^n x_i^2}.
$$
Multiplying out, we find that $Mx$ expanded out in the $\{u_1,\dots,u_m\}$ basis is
$$
Mx = \sigma_1 x_1 u_1 + \cdots + \sigma_r x_r u_r.
$$
such that $\lVert Mx\rVert^2 = \sigma_1^2 x_1^2+\cdots+ \sigma_r^2 x_r^2$. I don't think you can really say much else.
To address your second question, note that
$$
\sup_{x\neq 0} \frac{\lVert Mx\rVert}{\lVert x\rVert} = \sigma_1,
$$
which is the largest singular value. Indeed, assuming $\sigma_1\geq \sigma_i$ for all other $i\in\{2,\dots,r\}$, we see that
$$
\lVert Mx\rVert =\sqrt{ \sum_{i=1}^r \sigma_i^2 x_i^2} \leq \sigma_1\sqrt{\sum_{i=1}^n x_i^2}  = \sigma_1 \lVert x\rVert,
$$
with equality if and only if $x$ is parallel to $v_1$ (i.e. $x_i=0$ for all $i\in\{2,\dots,n\}$).

We can write $U$ and $V$ as
$$
U = \sum_{i=1}^m u_ie_i^T\qquad\text{and }\qquad V = \sum_{i=1}^n e_iv_i^T,
$$
where the $e_i$'s are the "standard" basis vectors (i.e., with zeros everywhere except a 1 in the $i$th position), and $\Sigma$ as
$$
\Sigma = \sum_{i=1}^r \sigma_i \, e_ie_i^T.
$$
It follows that $Vv_i = e_i$ and $Ue_i = u_i$ for all $i$. Moreover, $\Sigma e_i = \sigma_i e_i$. Thus
$$
Mv_i = U\Sigma Vv_i = U\Sigma e_i = \sigma_i Ue_i = \sigma_i u_i.
$$
Comment: I've edited my answer to more fully explain.
Comment: To say that $Mv_i = \sigma_iu_i$ is essentially the definition of the singular value decomposition! I've added more detail to hopefully explain.
Comment: Hmmm. A bit too terse for me: 1) how do you go from $x= x_1v_1+\cdots+x_nv_n$ to
 $\lVert Mx\rVert^2 = \sigma_1^2 x_1^2+\cdots+ \sigma_r^2 x_r^2$? 2) regarding the second statement, is this correct? $\frac{\lVert Mx\rVert}{\lVert x\rVert} \leq \sqrt{\frac{\Sigma_{i=1}^r\sigma_i^2 x_i^2}{\Sigma_{i=1}^n x_i^2}} \leq \sigma_1\sqrt{\frac{\Sigma_{i=1}^r x_i^2}{\Sigma_{i=1}^n x_i^2}}\leq \sigma_1$, with equality when $x$ is parallel to $v_1$. Right?
Comment: Apologies, I probably wasn't clear enough in my comment, and/or my brain is in weekend mode. I already knew the parts you added: what I still don't see is why $x= x_1v_1+\cdots+x_nv_n \implies Mx = \sigma_1 x_1 u_1 + \cdots + \sigma_r x_r u_r$. Let's make things simpler: can you just show that, say, $Mv_1=\sigma_1u_1$? If you can show me this, then $Mx = \sigma_1 x_1 u_1 + \cdots + \sigma_r x_r u_r$ trivially follows from the definition of basis and the linearity of $T$.


Sequence of independent random variables with same expected value such that the weak law doesn't hold

Question: I'm looking for a specific counterexample for the weak law of large numbers. That is, I want a sequence of random variables with same finite expected value $\mu$. These random variables must each have finite variance $\sigma_i^2$.
I guess that the $\sigma_i^2$ should be unbounded for this to work. Is there a known counterexample for this?
I'd also appreciate a book reference for me to learn a bit more!
Answer: Let $X_0, X_1, X_2, \dots$ be independent with $X_n = \pm 4^n$ each with probability $1/2$.  Then $E[X_n] = \mu = 0$ for all $n$.  Letting $S_k = X_0 + \dots + X_k$, we have
$$|S_{k-1}| \le \sum_{n=0}^{k-1} 4^n = \frac{1}{3} (4^k - 1)$$
so $$|S_k| \ge ||X_k| - |S_{k-1}|| \ge 4^k - \frac{1}{3} (4^k - 1) \ge \frac{2}{3} 4^k.$$
In particular, $|S_k/k| \to \infty$ almost surely.


How to embed a pdf into a html page for android browsers

Question: So,
At the moment I embed a base64 encoded pdf into a html page using iframe and I have no problem with this but I want to display it also on android browsers like chrome and firefox.
I also tried object or embed tag but none worked.
What should I do ?
Answer: You should try Viewer.JS or PDF.JS. If none of those work, you could possibly use Google Docs Viewer. This site will help you generate the URL for that : iTools.com. I prefer Google Docs currently because the performance is a little sluggish using both of those Javascript viewers. Keep in mind that in order for the Google Docs Viewer to work, you must have the file published to the web and accessible for Google's servers.
Another option would be to use a conversion library (such as imageMagick) to turn the PDF into an image and then offer a link to the full file. If your html is going to be viewed by other devices such as desktops, you could always check to see if Adobe Reader is installed and then, if not, offer an image instead with a link to the file. I use PluginDetect to check for support for PDFs.
There are other commercial options like iSSUU or FlexPaper but I don't have any experience with those. iSSUU is a software service that allows embedding viewers on your website and FlexPaper is a software that you buy and install to your website.
This is assuming you're trying to embed a PDF to a website. :/


Como mostrar todos os valores de três matrizes em uma única mensagem sem usar os índices

Question: package AlgoritmosII;

import javax.swing.*;

public class Trabalho1 {

    public static void main(String[] args){
        String[][] A = new String[3][3];
        int[][] B = new int[3][3];
        double[][] C = new double[3][3];
        double[] Ordenar_C = new double[9];
        double recebimento, pagamento, maior_saldo=0, aux;
        int flag=0, numero, i, j, n1=0, n2=0, Control, k=0, troca, fim;
        A[0][0]= "Tibúrcio";
        A[0][1]= "Ricardo";
        A[0][2]= "João";
        A[1][0]= "Felisbino";
        A[1][1]= "Seu Zé";
        A[1][2]= "Dona Maria";
        A[2][0]= "Gedonstrôncio";
        A[2][1]= "Batman";
        A[2][2]= "Homem de Ferro";
        B[0][0]= 111;
        B[0][1]= 222;
        B[0][2]= 333;
        B[1][0]= 444;
        B[1][1]= 555;
        B[1][2]= 666;
        B[2][0]= 777;
        B[2][1]= 888;
        B[2][2]= 999;
        C[0][0]= 0.0;
        C[0][1]= 0.0;
        C[0][2]= 0.0;
        C[1][0]= 0.0;
        C[1][1]= 0.0;
        C[1][2]= 0.0;
        C[2][0]= 0.0;
        C[2][1]= 0.0;
        C[2][2]= 0.0;
        while(flag==0) {
            Control = Integer.parseInt(JOptionPane.showInputDialog(" 1- Inserir Recebimento \n 2- Inserir Pagamento \n 3- Mostrar informações \n 4- Correntista mais rico \n 5- Saldos em ordem crescente \n 6- Sair"));
            switch (Control) {
                case 1:
                    numero = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero da conta para Inserir o Recebimento: "));
                    recebimento = Double.parseDouble(JOptionPane.showInputDialog("Digite o valor do Recebimento: "));
                    for (i=0;i<3;i++) {
                        for (j=0;j<3;j++) {
                            if (numero == B[i][j]) {
                                n1 = i;
                                n2 = j;
                                C[n1][n2] = C[n1][n2] + recebimento;
                            }
                        }
                    }
                    JOptionPane.showMessageDialog(null, A[n1][n2]+" seu saldo atual é de: "+C[n1][n2]);
                    break;
                case 2:
                    numero = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero da conta para Retirar o Pagamento: "));
                    pagamento = Integer.parseInt(JOptionPane.showInputDialog("Digite o valor do Pagamento: "));
                    for (i=0;i<3;i++) {
                        for (j=0;j<3;j++) {
                            if (numero == B[i][j]) {
                                n1 = i;
                                n2 = j;
                                C[n1][n2] = C[n1][n2] - pagamento;
                            }
                        }
                    }
                    JOptionPane.showMessageDialog(null, A[n1][n2]+" seu saldo atual é de: "+C[n1][n2]);
                    break;
                case 3:
                    //3–Mostre em apenas uma mensagem todos os Números de Conta, Correntistas e Saldos respectivos.
                    break;
                case 4:
                    for (i=0;i<3;i++){
                        for (j=0;j<3;j++){
                            if (maior_saldo < C[i][j]){
                                maior_saldo = C[i][j];
                                n1 = i;
                                n2 = j;
                            }
                        }
                    }
                    JOptionPane.showMessageDialog(null,"O Correntista mais rico é:\n Correntista: "+A[n1][n2]+"\n Número da conta:  "+B[n1][n2]+"\n Saldo: "+C[n1][n2]);
                    break;
                case 5:
                    for (i=0;i<3;i++){
                        for (j=0;j<3;j++){
                            Ordenar_C[k] = C[i][j];
                            k++;
                        }
                    }
                    troca = 0;
                    fim = 9-1;
                    while(troca==0){
                        troca=1;
                        for (k=0;k<fim;k++){
                            if (Ordenar_C[k] > Ordenar_C[k+1]){
                                aux = Ordenar_C[k];
                                Ordenar_C[k] = Ordenar_C[k+1];
                                Ordenar_C[k+1] = aux;
                                troca=0;
                            }
                        }
                        fim = fim-1;
                    }
                    for (k=0;k<9;k++){
                        JOptionPane.showMessageDialog(null,"Os saldos ordenados em forma crescente ("+k+"): \n"+Ordenar_C[k]);
                    }
                    break;
                case 6:
                    flag=1;
                    break;
                default:
                    JOptionPane.showMessageDialog(null, "Algo de errado não esta certo ;3");
            }
        }
    }
}

Meu problema é o case 3: "Mostre em apenas uma mensagem todos os Números de Conta, Correntistas e Saldos respectivos". Meu professor me disse:

-"Use concatenação de texto em uma variável. Depois só um showmessage".
-"Dica: for para concatenar texto depois um showmessage".

Eu realmente ainda não compreendi como eu poderia fazer isso mas se possível eu gostaria de colocar:
Nome: +A
Numero da conta: +B
Saldo: +C
Mas tendo de utilizar apenas uma mensagem para isso me confundiu um pouco, e eu gostaria de saber o que eu poderia fazer para mostrar essas informações, sem usar os índices (ex: Nome: + A[0][0], Numero Conta: + B[0][0], Saldo: + C[0][0]).
Comment: Porque tem que ser feito sem usar os índices?
Comment: Pois se eu utilizasse matrizes maiores ainda poderia utilizar esse código.
Answer: Eu diria que o professor já deu todas as dicas necessárias:

"Use concatenação de texto em uma variável. Depois só um showmessage".
"Dica: for para concatenar texto depois um showmessage".

Então primeiro você cria uma variável que vai ter a mensagem. Depois, use dois laços for para percorrer as "matrizes" (na verdade são arrays de arrays, mas enfim), e vá concatenando os respectivos valores nessa variável. Como são várias concatenações de String, eu sugiro usar um StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A[i].length; j++) {
        sb.append(A[i][j]).append(" ").append(B[i][j]).append(" ").append(C[i][j]).append("\n");
    }
}
String mensagem = sb.toString();

E pronto, no final a variável mensagem terá todos os dados concatenados. Eu coloquei um espaço separando o nome, número da conta e saldo, e coloquei uma quebra de linha no final (o \n). A mensagem ficou assim:
Tibúrcio 111 0.0
Ricardo 222 0.0
João 333 0.0
Felisbino 444 0.0
Seu Zé 555 0.0
Dona Maria 666 0.0
Gedonstrôncio 777 0.0
Batman 888 0.0
Homem de Ferro 999 0.0

Você pode mudar a mensagem do jeito que quiser (como colocar uma vírgula separando os dados, ou qualquer outro formato que desejar). E uma vez tendo a mensagem, basta mostrá-la com JOptionPane.showMessageDialog (ou o que quer que você esteja usando para exibir as mensagens).
Vale dizer que não tem como fugir de usar os índices, pois você quer concatenar A[i][j] com B[i][j] com C[i][j]. Sem saber os valores de i e j, não tem como saber quais dados serão concatenados na ordem correta.

Claro que você também poderia fazer sem um StringBuilder, criando a String e concatenando diretamente nela:
String mensagem = "";
for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A[i].length; j++) {
        mensagem += A[i][j] + " " + B[i][j] + " " + C[i][j] + "\n";
    }
}

Mas ao fazer concatenações em um loop, é mais eficiente usar um StringBuilder, conforme explicado aqui.

Esse código assume que A, B e C possuem a mesma quantidade de elementos (tanto que eu uso A.length - o tamanho do array A - sem verificar se B e C têm esse mesmo tamanho). Se a quantidade for diferente, teria que verificar antes se os tamanhos são iguais e tratá-los de acordo (não parece ser o caso do exercício), para que não ocorra o erro de index out of bound.
Por fim, sugiro usar as convenções de código do Java e usar nomes de variáveis que começam com letras minúsculas. E procure dar nomes mais significativos também (por exemplo: em vez de A, B e C, poderia ser nomes, contas e saldos). Pode parecer um detalhe bobo, mas nomes melhores ajudam na hora de programar.


JQuery onkeypress ENTER

Question: Eu tenho uma tabela que quando da double click em um dos seu campos ele vira um input e este input, quando pressiono enter, volta a ser um campo da tabela, porem as vezes não funciona de imediato, eu tenho que clicar no input e então apertar enter. Eu gostaria que eu pudesse clicar na celula da tabela, ela virar um input, eu alterar a informação, dar enter e ja era.
Meu codigo JS:
function updateFabricante(op) {
    let fabricante = $(`#fabricante${op}`).text() || $(`#fabricante`).val()

    $(`#fabricante${op}`).dblclick(function(){
        $(this).html(`<input type="text" required name="fabricante" id="fabricante" value="${fabricante}">`);
        $(`#fabricante`).focus();
    });

    $(`#fabricante`).on('keypress',function(e) {
        if(e.which === 13) {
            let fabricante = $(`#fabricante`).val();
            $(`#fabricante${op}`).html(fabricante);
            return false;
        }
    });
}

(Explicação para agilizar)
Onde
op: Especifica qual celula estou selecionando, são varias, de 0 à n
fabricante${op}: ID do campo que selecionei
fabricante: ID do input
Comment: Só para adiantar, está incorreto colocar os manipuladores de eventos dentro da função (pelo menos nesse caso). Isso porque se vc chamar mais de uma vez a função com o mesmo `op`, irá multiplicar os manipuladores, podendo ocasionar comportamento inesperado, o que parece ser o caso.
Comment: Como é que vc está chamando a função `updateFabricante` para ativar o double click?
Comment: Sim, eu notei que estava errado agora.
Answer: Eu criei uma tabela para exemplificar o código JQuery que adaptei. Acredito que funciona para o seu caso restando apenas alterar o seletor para o seu cenário.

/* Usamos $(document).ready(...) ou $(...) para garantir que todas as
 * instruções escritas sejam aplicadas após todos os elementos
 * do DOM (HTML) estiverem prontos para serem manipulados.
 */
$(function() {
/* Adicionando o evento de double click em todos os elementos td
 * que são filhos de qualquer elemento table.
 */
$('table td').dblclick(updateText); //Atribuindo a função updateText ao evento

/* Adicionando o evento de keypress nos elementos que tenham
 * a classe fabricante e que sejam filhos de qualquer elemento table.
 */
$('table').on('keypress', '.fabricante', function(e) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    const fabricante = $(this).val();
    $(this).replaceWith('' + fabricante + '	'); //Trocando o elemento atual (input) por um elemento td
    $('table td').dblclick(updateText); //Adicionando o evento de double click no novo elemento td criado
  }
});

function updateText() {
  $(this).off("dblclick"); //Desabilitando o evento de double click no elemento input
  const text = $(this).text();
  $(this).replaceWith('<input type="text" required name="fabricante" class="fabricante" value="' + text + '">');
  $('.fabricante').focus();
};
});

      Nome
      Idade

      Flávio
      42

      João
      15

Comment: Você pode me explicar como esse codigo funciona, por favor? Eu não trabalhei muito com javascript nem jquery
Comment: Esta acontecendo algo engraçado comigo agora. Eu tentei utilizar seu cogido, mas não sei porque ele não funciona quadno coloco no seletor "td". Eu teste com "th" e foi, até com a table inteira ele funciona, mas se eu colocar "td" neste aqui "$('table td').dblclick(updateText);" ele não faz nada. É por isso que gostaria que me explicasse.
Comment: Eu comentei o meu código, note que para adicionar o evento de double click nos elementos eu utilizei o seletor para buscar elementos HTML (`table` e `td`). Você pode alterar para ids ou classes se ficar mais fácil. Se ainda não conseguiu entender muito bem, podemos iniciar um chat que te ajudo.
Comment: Ta certo, entendi sim. Não sei exatamente o que estava acontecendo, mas resolvi colocando tudo na função documento ready do jquery. Muito obrigado!
Comment: Essa função serve para aplicar o código javascript que estiver dentro dela logo após todo os elementos do DOM estarem disponíveis para uso.

JQuery onkeypress ENTER


How do I pull in a group of term descriptions instead of their names?

Question: I am using a taxonomy to categorize content of type "lesson plan" by subject. Each lesson plan can belong to multiple subjects.
In a view where I display these lesson plans, I would like to have a field that lists all of the term's descriptions, rather than their names.
I followed these steps to pull in Taxonomy term: Term description instead of Content: Subject (where Subject is the name of the vocabulary) in the view.
However, in the Rewrite Results area, [description] only pulls in the first term's description, instead of all of them.
How do I get all of them?
Comment: Why do you need all of them in a single row? By adding a relationship to the taxonomy term your view should now have x rows, where x is the number of values for the field. Each of those rows has its own term description which gets printed separately...unless I've misunderstood something?
Comment: Ok yeah I misunderstood, thought this was a single content page but of course it's a list. What format are you trying to display the content in? Is it  a heading (content title maybe) followed by a list of term descriptions?
Comment: Currently it's in a special box below the heading. The term names are 1, 2, 3, etc. (representing 1st, 2nd, 3rd grade) and the descriptions are 1st, 2nd, and 3rd, respectively. I want the comma separated list of terms to say: "1st, 2nd, 3rd" rather than "1, 2, 3"
Comment: Aggregation is usually the way to sort that out but it can be a headache. If you're happy writing a custom module to solve it I can put some sample code for a (potentially) simpler solution in as an answer
Comment: Thank you! My boss is somewhat (not deal-breaking my but still) averse to custom modules -- can you tell me more about aggregation?
Comment: I don't know how to get it working for your exact use case off the top of my head, sorry. I usually wind up writing code for this sort of thing as it takes 5 minutes as opposed to several hours of wrangling with the Views UI, which usually ends in swearing and writing the code anyway. If your boss has any sense he'll listen to you when you tell him it's much more efficient to copy/paste/test 10 lines of code than it is to go in the other direction :) Incidentally the View will perform better without the extra relationship as well, if they need more convincing
Answer: One quick way to solve it with code would be to add a custom field formatter:
function MYMODULE_field_formatter_info() {
  return [
    'taxonomy_term_csv_descriptions' => [
      'label' => t('Taxonomy term CSV descriptions'),
      'field types' => ['taxonomy_term_reference'],
    ],
  ];
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];

  if ($display['type'] == 'taxonomy_term_csv_descriptions') {
    $descriptions = [];

    foreach ($items as $item) {
      $descriptions[] = check_markup($item['taxonomy_term']->description, $item['taxonomy_term']->format);
    }

    $element[0] = ['#markup' => implode(', ', $descriptions)];
  }

  return $element;
}

That will give you a new formatter to use for taxonomy term reference fields in Views or the Manage Display pages for content types.
If you go with this solution you can remove the relationship to the Taxonomy Term from your View.


How to display an image on two devices?

Question: I want to implement a kind of feature like copying an image file from one device to another. During the image transferring, I need to update the UI simultaneously on both side. For example, the image flies out of the device A, and then flies into the device B. On the user's side, he/she just see that image moves from one screen to another screen, then the transfer is completed.
One possible way I'm thinking so far is to display an animation during the image transferring. But I don't know how to display an image partially on screen A, and partially on screen B. Hope someone could give me some hints. Thanks a lot.
Answer: The trick is to find the time difference between the two devices.
I wrote an app that performed synchronized playback of an audio file on multiple devices.  To synchronize the devices, I had them ping a time server and make note of how much the device's clock differed from the server's clock.  With this offset value, I was able to do a reasonably good job of synchronizing the playback.  I'm glossing over a lot of the details (latency, variability, leap second, etc.), but this was the basic idea.
To synchronize the UI on both devices, the two devices need to know the difference between each other's clock.  Once you have this value, you simply time the animation appropriately.  I've only ever done it with a server, but if the two devices are talking to each other for the file transfer, perhaps you could have one device ask the other for its time and compute the offset.
Tip: compute the difference several times, then use standard deviation to select a good value.  If you want to really study how this is done, check out how NTP does it: http://en.wikipedia.org/wiki/Network_Time_Protocol
Comment: Thanks for the idea. I think this is a kind of solution if the animation is same on both sides. But what I'm thinking is a little bit different than that. I hope to use the image which is being transferred to draw the animation. For example, if the image has 20% transferred, I hope to draw 80% on device A, and 20% on device B. So the whole action just looks like that image flies from A to B. I wonder is this possible? Or what kinds of techniques would be involved?
Comment: Any synchronized action between the devices requires, well, synchronization.  If you find a way to do your animation that doesn't require synchronization, please post it.  I'd be curious to hear how you solve the problem.

How to display an image on two devices?


Confusion with dynamics

Question: I'm not sure if anyone's asked these before on here but I'm trying sort some dynamics out on my composing project and I have some questions:
1) What I want to do is have a diminuendo from ff to p across 4 bars; do I use 4 separate diminuendos or just 1 across the 4 bars?
2)After the part mentioned in the previous question I want to have a sudden sfz on both hands (I'm using a piano btw) so do I put one sfz between the 2 staffs or a sfz for each?
3)After the sfz, I want to go back to p and crescendo across another 4 bars back into ff so do I put a p after the sfz and then after the crescendo (or crescendos depending on the answer to the first question) do I put ff?
PS: I'd ask my music teacher but I'd probably forget the questions by Monday
Comment: P.S. - show your music teacher this post on Monday!
Answer: 1) You shouldn't use multiple decrescendos so use just the one, but if that looks awkward because 4 measures is wide use staff text decresc. after the fortisimo.
2) Sforzando is an accent, not a dynamic mark, so put it on both hands' notes.
3) Yes do this. Consider using staff text cresc. instead of a 4 measure crescendo.
Comment: I've never seen two sfz markings in the same place (i.e. measure and beat) in a piano score: it's **always** been one sfz marking between staves.
Comment: @Dekkadeci It happens occasionally when the voices are doing something very different (so it wouldn't be obvious that the sfz goes for both hands).
Comment: Helpful, maybe.  But incorrect regarding the sfz I'm afraid.
Answer: One of everything, between the staves. (waffle to reach 30 characters)

Confusion with dynamics


Tab widget in android from portrait to landscape

Question: Is there any way in order to make a single layout for tab widjets and when changing orientation from portrait to lanscape single layout is called.
Which properties and how the properties are changed.
Answer: Just create the layout and android will do the rest is the simple answer.  See the Tab Widget Layout tutorial on the on the Android developers site for a code example.  It handles correctly with both portrait and landscape orientations.


Populational model with parameter

Question: In preparation of my math exam I was trying to solve some exercises about population models.
The question is as follows:

Consider a population model with two species $X$ and $Y$. The populational growth of $X$ after $k$ years is indicated by $x_k$ and for $Y$ this is $y_k$. Let's assume that these populations evolve according to the following equations
$$
x_{k+1} = \frac{1}{4}(x_k + 2ay_k)
$$
$$and$$
$$
y_{k+1} = \frac{1}{8}(2y_k + ax_k)
$$
where $a>1$ is a constant.

(a) Write these equations in matrix-vector form and calculate the characteristic polynomial and the eigenvalues of the occuring matrix (as functions of $a$).
(b) For what values of $a$ is the growth exponential? For what values does the population go extinct?
(c) For what value of $a$ is the population in equilibrum? Calculate the equilibrum population if $x_0=300$ and $y_0 = 100$.

Question a is relatively easy
Matrix-vector form is:
$$\begin{pmatrix} x_{k+1}\\ y_{k+1} \end{pmatrix} = \begin{pmatrix} \frac{1}{4}&\frac{a}{2}\\ \frac{a}{8}&\frac{1}{4} \end{pmatrix}\begin{pmatrix} x_{k}\\ y_{k} \end{pmatrix}$$
Eigenvalues are:$\frac{1}{4} \pm \frac{a}{4}$
Now I'm stuck with questions b and c. An explanation on how to solve these would be very much appreciated!
(P.S. I translated this question from Dutch to English so excuse my 'rough' translation and/or spelling/vocabulary errors)
Answer: I'm not going to give you a full answer but I'll give you the steps to get to it.
You've found the eigenvalues. Now find the eigenvectors then build a matrix $U$ made of those eigenvectors (say, as columns, that is, each column of $U$ is one of the eigenvectors).
Once you have this matrix $U$, you can uncouple the equations, that is, you will be able to define new population variables $x'$ and $y'$ such that the time-evolution of $x'$ depends only on $x'$ and the time-evolution of $y'$ depends only on $y'$. Hint: $x = Ux'$.
This will let you solve for the time-evolution of both $x'$ and $y'$ in terms of $a$ and $k$. How? By replacing $x$ and $y$ in the original matrix equation with $x = Ux'$ and $y = \ldots$. ($y$ is for you to figure out).
You can then go back to the original population variables $x$ and $y$, which will each be a linear superposition of both $x'$ and $y'$. How? Well, if $x = Ux'$ and you have $x'$, then...
Since you'll have solved for the time-evolution of $x'$ and $y'$, you'll have a complete solution to both $x$ and $y$. Then it's a matter of looking at what happens to them for various values of $a$, as $k$ increases.

Populational model with parameter


A search feature for fields?

Question: I've looked at the core search module, and from what I've been able to tell so far, it searches on the body of a node.
What's the best way to get a search feature for a site that will search on specified fields of a content type?
Answer: You can use Views module http://drupal.org/project/views.
With Views module, you will have a flexible method to pull content according fields of your content that you want to show, and with Exposed Filters feature of Views module (or with modules like Better Exposed Filters), you can search/refine by field of your content.
here is a documentation about Views: http://drupal.org/documentation/modules/views
here is an example: I want to filter and search by Title of my content. Then I can add to my View a filter to search by Title, then in Filter Criteria I can select Title and expose that filter to use, for example, a text field for search Titles:
this screen shot is about where is located the Filter Criteria area, and where is the option to add filters:

this screenshot is about where you can select if you want expose a text box to search/filter, in this example, by Title. The operator is very important to filter. In this case I will select Contains that seek a word that is part of title:

Also remember that you can add another filter, the filter by content type, to filter results by list of content type desired. This filter can be not exposed, or if you want, can be exposed to allow to users filter and search, according content types:

And finaly this screenshot have the View with a text field for filter and search by titles of my content:

I hope information be useful.
Answer: For Drupal 7 try the Finder module.

A search feature for fields?


Model selection in a paper: what to say about the dropped variables?

Question: I have a question (simpler than my previous post today I hope!), which is probably very stupid as nobody has never asked it before.
Lets say I am trying to explain the effect of 3 variables (A, B and C) on a dependent one (Y). Biologically speaking, A and B should really have an effect on Y. So I am testing:
Y ~ A + B + C
But when I use a model selection method (whatever the method is), the 'best' model, the one that fits the data the best, drops A. So I end up with:
Y ~ B + C
What can I say about A then?
Can I cite something to justify the dropping (the F statistics, something about the AIC/BIC, etc)?
OR
If I need to show that A has no effect, do I need to use the full model anyway?
Comment: Don't confuse dropping a variable with having no effect, Joe! For example, let y ~ a+d+e, b=a/2+2d+e/2, c=a/2-d+e/2, with d, e, (and the implicit error) all small compared to the variation in a.  Then a may have a profound effect on y, but (due to its association with b and c) is unnecessary in the model (and won't even be significant in the full model y ~ a+b+c); the best model would be y ~ b+c (because this equals a+d+e).
Comment: Thanks. And I agree for the tl;dr thing, but I like to be clear, and thats also a very specific case, so I had to fully describe it. Thats the complexity of that dataset that makes it challenging to analyze.
Comment: @whuber That's very well-put.  Why not make it an answer?
Comment: AIC, BIC, DIC, Likelihood Ratio, cross-validation, etc... are tools that you can use depending on the features of the model you are interested on. If they indicate that A can be dropped, then you could use the [Occam's razor](http://en.wikipedia.org/wiki/Occam%27s_razor) to defend the model $B+C$. The other post is interestig, but a bit long. Shorter questions seem to be more successful, you know, the popular [TL;DR](http://en.wikipedia.org/wiki/Wikipedia:Too_long;_didn%27t_read).
Comment: And for your answer here: it's not really my question though=> I want to know what to say about the dropped variable. I need a way to prove that it had no effect.
Comment: You wouldn't show A has *no* effect, unless the coefficient is exactly 0, which won't happen except in some very odd cases. You may show the estimated effect is small.
Comment: Thanks to all of you guys! I can know go on with my stats and finally write that paper :)
Comment: Thanks @Matt, but my comment wasn't a real answer, although it may have shed some light on the subtleties involved.
Answer: It depends on your aim.  Since A "really should" have an effect on Y but appears not to, I would definitely include the full model.  As Procrastinator suggests, model selection might be useful to propose a parsimonious new model - if that's your objective.  But if your objective is to estimate the relationships between your predictors and Y, then I don't think you need a model selection step at all - just present your full model results.
Comment: Ok thanks. I guess I got confused about the role of model selection, which is probably not appropriate in that case. I just thought that 'fitting the data better' was better, but actually it's not here!


O que é e para que serve um Bloom Filter?

Question: Estava lendo uma resposta aqui no SOpt (sim, é jocoso) e vi sobre Bloom Filter, queria mais informações sobre ele. Além do que é e para que serve, onde posso usar na prática?
Comment: Já leste esse https://www.ic.unicamp.br/~francesquini/mc202/files/aula26.pdf
Comment: @LeoCaracciolo sim.
Comment: eu tinha imaginado que sim :-)
Comment: até eu fiquei na curiosidade e fui procurar a respeito. o link https://www.psafe.com/blog/o-que-e-bloom-filter/ parece tirar 99% das duvidas sobre bloom filter de forma bem didatica. da uma olhada la
Comment: pois é cara, eu fui em busca do assunto também. Inicialmente não faz sentido nenhum ter uma estrutura que usa um hash probabilístico impreciso e com perda de desempenho no aumento do hash. Só fazendo o estudo assintético para ver se gera benefício em hashes pequenos. Ou isto, ou auxilia aplicações específicas que precisam eliminar os falsos negativos a qualquer custo. É de se pensar.
Comment: è uma filtragem de dados por eliminação onde a prioridade é descartar negativos
Answer: Bloom filter é uma estrutura de dados criada em 1970 por Burton Howard Bloom (daí o nome bloom filter)
Ele é uma estrutura probabilística com as seguintes propriedades:

Possui eficiência de espaço

Permite falsos-positivos

Não permite falsos-negativos

Elementos podem ser adicionados ao filtro

Uma vez adicionados no filtro, elementos não podem ser removidos

Quanto mais itens dentro do filtro, maior a chance de haver falsos-positivos

São baseados em:

Funções de hash
Bit fields

Para um bom funcionamento são essenciais:

Diversas funções de hash
Espalhamento uniforme

Exemplo de aplicação pratica:
O seu browser verifica todos os endereços que você acessa
para determinar se é um endereço seguro e poder te dar
um aviso caso não seja.

Há bilhões de endereços na Internet.
Podemos supor com uma boa margem de segurança que
dentre eles há alguns milhões de sites fraudulentos.
Seria ineficiente fazer com que todos os computadores do
mundo fizessem download de uma lista completa de sites
fraudulentos.
Também não seria muito eficiente checar um banco de
dados central a cada endereço que fosse acessado.
O browser faz download de um filtro de Bloom contendo
todos os sites reconhecidos como inseguros
A cada endereço acessado, o browser verifica se ele está
contido no filtro.
Se a consulta ao filtro indicar que o endereço não está
contido, então com certeza o endereço não está na lista
de sites inseguros e o acesso continua normalmente.
Se o filtro indicar que está contido, então pode ser que site
esteja na lista de endereços inseguros. Neste caso o seu
browser faz uma consulta adicional a um banco de dados
na Internet (esta sim com a lista completa)
Note que caso seja um falso positivo, a única
consequência é uma demora um pouco maior para
acessar o site desejado.

Outras aplicações:

Verificação preliminar de direitos de acesso
Evitar recomendar artigos/páginas que o usuário não
gostou ou já leu
Evitar leituras no disco em bancos de dados
Verificar senhas fracas
Corretores ortográficos
Dentre outros

Fonte: https://www.ic.unicamp.br/~francesquini/mc202/files/aula26.pdf
Comment: Diga-se de passagem que esse slide citado é muito ruim... o conteúdo pode até não ser, mas é complicado ler com aquela imagem de fundo e esquema de cores. Tirando isso achei interessante o assunto... Muito boa resposta.


Relation between intersection and product of ideals

Question: Let $C$ be a smooth projective (irreducible) curve in $\mathbb{P}^n$ for some $n$. Denote by $I_C$ the ideal of $C$. Let $g \in I_C\backslash I_{C}^2$, an irreducible element. Is it true that for any positive integer $m$, $I_C^m \cap (g) \cong (g)I_C^{m-1}$?
Comment: http://mathoverflow.net/questions/198521/relation-between-intersection-and-product-of-ideals
Answer: Since you asked, here is a translation of the answer from MathOverflow so that it does not use the language of sheaves:
First, a short summary of this proof seems to be that "In this situation (a smooth integral subvariety of a smooth variety) we have a notion of $I$-valuation that is strictly additive; but the $I$-valuation of $g$ is 1, and we produce $f$ so that the valuation of $f/g$ is $m_0$, and the valuation of $f$ is strictly greater than $m_0+1$. This is a contradiction."
Careful proof (from MO): Let $m$ be the first value where the equality fails, so there exists $f \in I^m \cap (g)$ but not in $I^{m-1}(g)$.
Write $f = gh$. Note that it must be true that $h \notin I^{m-1}$, so let $m_0$ be the largest value so that $h \in I^{m_0}$ but not $I^{m_0+1}$. There are two relevant inequalities here:
$$m_0 < m-1\ \ \text{ and }\ \ m_0+2 \leq m.$$
Now we consider the associated graded ring $$\mathrm{gr}_I R = R/I \oplus I/I^2 \oplus I^2/I^3 \oplus \cdots,$$ which by the theorem from Hartshorne is isomorphic to
$$R/I[t_1, ..., t_{n-1}],$$ where the $t_i$'s are a regular sequence generating $I$. (The isomorphism sends $t_i$ to the $i$-th generator; this works because $\mathbb{P}^n$ and $C$ are smooth, in particular $\mathbb{P}^n$ is Cohen-Macaulay and $I_C$ is generated by a regular sequence.)
Look at the image of $h \in I^{m_0} / I^{m_0+1}$. This is nonzero by the choice of $h$. Likewise the image of $g \in I/I^2$ is nonzero by hypothesis.
In the graded ring, multiply them to obtain $h\cdot g \in I^{m_0+1} / I^{m_0+2}.$ Now note that $h\cdot g = f$ is actually in $I^m \subseteq I^{m_0+2}$ by the second inequality above, so the product is zero in the graded ring.
This is a contradiction because $R/I[t_1, \ldots, t_n]$ is an integral domain.
Comment: @Levinson: Thanks a lot.
Answer: Edit: This proof has an error. :-( I will leave it up for now to see if it can be fixed (comments welcome).
We have an obvious injection $I^{m-1}_C \cdot(g) \hookrightarrow I^m_C \cap (g)$, which becomes an isomorphism locally at any point $p \notin C$, since then $I_C$ localizes to $(1)$.
Now, let $p \in C$ and let $R_p$ be the local ring. Since $\mathbb{P}^n$ and $C$ are smooth, $C$ is locally a complete intersection, hence $I_C$ is generated (in $R_p$) by $n-1$ elements. By Nakayama's Lemma, your hypothesis on $g$ says that we can extend $g$ to a minimal generating set [edit: this is not true!], say $g, f_1, \ldots, f_{n-2}$. Let $J = (f_1, \ldots, f_{n-2})$.
Claim: For all $m$, $J^m \cap (g) = J^m(g)$. We will prove this in a moment.
To see that this is sufficient, write
$$I^m \cap (g) = (J+(g))^m \cap (g) = (J^m + J^{m-1}(g) + \cdots + (g)^m) \cap (g). $$
Intersection distributes over sum, and all terms but the first are already contained in $(g)$, so this is
$$ = J^m \cap (g) + (J^{m-1}(g) + \cdots + (g)^m).$$
By our claim, $J^m \cap (g) = J^m \cdot (g)$, so we can factor (g) back out:
$$ = (J^m + J^{m-1} + J^{m-2}g + \cdots + g^{m-1})\cdot (g)$$
Now $J^m \subset J^{m-1}$, so this is exactly $I^{m-1} \cdot (g)$, as desired.
Proof of claim. First, note that
$$J^m \cap (g) = J^m(g) \text{ iff  } \mathrm{Tor}^1_R(R/J^m,R/g) = 0.$$
This is explained here. There's probably more than one way to prove that this Tor vanishes in this situation, but here is one proof: we have an isomorphism
$$k[[x_0, \ldots, x_{n-1}]] \to \widehat{R},$$
where $\widehat{R}$ is the completion of $R_p$, that sends $x_0 \mapsto g$, and $x_i \mapsto f_i$ for $i=1, \ldots, n-2$, and $x_{n-1} \mapsto t$, for some choice of uniformizer $t$ for $C$ at our point $p$. (Here I am using that $C$ is smooth. I'm not sure this is strictly necessary.)
Now since $R \to \widehat{R}$ is faithfully flat, $\mathrm{Tor}^1_R(R/J^m,R/g) = 0$ if and only if $\mathrm{Tor}^1_{\widehat{R}}(\widehat{R}/J^m\widehat{R},\widehat{R}/g\widehat{R}) = 0$, if and only if $J^m \widehat{R} \cap g\widehat{R} = J^mg \widehat{R}$.
But now this last equality is obvious, since $J\widehat{R}$ is the monomial ideal $(x_2, \ldots, x_{n-2})$ and $g\widehat{R} = (x_0)$. Both $J^m \widehat{R} \cap g\widehat{R}$ and $J^mg \widehat{R}$ are generated by $\{x_0 y : y$ is a monomial of degree $m$ in $x_1, \ldots, x_{n-2}\}$.
Comment: Does it really follow that g can be extended to a regular sequence in every local ring? E.g. C the line x=y=0, g = xw-yz defining a quadric cone containing C. g is not in the square of the ideal of C, but it's not regular at the origin.
Comment: @JohnBrevik: Hmm, that's a good point -- I was thinking of the case of a maximal ideal. (I guess my proof only works under the stronger assumption $g \in I \setminus m_p I$... which seems roughly like a transversality hypothesis.) I'll have to see if I can fix the proof.
Comment: @Jana: I do not think that is correct, assuming the elements $f_i$ can be found in the first place (e.g. if $g \notin m_p I$), anyway. The element $f_i^{m-1}g$ is not zero in $R/J^m$.
Comment: (In fact the claim about Tor is true any time we make ideals out of disjoint subsets of a minimal generating set for the maximal ideal of a regular local ring.)
Comment: @Levinson: Sorry, my mistake. Will remove the comment. I misunderstood the notation.
Comment: @Jana: no worries -- plenty of mistakes to go around...
Comment: @Levinson: I posted this question on mathoverflows as well (same title) and there is a slightly different solution. Could you please have a look?
Comment: In fact, my above post has a glaring mistake as well! The cone I had in mind is x^2-yz, not xw-yz which is smooth.


how to use np.where for 3d array?

Question: I have an 3d array and i want to find an array that holds specific values (in this case [1,2,3]) and change it.
a3 = np.array([ [ [1, 2, 3], [4, 5,
6], [1, 8, 9] ], [ [1, 2, 3], [4, 5,
6], [1, 8, 9] ], [ [1, 2, 3], [4, 5,
6], [1, 8, 9] ] ])

For example, using np.where
np.where(a3 == [1,2,3], [9,9,9], [0,0,0])

#Result i want
[[[9 9 9]
[0 0 0]
[0 0 0]]

[[9 9 9]
[0 0 0]
[0 0 0]]

[[9 9 9]
[0 0 0]
[0 0 0]]]

But i would get this instead.
[[[9 9 9]
[0 0 0]
[9 0 0]]

[[9 9 9]
[0 0 0]
[9 0 0]]

[[9 9 9]
[0 0 0]
[9 0 0]]]

I assume it happens because they find each element instead of the subarray.
So how would accomplish what i want?
Answer: Try
np.where(np.all(a3 == [1, 2, 3], axis=2, keepdims=True), [9, 9, 9], [0, 0, 0])

how to use np.where for 3d array?


How to inspect outgoing email content?

Question: There are several modules that send email from my site: Rules, Trigger, User, ...
I am looking for a place to set a drupal_set_message() and print out the email contents. Where in the code would be the best place for that?
Answer: You can use hook_mail_alter() to get, or alter, the content of an e-mail message before it's sent out.
function mymodule_mail_alter(&$message) {
  dpm($message);
}

Not all modules use drupal_mail(), which means that for those modules hook_mail_alter() won't be invoked when they send an email.
In this case, you need to identify where in the module's code the mail is sent out, and see if they provide their own alter hooks. Look for any call to drupal_alter(), module_implements(), module_invoke(), or module_invoke_all().
Failing that, you may have to temporarily add the dpm() call directly to the module in the right place.

How to inspect outgoing email content?


Finding the number of elements in the intersection of two power sets.

Question: The question is:
Let the sets S and T be defined a follows:
S=x:x is a positive integer multiple of 3 less than 100
T=x: x is a positive integer multiple of 4 less than 100
If ℘ (X) represents the power set of X for any any set X, how many elements are there in ℘ (S) ∩ ℘ (T)?
Now if it asked for the intersection of S and T, then the answer would simply be {12, 24, 36, 48, 60, 72, 84, 96}. It is asking for the intersection of two power sets, and there are so many elements in the power sets of both the sets. Is there any shortcut method which can be used? Any help would be appreciated.
Comment: Hint: $P(S)\cap P(T)=P(S\cap T)$.
Comment: @AndreaMori so it would be just 2^8 (since there are 8 elements in S∩T) ?
Answer: The elements in the intersection of power set of both sets will be same as the elements in power set of intersection of both sets.(as hinted by Andrea Mori)
Hence ,answer to your question will be the number of elements in power set of {12,24,36,48,60,72,84,96} i.e 2⁸= 256.
You can verify this by taking any simpler example.
Hope it helps:)


Postgresql postman sending null value

Question: I am trying to learn postgresql with express js and currently trying to send in a test "name" value to my backend database but everytime it is sent is being stored and returned as null. Here is my current server.js which express is ran out of:
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const PORT = 5000;

//
//Middleware
//
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }))

//
//Routes
//

//Add to cart
app.post("/addCart", async(req,res) =>{
    try {
        const { description } = req.body;
        const newName = await pool.query(
            "INSERT INTO products(name) VALUES($1) RETURNING *",
            [description]
            );
        res.json(newName.rows[0]);

    } catch(err){
        console.error(err);
    }
});

app.listen(PORT, () =>{
    console.log("Express Server has started on port", {PORT});
});

and this is my postman body:
{
    "name": "testtest"
}

and this is the response being returned:
{
    "id": 9,
    "name": null
}

any help would be appreciated!
Answer: Looks like you're pulling the wrong attribute out of the request body. Try changing description to name in your code:
try {
-    const { description } = req.body;
+    const { name } = req.body;
    const newName = await pool.query(
        "INSERT INTO products(name) VALUES($1) RETURNING *",
-        [description]
+        [name]
        );
    res.json(newName.rows[0]);

Comment: Oh crap i dint realize { description } was what it pulled i just assumed it was a variable name we used, i appreciate it!

Postgresql postman sending null value


Updating of drupal core and modules impossible

Question: I have several different drupal sites (all hosted seperately). Some of them run on 7.22, and some of them run on 7.26.
For some reason the update.php script does not seem to work anymore. I can visit the page and it correctly shows the first step: Verify Requirements is shown in green and I see the Overview step. When I press the Continue button the browser starts loading and never finishes. I have tried this a dozen time, every time with the same result. I tried this on the hosted environment and on my home envirentment (installed a backup of the site).
One site is fairly small so I did a clean install of 7.26, installed all the modules, articles, etc. Same result. I am at a complete loss and now unable to install updates of drupal core and modules. Please help.
BTW 1: I use these modules in all of my sites: ctools, ckeditor, imce, lightbox2, views, metatag token.
BTW 2: nothings strange to be found in Apache error.log and php-errors.log
EDIT: Just found out that this is a known issue for IE. Tried this in Chrome and it works fine. Hope others with the same problem find this post sooner than I found the anwer
Comment: Did you try increasing the PHP memory limit? It sounds as if the server does not have enough power to process the request that comes after pressing "Continue".
Comment: I changed memory_limit from 256M to 990M but got same result
Comment: could you try drush. `Drush updb`
Answer: See https://drupal.org/node/2157815. Don't know how else to close this question...


How to prove divisibility implication.

Question: If 11|(12i+3j) and 22|j then 11|i.
This is the implication.
Focusing on 22|j. If J is divisible by 22 that means its an even number and is also divisible by 11. Can I go from 22|j to 11|(j/2)?
I dont know what I should do after this point. Should I use Transability of Divisibility or Divisibility of Integer combinations to prove.
Comment: Yes, if $22\mid j$, $11\mid j$: if $j=22 k$, then $j=11\cdot(2k)$.
Comment: @Bernard If I can confirm $11|J$ then I can conclude that $11|3j$ then I can determine that $11|12i$ this is where I am stuck again
Answer: $11\mid12i+3j$ means there exists $l$ such that $12i+3j=11l$. If furthermore $j=22k$, then
$$12i=11l-3j=11(l-6j),$$
whence $i=12i-11i=11(l-6j-i)$.

How to prove divisibility implication.


Let X be any set and let (Y, T*) be a topological space. Describe the smallest topology for X which makes f continuous.

Question: Can I take coarser topology here to describe this? I need this solution.
Comment: What is $f$ exactly?
Comment: f:X→Y is a map.
Comment: You should get a bit more specific, when asking questions here. It seems like you want to know it for a function $f: X\mapsto Y$? Still, in the future please use your Headline as a headline and describe your question properly, it makes things easier.
Comment: Ok sir. Sorry for inconvenience.
Comment: Yes, I want to know for a function f:X→Y.
Comment: Well, yes, by virtue of "coarse topology" = "small topology", it is true that the smallest topology on $X$ such that $f:X\to (Y,\tau^*)$ is continuous is the coarsest topology such that $f:X\to (Y,\tau^*)$ is continuous.
Comment: Let T be the cofinite topology on R. let I:(R, T)→(R, U) and I*:(R, U)→(R, T) be the identity mappings. Then
 show that (i) I is not continuous. (ii) I* is continuous.
Comment: U is an usual topology on R.
Comment: Can you tell me that one?
Answer: In the topological sense a function $f:X\mapsto Y$ is continuous if the preimage of every open set (i.e. every set $A\in T^*$) is open, which implies that the coarsest topology to make f a continuous function is $f^{-1}(T^*)$.
Comment: You can mark post as answering your question. Otherwise others won't be sure if you already have got your answer or if they should put in some extra effort.
Comment: Thanks sir.  I appreciate it.