(Sequelize) Cannot read property 'title' of undefined

Question: Olá, estou desenvolvendo um sistema de carrinho para ecommerce, e dentro do Model Cart, fiz um relacionamento com Model de User e o Model de Product, para que eu possa acessar os dois itens através do Cart. No entanto, ele não reconhece os campos dos outros models (Product e User). Códigos:
Product.js
const Sequelize = require('sequelize')
const Category = require('./Category.js')
const connect = require('./Database.js')

const Product = connect.define('products', {

    title: {
        type: Sequelize.STRING(120),
        allowNull: false
    },

    slug: {
        type: Sequelize.STRING,
        allowNull: false
    },

    image: {
        type: Sequelize.STRING,
        allowNull: false
    },

    price: {
        type: Sequelize.INTEGER,
        allowNull: false
    },

    body: {
        type: Sequelize.TEXT,
        allowNull: false
    }
})

Category.hasMany(Product)
Product.belongsTo(Category)

Product.sync({ force: false })

module.exports = Product

User.js
const Sequelize = require('sequelize')
const connect = require('./Database.js')

const User = connect.define('users', {

    name: {
        type: Sequelize.STRING(120),
        allowNull: false
    },

    email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true
    },

    password: {
        type: Sequelize.STRING,
        allowNull: false
    },

    cellphone: {
        type: Sequelize.STRING(15),
        allowNull: false,
        unique: true
    },

    is_staff: {
        type: Sequelize.BOOLEAN,
        defaultValue: false
    }
})

User.sync({ force: false })

module.exports = User

Cart.js
const Sequelize = require('sequelize')
const Product = require('./Product.js')
const User = require('./User.js')
const connect = require('./Database.js')

const Cart = connect.define('carts', {
    quantity: {
        type: Sequelize.INTEGER,
        allowNull: true,
        defaultValue: 1
    }

})

Cart.belongsTo(Product)
Cart.belongsTo(User)

Cart.sync({ force: true })

module.exports = Cart

Imagem do Erro
Comment: O erro está acontecendo na consulta das informações aparentemente, você só colocou as definições dos modelos, poste o código onde a consulta no banco de dados é feita para conseguirmos ajudar
Comment: Eu usei o findAll() normal, tentei por o include mas dava outros erros.
Answer: O erro está acontecendo na consulta das informações aparentemente, você só colocou as definições dos modelos, poste o código onde a consulta no banco de dados é feita para conseguirmos ajudar, mas há algo que você pode tentar.
Sequelize não inclui na consulta por padrão as entidades mapeadas dentro da entitidade que está sendo buscada, na documentação é citado o uso do include:
await User.findAll({ include: Task });

Resultado:
[{
  "name": "John Doe",
  "id": 1,
  "tasks": [{
    "name": "A Task",
    "id": 1,
    "userId": 1
  }]
}]

Um array pode ser passado pra propridade include, algo como:
await User.findAll({ include: [Task, OutraTabela] });

Informações tiradas da documentação do sequelize.
Comment: Eu tentei usar o include, porém dava outros erros, erro do "as", de associação...


Please help me clarify this sentence about 'microtones' on Grove Music

Question: The following sentence is from an article titled Microtone from Grove Music.

The harmonic question is differently settled, of course, when microtones are conceived not as additions to the equal-tempered chromatic system but as basic intervals in other tunings – tunings which have customarily been developed not in order to make available intervals smaller than a semitone but to find better approximations to just intonation than 12-note equal temperament can deliver.

Although I read it several times, then looked up 'just intonation' on Britannica, I still didn't understand the author's suggestion.
Comment: It's not clear from the quotation whether the author is considering the anachronistic application of "microtonal" to historical tuning systems of the early 19th century and earlier or reserving it for systems developed in modern times.  Can you describe how the "harmonic question" is "settled" in the earlier part of the article?
Answer: Music that uses tuning systems other than 12-tone equal temperament (12-TET) is often referred to as "microtonal". 12-TET arose as an approximation of Just Intonation so that it was possible to modulate to any key. However, it's not a very close approximation. Other tuning systems, often called "microtonal" systems, provide better approximations.
A very good explanation of the mathematical difference between 12-TET and Just Intonation can be found in Difference between equal temperament and just intonation. A Just Major 3rd and a 12-Tet Major 3rd are close mathematically, but still audibly different. A "microtonal Major 3rd" might be equal to, or at least closer to, a Just Major 3rd.
Many instances of this type of microtonality can be found on this site by searching the microtonality tag. One in particular that might be of use:

Microtonal theorists who go beyond describing temperament and scale construction
Answer: To expand on what @Aaron already said:
music (tones) is based on partial harmonics. Take the first two partial harmonics (1:2 and 2:3) of any given tone and you get the octave (1:2, double the frequency) and the fifth (2:3, multiply the frequency by 1.5).
Now, go to the nearest piano and stack 7 octaves of any tone. i.e. C-c-c'-c''... Because each one has a frequency double that of the previous one, the first and the last tone should have a frequency relation of 1:128 (2 to the power of 7).
Next, try the same with fifths, i.e. C-G-D-A-E-B-F#-C#-G#-D#-A#-E#(F)-C. Because we have arrived at the same key we should have the same frequency relation between the first and the last tone as before. But when we calculate (1.5 to the power of 12) we find that the result is 129.7 and change. This difference is called the "Pythagorean Comma".
Using only the first and second partials one could construct all 12 tones of our tone system (use fifths to construct the tones, then octaves to have these tone all in the same register). Unfortunately only one scale would sound "in tune", the farther you get away from the original key it the circle of fifths the less properly tuned the scales sound. This is called "just tuning".
Now, you don't want to retune your instrument every time you modulate to a new key and hence ways to get around this were sought - and found. The basic idea is to distribute the difference as evenly as possible around all tones so that no scale sounds perfect anymore but no one sounds completely out of tune either. These forms of tunings are called "temperament".
The last (major) development was the "well-tempered temperament", which makes all the 12 major and minor keys available (a fact which excited J.S.Bach so much, he wrote a piece for a keyboard tuned that way, the "well-tempered keyboard". The well-tempered tuning was discovered in the 16th century by a Chinese mathematician, later re-discovered in the 17th century in Europe (Werckmeister, Kirnberger, ...).
Today we use a tuning quite similar (but not equal) to the well-tempered tuning, the "equal temperament", where the relations between semitones are uniformly  1:12th root of two.
On the upside we are able to modulate to absolutely any scale, as showcased i.e. in "Giant Steps" by John Coltrane. On the downside no interval is "pure" any more and when you play a major triad you will hear a "beat", which you wouldn't hear in a pure tuning.
Comment: There seems to be confusion between meantone and Pythagorean tuning. In Pythagorean tuning, it's not true that "the farther you get away from the original key it the circle of fifths the less properly tuned the scales sound"; rather, all keys will sound similar except for the relative location of the single wolf fifth. The real issue is with the major thirds, even sharper in Pythagorean tuning than in equal temperament, which is what led to the development of meantone temperaments long before modulating to distant keys was an issue. These temperaments do favor keys with simpler key signatures.
Comment: I don't see you this answers the OP
Comment: Try bringing up [quarter-comma meantone tuning](https://en.wikipedia.org/wiki/Quarter-comma_meantone), too. There were also (apparently) a load of types of [well-temperament](https://en.wikipedia.org/wiki/Well_temperament), too.
Answer: Before 12tet came about, some instruments - such as harpsichords - whch are tuned specifically, would be tuned so that their notes sounded best in certain keys. Just Intonation and other temperaments were used , where the intervals sounded more harmonious, musical. This meant that playing pieces in other keys did not sound as harmonious, musical. The pitches of those notes are where this question comes from, I think - differing slightly from the pitches in common use today - with use of 12tet.
Thus the compromise of 12tet came about, where each note was tuned so that it could sound pretty much o.k. in any key. But it was a compromise, where each octave is split exactly equally into 12 parts, and we've basically got used to it.
Instruments such as violin, trombone, and voice will tend to gravitate back to just intonation tuning while playing, so for example, a C note in one key will be slightly at a different pitch from a C note in a different key.
Those two (or more) different C pitches are microtones, not the same as each other. It's rare that they would be used together in one piece - the C in a piece in key C will not be the same pitch as the C (M3) in a piece in key A♭, (or even C (P5) in key F), but they wouldn't occur in the same piece in one key only. That's to say, one pitch would be used that is appropriate for one harmony, a subtly different one for a different harmony, if that makes sense.
Trouble is, on an instrument tuned to J.I. it has to be one or the other, so 12tet gets used. There have been pieces written for microtonal music specially, but they are a different breed.
Comment: "Just Intonation was used": not for tuning harpsichords, it wasn't. Rather, there were dozens of different unequal temperaments used in different times and places.  Also, it's not correct to say "It's rare that they would be used together in one piece."  The tuning of any given note can vary even in one key when played by strings or trombones or sung.  To take the example of C, suppose you're in E-flat major.  The third of the A flat major triad will be lower than the fifth of an F chord (whether minor, major, or dominant).
Comment: @phoog - what I meant was that JI would be used as one tuning method for instruments that needed to be tuned (like pianos today). Of course other temperaments were used, none of them 12tet at the time. I take your point about what harmony is happening in a particular bar. See if the edit helps. Thanks for the explanation of the dv!
Comment: But if you tune a keyboard to just intonation, it isn't useful even in one key because of the wolf fifth between the second and sixth scale degrees.  Nobody ever tuned keyboards in pure just intonation (unless you count pythagorean tuning in the middle ages, where there were only 8 pitches per octave and the major third was a dissonance, so it's not at all the same thing as the 5-limit just intonation most people have in mind when they say "just intonation").  Another way of looking at this is to consider the need to move certain pitches even when staying in one key, which a keyboard can't do.
Comment: @phoog - would my answer be best deleted? I think if you included info such as in these comments, it would make a good answer. I'm learning a lot ! OP seems to be homing in on JI.
Comment: No, I wouldn't delete this answer.  I would just rewrite the beginning of the second sentence so it doesn't say (or appear to say) that harpsichords were tuned in just intonation.  (In fact, the family of temperaments that dominated from the late Renaissance to the middle baroque, "meantone" temperaments, had prominent major thirds that were pure "just" major thirds, or at least closer to pure than those of 12-tone ET, but in order to achieve this they had prominent fifths that were largely rather _farther_ from pure than 12-tone ET, so hardly "just.")
Comment: @phoog - thanks! And thanks for the explanation. Still awaiting your own answer!
Comment: I don't see how this answers the OP.
Comment: @Aaron - I thought I'd explained what microtones are with reference to different tuning systems. What did I miss?
Comment: Your post reads to me as an explanation of the difference between 12TET and JI, which seems to miss the OP questions intent. Your last sentence, IMO, would be the first sentence in a more direct answer.
Answer: Just in case Grove has a global perspective on things: Arabic music is often described as having "microtones" or "quarter tones". The actual case here is precisely what Grove describes: it does  not concern additional intervals to the scale, but rather a different construction of the scale in a different basic tuning. For instance, you could have a scale C-D-E,-F-G-A-B-c where "E," denotes a half flat. In that case the normal E & Eb simply don't exist: the third scale degree is consistently the half flat.
Answer: Just intonation favours expressing intervals across the entire keyboard as ratios of small numbers:

(Perfect) octave - 2:1
Perfect fifth - 3:2
Perfect fourth - 4:3
Major third - 5:4
Minor third - 6:5

As alluded to in other answers, though, these small-number ratios conflict with each other when repeated across the entire keyboard and near-matches keep being found. One of the most important such examples is that 7 octaves tuned as 2:1 each almost equal 12 perfect fifths tuned as 3:2 each - the ratio difference between the 12 perfect fifths and the 7 octaves is (1.5)12⁄ 27 = 531441⁄524288 ≈ 1.01364, or about 23.46 cents. This is known as a Pythagorean comma.
12-tone equal temperament expresses all intervals as ratios of the 12th root of 2, so only octaves get nice, simple, and clean ratios that resemble just intonation precisely. For example, 12TET's ratio for a major third is equal to the cube root of 2 ≈ 1.259921, which is off from just intonation's 5:4 = 1.25 ratio by around 13.69 cents (a big enough difference to force a concert band instrument player to re-tune their instrument - I speak from experience playing in concert bands here).
Just intonation still holds a certain appeal for listeners because it produces particularly harmonious results that 12TET's more complex ratios and therefore increased tendency of subtle beats will not produce. Perhaps one of the most famous examples of that appeal is barbershop quartet music's penchant for wondrously ringing major-minor 7th (a.k.a. "dominant 7th") chords - chords that require just intonation in order to ring. Barbershop quartets use a 7:4 ratio for minor 7ths in order to get that ringing just right.
Tuning systems therefore will often use commas and portions thereof, all microtonal-sized, to approximate at least some of the best parts of just intonation while mitigating at least some of the worst parts (e.g. habit towards wolf fifths if you want to preserve all (perfect) octaves and are willing to compromise on "perfect" fifths). For example, quarter-comma meantone tuning prioritizes major thirds that sound justly tuned at the cost of leaving in a wolf fifth. The comma that quarter-comma meantone tuning cares about is the syntonic comma = 81:80 ≈ 21.51 cents (among others, this is the just intonation ratio difference between 4-perfect-fifths and 2-octaves-and-1-major-third - e.g. C4 to E6 - and between 1-octave-and-1-minor-third and 3-perfect-fourths - e.g. C4 to E♭5), and it flattens nearly all its "perfect" fifths by a quarter of that comma. Quarter-comma meantone tuning was notably more prominent in the 16th-17th centuries than today.
Answer: Whenever you play two notes at the same time, the difference in pitches is called an interval. Because of how pitch perception works, generally we care about the ratio of frequencies, rather than the difference.
Some intervals sound better than others. That's subjective, of course, but it's generally held that the best-sounding frequency ratios are the ones that match up with simple integer ratios - such as 2:1 (i.e., an octave), or 3:2 (the so-called "perfect fifth"), or 4:3 (the so-called "perfect fourth" - which you may notice is also the same as going up an octave and then down a perfect fifth, since 2/1 * 2/3 = 4/3). More complex combinations are usually held to sound okay, even if the numbers get big. For example, going up two perfect fourths and then down a perfect fifth gives you a ratio of 32:27, which is sort of close to the simpler 6:5.
But none of these ideal ratios is actually produced by instruments tuned in the normal modern way (12TET). The modern tuning is designed so that the spacings are the same no matter what key you're playing in; the ratios between adjacent notes are identical. It turns out that no matter how many notes you divide up the octave into, you can't get just-intonation results if you divide it up equally. But with 12 notes (a convention with centuries if not millennia of tradition behind it), you can get very close for some notes (2^(7/12) is about 1.4983), and acceptably close for most others, and it produces a sound that everyone (at least in contemporary Western cultures) is very familiar with.
"Microtones", generally, just means "notes chosen so that the intervals between notes are smaller than in 12TET". That is to say, more than 12 notes are used per octave. (Of course, as the number of notes increases, it becomes harder to design instruments or to write or perform music.)
There are any number of reasons you might want to do this, and depending on your reasons, you might choose to space the notes out in different ways. Equal spacing with a greater number of notes produces interesting results - for example, with 19 equally spaced notes, you get an extremely accurate approximation for the 6:5 interval. Some avant-garde composers, on the other hand, choose dissonance instead; with 14 or 15 notes, the closest approximations to the perfect fifth are quite far off.
However, if we have fixed the key that we want to play in (easy enough in the case of electronic music), then instead of equally spacing the notes, we could simply add notes that are intended to make it easier to get good approximations of the just-intonation intervals in certain keys.
One example of this is in the classical Indian system, each 12TET note, aside from the root and the perfect fifth, is essentially split into two slightly different variations.
Comment: This is explicitly not what the question is about. OP understands that microtones can be used to modify, expand, or decorate 12-TET. OP wants to understand the quotation's other usage of the term "microtone" which is entirely independent of any reference to 12-TET.
Comment: It's not at all clear to me what OP understands, and "the question is about" what the author meant by a single, very long sentence. I tried to cover all the bases. That said, `find better approximations to just intonation than 12-note equal temperament can deliver.` sounds **much more** to me like "decorate 12TET so that JI intervals are also available" than "independently develop a microtonal scale with good JI approximations" - especially since it's being **contrasted with** `make available intervals smaller than a semitone` (i.e., "use nTET where n>12").
Comment: I think your answer would be greatly improved if it focused more on the "independently develop a microtonal scale" rather than explaining the differences between 12-TET and JI.


What is the appropriate statistical test to assess position within a distribution?

Question: I am doing a bioinformatics analysis, where I am scoring every protein-coding gene in the human genome (~19,000) for some genomic property ("interestingness"), then plotting the distribution of scores from lowest to highest. I am then marking, within this distribution, the position of specific subsets of genes - in the figures below, gene set 1 is labeled A-Y, and gene set 2 is labeled a-x. Some genes are marked in red and/or larger text, according to whether their individual "interestingness" score is statistically significant. The red dotted line indicates the cutoff point between "positively interesting" and "negatively interesting."
What would be appropriate statistical tests for the "biasedness" of each gene set within the distribution - visually, it looks like group 1 is non-randomly biased toward the "positively interesting" end, while group 2 looks pretty random, but I'd like to be able to quantify this with a statistic and p-value. I can do, for example, a binomial test for membership in the positively vs negatively interesting groups, which confirms my suspicions, but this seems like a very underpowered and uninformative approach. In the genomics world, people frequently use an approach called "Gene Set Enrichment Analysis" (GSEA) for problems like this, but I think there are assumptions built into that (rather opaque) approach that might not be valid for my interestingness metric. I'm using R for my actual analysis, so if you can recommend a specific package or function that works for your recommended test, that would be great. Thanks!
Answer: As all the genes are included in a single rank-ordering, this could be handled very simply by a Wilcoxon–Mann–Whitney (WMW) test. That tests whether a randomly sampled member of Group 1 tends significantly to be higher (or lower) than a randomly sampled member of Group 2.
The test itself requires few assumptions. It requires that the observations are independent of each other, which is probably OK here (perhaps depending on your measure of "interestingness"). A frequent interpretation of the WMW test, that the median values differ between groups, does require an assumption that the distributions within the two groups have the same shape.
In R you can use the two-sample version of the standard Wilcox.test() function.
Comment: Sorry I forgot to mark this as answered, but this was a great suggestion and worked (I was busy with other analyses and got back to this recently). I don't have enough points on Cross Validated to upvote the answer, but thank you!


file_unmanaged_copy - Any service alternatives?

Question: The functionality of the file_unmanaged_copy is exactly what I need. The only problem is: it's a global function which uses static service calls.
Since I need to unit test my class (and not to mention how I dislike hidden dependencies coming from global functions) I can't use it.
Am working with D8 since the very beginning, but am failed to find any OO alternatives. Has anyone faced the same situation? Any "Best-practises" or workarounds?
Comment: There is no oop replacement yet. There are a number of issues to convert those function to services but it didn't happen yet. The common approach that core uses to solve this problem so to hide this function in a protected method and in the unit test, you mock your own class so that you are able to mock that method. Or you make a separate service that just wraps that method so you can mock it
Answer: This changed in Drupal 8.7.0
See https://www.drupal.org/node/3006851
try {
  \Drupal::service('file_system')->copy($source, $destination, $replace);
}
catch (\Drupal\Core\File\Exception\FileException $e) {
    // Log or set message or doing something else.
}

Answer: As for now Berdir's comment is the right answer:

There is no oop replacement yet. There are a number of issues to
  convert those function to services but it didn't happen yet. The
  common approach that core uses to solve this problem so to hide this
  function in a protected method and in the unit test, you mock your own
  class so that you are able to mock that method. Or you make a separate
  service that just wraps that method so you can mock it

Personally, I prefer the later one, wrapping it the globals into a service.


Spray's integration with idea

Question: I have a simple spray service actor
class SimplService(service: AService) extends HttpServiceActor
  with MyJsonProtocol
  with SprayJsonSupport {

  override def receive: Receive = runRoute {
    path("a") {
      get {
        parameter('param.as[String]) { p =>
          complete {
            service.foo(p)
          }
        }
      }
    }
  }
}

AService's foo methods returns Future[List[SomeClass]]
There is an implcict a jsonFormat declared in MyJsonProtocol(which of course extends from DefaultJsonProtocol) for SomeClass
When running in intellij idea i get such compile time error
could not find implicit value for parameter marshaller: spray.httpx.marshalling.ToResponseMarshaller[scala.concurrent.Future[List[SomeClass]]]

What I'm doing wrong?
Answer: SOLVED
The problem was in absence of implicit Execution context.
IMHO, error message might be better

Spray's integration with idea


Raspberry pi 2 and BMP280 : Slave address was not acknowledged

Question: I follow the project WheatherStation on https://www.hackster.io Windows IOT.
I downloaded project on github and connected my BMP280 sensor on Raspberry.
You can check my connections on

http://kdamerval.fr/WeatherStation/1.jpg
http://kdamerval.fr/WeatherStation/2.jpg

For me, it's correct, but i have an exception with bmp280.WriteRead(WriteBuffer, ReadBuffer);

System.IO.FileNotFoundException: The system cannot find the file specified. Slave address was not acknowledged.
Comment: why don't use `raspbian` (with a lot examples and modules)?
Comment: @viiink did you had success for writing a bmp280 Windows 10 IoT Core driver / controller?
Answer: There are a couple of different causes for this issue, most of which relate to hardware.
I see you're using the Adafruit breakout board and will reference the pins based on this.

Make sure your SDO and SCL lines are properly connected to your Raspberry PI.  SDO should connect to Pin 3 and SCL should connect to pin 5. From looking at your diagram pictures this should be correct.
Next up is Vin.  The Fritzing Image is incorrect on the Hackster.io.  Vin should be connected to your 3.3V line, Pin 1 on your PI.

This is because Vin is the supply level of your logic signal. In this case the Raspberry PI is 3.3V, putting it at 5 can cause issues where data is not properly clocked in via I2C.

Lastly, pull SDO high by tying it to V3.3.

The reason for this is if you read the datasheet for the BMP280/BME280 and look at the schematic you will see SDO has a pullup resistor that pulls it to 3.3V it's internal logic level. This is going to be exceptionally weird if using 5v rails as you're not technically in a tristate neither low nor hi so you will probably end up with a random address.
Pulling this to 0V via ground will cause the slave address to be 0x76.  With it pulled high the slave address of the BMP280/BME280 sensor will be 0x77. From looking at their supplied code they expect this pin to be pulled high giving a 0x77 address.

An alternative software solution for #3 is to change the I2C Slave address in the BME280 device code. In the example code this is contained within Lesson_203\StartSolution\BMP280.cs:
class BMP280
{
    //The BMP280 register addresses according the the datasheet: http://www.adafruit.com/datasheets/BST-BMP280-DS001-11.pdf
    const byte BMP280_Address = 0x77;  //If SDI is pulled high 0x77, if pulled low 0x76
    const byte BMP280_Signature = 0x58;

Lastly, your pin connections on your Pi if you're looking at the pi from the top with the HDMI port pointing towards you and the SD card slot on the left you are interested in the left most pins of the 40 pin header.
5V | 5V | Ground
3.3V | SDA(SDI) | SCLK
See also this header map. Pi3 Header Map
Answer: This may be an issue with I2C bus (since ACK is not received).
If that is fine, cross-check if you have cloned their repo using the --recursive flag? All sub-modules would be properly cloned using this. (There may be some file missing otherwise.)
Answer: Check your wires. Make sure they are completely pushed and at the right place. It was the problem for me.
Answer: You had to solder the BMP280...


How to create Javascript concatenation; Several text fields to seperate text areas?

Question: I'm trying to concatenate 5 text fields into 2 different formats and have each specific format output to 2 seperate text areas in the same form/page.
The attached code works fine to output to TextArea1 but will not output to my second TextArea2.
So C+A, B+D, E to populate TextArea1.
And C+D, A, B+E to populate TextArea2.
Any help/advice would be greatly appreciated.
Thank you.

    <form method="post">

  <input name="TextA" onkeyup="setName()" type="text" />

  <input name="TextB" onkeyup="setName()" type="text" />

  <input name="TextC" onkeyup="setName()" type="text" />

  <input name="TextD" onkeyup="setName()" type="text" />

  <input name="TextE" onkeyup="setName()" type="text" />

  C+A, B+D, E

  Created this outcome:

  <input name="TextArea1" onfocus="setName()" style="width: 286px; height: 90px" type="text" wrap="hard" />

  C+D, A, B+E

  Created this outcome:

  <input name="TextArea2" onfocus="setName()" style="width: 286px; height: 90px" type="text" wrap="hard" />

  Clear Form

  <input name="Reset2" type="reset" value="reset" />

    </form>

Comment: Please try to isolate code/markup to the bare essentials necessary to illustrate the problem. Things like CSS etc. won't affect outcome in this case. Also, http://jsfiddle.net and similar are an easy way to provide a live example people can look at.
Answer: You have two functions with the same name; the second overwrites the first.
Answer: You're using the same function name for both of the functions.  The second one is overriding the first.  Change it to setNameTwo() or something like that and it should work fine.
Answer: You have the function setName() defined twice. The first one is being called, but not the second one. Put the code from the second setName into the first one, along with the code that's already there, and it will work.

Comment: Actually, the second one is being called--later definitions override earlier ones.
Comment: I didn't know that. Learned something new :) but based on the question, the first one is being called. OP said TextArea1 is being populated, which is what the first instance of setName() is doing.
Comment: Could be, but the semantics of JS don't care what any of us think: if you define two methods with the same name, the first is vapor. Also, IMO combining the two methods conflates intrinsically separate behaviors and is a bad habit to get in to.


SPContext in Event Receiver (PortalSiteMapProvider)

Question: I'm trying to write an event receiver which uses the PortalSiteMapProvider. Without having HTTPContext or SPContext INSIDE the event receiver, how would one go about accessing the PortalSiteMapProvider?
Comment: I would be more interested in how you would use an event receiver without having a SPContext object. Please explain.
Comment: You do not have SPContext inside an Event Receiver.
Comment: Which type of event are you using?
Comment: You can determine both the web and list from SPItemEventProperties
Comment: But you don't have SPContext to use the PortalSiteMapProvider. Getting a reference to web/list don't give me context.
Comment: I assume you want to use PortalSiteMapProvider because you want a quick way to query against the web from inside of your event.  Is my assumption true?  What is it you need to do?
Answer: Try this in your event receiver:
<code>var web = properties.Web;

HttpRequest request = new HttpRequest(string.Empty, web.Url, string.Empty);

HttpResponse response = new HttpResponse(new System.IO.StreamWriter(new System.IO.MemoryStream()));

HttpContext impersonatedContext = new HttpContext(request, response);

impersonatedContext.Items["HttpHandlerSPWeb"] = web;

HttpContext.Current = impersonatedContext;

SPContext context = SPContext.GetContext(impersonatedContext);
</code>
You should be able to get your SPContext from that.


Can not display background-image in laravel

Question: please help me! In resources/views/welcome.bale.php:
<link rel="stylesheet" href="{{asset('css/style.css')}}">

Facts that Make us Unique

In public folder: css/style.css
.factarea {background-image: url(../img/website.jpg);}

public/img/website.jpg  location
Answer: I hope the below line will help you to resolve this issue.
You can try this.

background-image: url("/img/website.jpg");

You can try with another way like in-line css and check what we getting the image or not. so we can easily find the correct path.
Thanks
Comment: You can try with .factarea {background-image: url(./img/website.jpg);}
Comment: Happy to help you. @KumoMit
Answer: use root path
.factarea {background-image: url(/img/website.jpg);}

like this then
websiteurl/img/website.jpg will work here
websiteurl/public/img/website.jpg will not work only pretty url will work
so in order to work in public url as well you have to add inline css
which is
<link rel="stylesheet" href="{{asset('css/style.css')}}">

Facts that Make us Unique


Find the probability that a pump would have cost more to rent than to buy

Question: We have a continuous random variable $X$ modelled by $f(x)=\frac{k}x$.   For $1<x<9$ this is the length of time in years that water pumps last for.
(Therefore $k$ can be solved to get $k=\frac{1}{2\ln3}$)
Then there are two very difficult concepts that come with this question.
First part: The farmer is offered a guarantee to cover the cost of replacing a pump that fails during the second year, at a cost of $300$. Given the pump will cost $1000$ to replace if it fails during the year, what advice would you give as to the offer?
Second part: pumps can be rented for an installation charge of $200$ plus $250$ per year payable in advance. The yearly payment is not refundable if the pump fails before the end of the year. The farmer does not purchase the guarantee. Find the probability that the pump, at the end of its life, would have cost more to rent than to buy for $1000$.
To be honest I don't even know where to start. In fact I made this account because nobody I talk to knows where to start. I hope that if somebody can explain this to me then I will be able to have a much greater understanding of the concepts underpinning this question
Answer: For the first part, he can accept a loss of $300$ or take his chances on losing $1000$.  Buying the insurance will be a good deal if the probability of the pump failing is greater than $0.3$.  Integrate the probability distribution from $1$ to $2$ to get the chance it fails during the second year.  For the second part, if it fails during the second year you pay $700$.  If it fails during the third year you pay $950$.  If it fails after the third year, you pay more than $1000$ to rent it.  Compute the chance it lasts more than three years.
Comment: yikes, sorry. I edited the number $k$ wrongly.
Comment: Thanks Ross. I completely understand how you did that. But here's another wee problem I have. I feel like there is another way I can do this problem which seems legitimate( but it can't be because it gives an answer of 0.47, whereas you method gives a perfect 0.5).                          The other way is this: event is Rent cost>Buy cost. Event B is always equal to 1000. Event R is modelled as 200+250X (where X is the life of the pump.) Then 200+250X>1000. I think (not sure completely) we are allowed to use algebra on this to get X>3.2. Then solving P(X>3.2) gets the answer of 0.47
Comment: The problem says you pay 250 at the start of any year when the pump has not failed and you do not get a refund for partial years.  That is why I did it the way I did.  Once the fourth year starts you pay the fourth $250$ for a total $1200$, which is when the rental cost exceeds $1000$.
Comment: Wait Ross so you see how I got p(X>3.2) right?  Is that a legitimate way to do the question? Then I can say that because you don't get a payment for partial years then you round it to p(X>3). Is that also a way of doing it?
Comment: I see how you got it.  It is correct if you get a partial refund, but the question specifies you do not.  If the pump lasts 3.1 years you spend 1200 renting and are losing compared to buying.


Paleta de cores (VBA/Excel), evento "botão direito do mouse" para objetos Frame

Question: Não encontrei referência sobre o evento que seja acionado pelo botão direito do mouse em um objeto Frame. Com o evento do botão esquerdo do mouse seleciono a cor desejada, isto está funcionando, porém, com o botão direito eu definiria as cores personalizadas dinamicamente, mas não encontrei o evento desejado para fazer isso.
A ideia é alterar a cor de fundo de cores a serem personalizadas (já funciona também) ao clicar o botão direito em um objeto Frame. Cada frame representa uma cor adicional a personalizar (são as dezesseis áreas em branco da parte inferior da paleta).

Existe evento correspondente ao clicar do botão direito do mouse para o objeto Frame?
ATUALIZAÇÃO
Veja a solução encontrada na Resposta abaixo
Comment: Mostra a tela onde você está programando. Mostra um print
Comment: Oi Eduardo, não entendi. Esta paleta já é um PrintScreen editado que coloquei em um objeto imagem. Pelo mouse move (x,y), sei a região que o cursor está, e com o click qual a cor que foi selecionada. O que quero é, da mesma forma, ao clicar o botão direito do mouse em cima de um dos dezesseis frames em branco, abrir outra imagem que tenho que usa o RGB conforme as coordenadas x e y (mostrando várias cores dinamicamente) e ao clicar, ele retorna a cor escolhida (isso já funciona). Portanto, Resta apenas eu aplicar o evento que acione o botão direito do mouse. É isso.
Answer: SOLUÇÃO
Encontrei o modo de fazer o controle do clicar do botão direito do mouse sob um frame (serve para outros objetos também).
Deve-se usar o evento MouseDown ou MouseUp, por exemplo (após criar o Frame1 no formulário):
<code>Private Sub Frame1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

If Button = 2 Then MsgBox "Botão direito do mouse"

End Sub
</code>
Neste link aparece os valores correspondentes a cada botão do mouse, e a soma pode ser combinada para saber se mais de um foi acionado ao mesmo tempo:
https://msdn.microsoft.com/pt-br/library/office/gg278486.aspx
Um detalhe, veja o nome dos parâmetros criados dentro do evento que for manipular (olhe os argumentos do evento), pois há diferenças do que está informado no site, uma vez que a descrição é para eventos de formulário (fm), por exemplo, a variável fmButton é indicada para capturar o valor do botão acionado do mouse em um formulário, mas no evento do frame a variável é simplesmente Button.
É isso!


Terraform parallel VM creation

Question: I'm trying to do a very basic task on Terraform v0.10.7.
I have up to 100 VM to be povisionned using terraform + vSphere provisionner and I want to be able to launch several resource creations in the same time and not one after the other. For the moment the second VM is created only if the previous one is finished.
I've tried to read the doc but I didn't found any answer, could somebody help me ?
variable "user" {}
variable "password" {}
variable "vsphere_server" {}

provider "vsphere" {

 user           = "${var.user}"

 password       = "${var.password}"

 vsphere_server = "${var.vsphere_server}"

 allow_unverified_ssl = "true"

}

resource "vsphere_virtual_machine" "dum03" {
  name          = "dum03"
  hostname      = "dumHN"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "NET-TEST"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "10.20.30.40"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "datastore"
    template  = "mytemplate"
  }
}

resource "vsphere_virtual_machine" "dum04" {
  name          = "dum4"
  hostname      = "dumHN2"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "test"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "18.104.22.168"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "mydatastore"
    template  = "mytemplate"
  }
}

Answer: You need to start all your VMs within one vsphere_virtual_machine resource using count statement. Count starts from 0.
It should be like:
variable "vm_count" = 2

resource "vsphere_virtual_machine" "dum" {
  name          = "dum${format("%02d", count.index+3)}"
  hostname      = "dumHN${count.index+1}"
  count         = "${var.vm_count}"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "NET-TEST"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "10.20.30.${40 + count.index * 5)}"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "datastore"
    template  = "mytemplate"
  }
}

Comment: Thank you for your answer and sorry but I didn't solved the problem like.

Actually my problem was that the ressources were created one after the other which was so long, but defining my resources themself wasn't a problem.

Please check the following answer to get my solution.
Answer: Some providers (AWS, for example), handle API rate limiting issues at a lower level by implementing graceful backoff/retry in their respective API clients. For this reason, Terraform does not use this parallelism feature to address API rate limits directly.
Check the official doc of terraform
Answer: This is my solution :
I generate my terraform files using Ansible.
A new directory is created for each machine and I generate my scripts in each directoy for ONE and only ONE machine.
Finally, still using Ansible, I command an asynchronous "terraform apply -var-file=XXX.tvars" for each scripts locations with a with_items for each location/each machine and register this command.
The VMs are all triggered in the same time.
By registering my command earlier, I have now access to a job_id, so now I can control the result after.
- name: Apply ressource creation
  command: "terraform apply -var-file=./{{environment_name}}.tfvars
-var-file=./instance.tfvars"
 args:
    chdir: /appli/terraform/{{item.name}}/
 async: 3600
 poll: 0
 with_items: "{{VM_provide}}"
 ignore_errors: yes
 register: creation

- name: Wait for the creation job to complete
  async_status: jid="{{creation_item.ansible_job_id}}"
  with_items: "{{creation.results}}"
  loop_control:
    loop_var: "creation_item"
  register: job_result
  until: job_result.finished
  retries: 200
  poll: 10

Comment: Except now you have multiple `terraform.state` files instead of one for your whole deployment which means it's now harder to manage. Also, any sane VMware deployment will limit how many operations a user is allowed to issue concurrently to the cluster so I'd never expect you to be able to create 100 VM's all at once.
Answer: I try this and works:
In this example I deploy 3 vms in the same file with different resources like hostname.
Change the variable resource "vsphere_virtual_machine" "vm(number)" for the number of vms to deploy:
resource "vsphere_virtual_machine" "vm"
resource "vsphere_virtual_machine" "vm1"
resource "vsphere_virtual_machine" "vm2"

Here the link with full config:
terraformconfig
Comment: please fix formatting

Terraform parallel VM creation


Consistency of values generated with a Poisson inverse function and random numbers in Python

Question: I have a Python file that simulates 10 000 hypothetical soccer matches between two teams. This is done by generating two sets of 10 000 random numbers between 0 to 1 (10 000 for each team). This is then passed through a Poisson inverse function for each team, which uses the expected goals per team for the match (a value that considers expected goals scored and received per match), to calculate goals per team for each one of the 10 000 matches. I then count the percentage of wins, ties and losses, which will vary depending on the teams considered and their expected goals per match.
I have noticed that if I run this code for a particular team playing against itself, or two teams that have the exact same number of expected goals for a match against each other, the percentage of wins, ties and losses is not consistent, within a margin of error of about 2 %. Roughly speaking, I have not calculated this. This means that a team will for example win against itself 38 % of the time and lose against itself 37 % of the time. I would expect the same percentage of wins/losses for the same team agsinst itself. The discrepancy is in the counts, and is not explained by rounding up the percentages. I am trying to get a better understanding of what is going on, to take this into consideration in the code. Does this have to do with the way Python generates random numbers? Or is there an intrinsic aspect of the Poisson inverse that causes this?  In any case, what could be going on here? I have the feeling that there is a very simple explanation that I am overseeing.
Comment: It has nothing to do with Python and not much to do with a Poisson distribution, but everything to do with the noise inherent in simulations.  Flip a coin $10000$ times and you should not be surprised if the numbers of heads and tails differ
Comment: This is pretty vague. Can you simplify the problem to a minimal working example that demonstrates the unexpected behavior? When you do, please include the code and the specific results that surprise you. I'm not certain, but I think that Python relies on the operating system to provide it with random numbers, so I don't think there will be any strangeness with the generation specific to the language. Could be wrong about that.
Comment: There are multiple ways to use Python to do what you are describing, and without knowing the specific code it is almost impossible to answer your question. The right way to ask a question like this is to try to reproduce the behavior you are describing in a few readable lines of code (i.e. remove all the code which is non-essential to the phenomenon you observe), include a code into your question, and ask a question about the behavior of that code snippet.
Answer: If you are surprised that a large proportion of your simulation runs have an absolute difference between wins and losses of more than $50$ games i.e. more than $\pm 0.5\%$ of the $10000$ games simulated, you should not be. This may happen about $56\%$ of the time.
Suppose the probability of a win against your clone was $37.5\%$, and similarly the probability of a loss was also $37.5\%$, and a draw $25\%$, then in a single game the probability of win-loss being $+1$ is $0.375$ and being $-1$ is $0.375$ and being $0$ is $0.25$.  This distribution has mean $0$ and variance $0.75$.
Take $10000$ i.i.d. simulations and the total wins-losses has mean $0$ and variance $7500$, i.e. a standard deviation of $\sqrt{7500} \approx 86.6$. As a proportion of the $10000$ games, that standard deviation is $0.00866$ or $0.866\%$.
So seeing a simulated difference betweens wins and losses in a range of $\pm200$ games or $\pm 2\%$ of the games is more or less what you might expect: it is about $\pm 2.3$ standard deviations from the mean, and you might expect about $98\%$ of your simulation runs to fall inside this interval.
Comment: Not that it matters, but you get those probabilities if each team independently scored a Poisson distributed number of goals each with expectation about $1.4274$
Comment: Thanks! I think this pretty much sums up what is going on. I had a feeling it was a simple explanation. I could share the code and results, but considering your suggestion, this behavior is rather independent of the method, and to be expected as noise in a probabilistic scenario like this one.
Comment: By the way, I realized that I was confusing "inconsistency" in Python's method to generate random numbers, or Python's inverse Poisson function, with "randomness". All methods can be consistent, but there will still be randomness in such a simulation. And that is the whole point of the simulation, contrary to just getting the probabilities for each possible score with a Poisson function (not its inverse and random numbers), which renders the exact same result for the same expected goals. The whole point of simulating like this is to create a random situation that resembles reality closer.


SOCKETS EM C - Número de Sequência TCP

Question: Estou precisando de um help com sockets em C. Minha professora passou um trabalho em que devo executar a comunicação TCP entre cliente e servidor onde eu devo executar algumas regras..

1 - O Cliente envia uma mensagem ao servidor. A mensagem deve conter
o número de sequência e a quantidade de bytes carregada pela
mensagem.
2 - O servidor deve receber a mensagem e enviar um reconhecimento ao
cliente. A mensagem de reconhecimento deve conter, o número de
sequência da mensagem reconhecimento, o número de sequência do
próximo segmento a ser enviado pelo cliente.

Alguém conseguiria me explicar melhor como funciona o numero de sequencia e se possível me auxiliar a codificar isso? A parte da comunicação TCP entre cliente/servidor está em anexo e pronta.
Trecho de código cliente:
 sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 8888 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");

    //keep communicating with server
    while(1)
    {
        printf("Enter message : ");
    gets(message);
    fflush(stdin);
        //scanf("%s" , message);

        //Send some data
        if( send(sock , message, strlen(message) , 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if( recv(sock , server_reply , 2000 , 0) < 0)
        {
            puts("recv failed");
            break;
        }

        puts("Server reply :");
        //puts(server_reply);
    int vl = 0;
    for(int i =0; server_reply[i] != '\0';i++)
    {
        if(server_reply[i] != ' ')
            vl += (int)server_reply[i];
    }
        printf("%d\n",vl);
}
    close(sock);

Trecho de código do servidor:
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
    printf("Could not create socket");
}
puts("Socket created");

//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );

//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
    //print the error message
    perror("bind failed. Error");
    return 1;
}
puts("bind done");

//Listen
listen(socket_desc , 3);

//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);

//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
    perror("accept failed");
    return 1;
}
puts("Connection accepted");

//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
    //Send the message back to client
    write(client_sock , client_message , strlen(client_message));
}

if(read_size == 0)
{
    puts("Client disconnected");
    fflush(stdout);
}
else if(read_size == -1)
{
    perror("recv failed");
}

Answer: Monte as mensagens a serem enviadas ao servidor seguindo o layout solicitado, contendo o número de sequência e o tamanho da área de dados da mensagem.
Por exemplo:
mensagem 1:
0000 0010 0123456890

A mensagem 1 tem o número de sequência 0 (0000), o tamanho 10 (0010), e 10 bytes de dados: 01...90
mensagem 2:
0001 0015 012345689012345

A mensagem 2 tem o número de sequência 1 (0001), o tamanho 15 (0015), e 15 bytes de dados: 01...9012345
Etc.
A resposta do servidor vai conter apenas o último número de sequência recebido e o próximo número de sequência a ser recebido.
Fluxo de mensagens:
Cliente envia mensage 0000:
0000 0010 0123456890

Servidor responde resposta 0000:
0000 0001

nesta mensagem o servidor informa ao cliente que recebeu a mensagem com número de sequência 0000, e espera receber a próxima mensagem com número de sequência 0001.
Etc.

SOCKETS EM C - Número de Sequência TCP


Computer-based alternatives to TI89 calculator?

Question: Back in the 90s in order to solve complex algebraic equations I would use my TI-89 calculator. What is a PC or Mac or iPhone or Internet-based equivalent?
I need to solve an equation like the following:
<code>25000x^0.293150685 + 250000x - 298082 = 0
</code>
I tried the Desmos iPhone app and it said it didn't solve algebraic equations yet. It's 2017, let's get with the times already!
Comment: http://www.wolframalpha.com/input/?i=25000x%5E0.293150685+%2B+250000x+-+298082+%3D+0&t=crmtb01 Wolfram Alpha also has an app for iPhone
Comment: It's andoid or linux :) e.g. https://play.google.com/store/apps/details?id=com.Bisha.TI89Emu&hl=en or http://www.sagemath.org/
Answer: SAGE! You should give very serious consideration to SAGE. There's a free online version which is superb. You can use it on your iPhone, tablet, or computer.
There is also a software package you can download and install.
I recommend SAGE as the default calculator for my classes. It's perfect for getting experience with Python, checking your work, or having it do work for you. It can integrate with GAP, Haskell, and so much more.
http://www.sagemath.org
Comment: I tried SageMath, but when I tried to write a program to solve the algebraic equation in my original question, it froze and never could solve it. Maybe I was doing it wrong. Can you give me the right program code?
Comment: Let me see your code, then I'll be happy to help.
Comment: Actually it was just a command: solve([0 == (250000*x^365) + (25000 * x^107) - 289082], x)
Comment: https://cloud.sagemath.com/projects/82478ca9-aa05-4399-bb6e-bc6140d905c7/files/Stack%20ex.sagews

Via: https://ask.sagemath.org/question/7823/numerically-find-all-roots-in-an-interval/


mongoose / mongodb - reference value from another document

Question: Learning in progress - Stuck working out how have to have 2 separate documents in different collections: events & event reviews
I'm able to reference objectId's between the two but what's the best way to reference data from within those documents if I wanted to populate information from the event into the event review as it's created? I've been trying to trying to google the answer for a few hours now but have so far been unsuccessful with each method I've found. Not looking for a specific answer just somebody with a bit more knowledge to point me in the right direction.
Comment: Can you be more specific about what you're trying to do beyond Mongoose's support for [population](http://mongoosejs.com/docs/populate.html)?
Comment: Are You Trying to store the object id from event into event review ?
Answer: You need to explicitly state that a field in your event reviews schema references the ObjectID of a document in your event collection. Like so...
var mongoose = require('mongoose'), Schema = mongoose.Schema
var EventReviewSchema = new Schema({
   someField:{
     type: Schema.Types.ObjectId,
     ref: 'Event'   // Note this is the name of the event model, not schema
     }
})

You mentioned that you want to do this "as it's created."
Remember that in MongoDB, write operations are only atomic at the single document level. So there is no "built in" way to guarantee that every event document you create will have a corresponding event review document (I assume that this is what you're trying to do.)
You will need to save an event document, grab that document's ObjectId and use it to populate the appropriate field in your event review document. But remember, there is chance that the second write operation will fail if some error occurs between the time of the first and second write operation.
My advice is to try to write your application in a way that can use a mongoose FindOrCreate method (with a plugin) when querying for event review documents. It's a quick and dirty way to solve this problem.
EDIT:
var Review = mongoose.model('Review', EventReviewSchema)

module.exports.reviewCreate = function(req, res, next) {
    var eventid = req.params.eventid
    if (eventid) {
        var review = new Review() // Review model
        review.someField = eventId
        review.save(function(err){
            if(err) return next(err)
            // save successful
        })
    }
}

Comment: Ok this is one of the methods I had attempted and is similar to how I reference the objectId. The part I'm not understanding, is based on the information above, what is required on the module side to specifically reference the required data. Here's what I thought would work (but does not). Am I missing a step?
`module.exports.reviewCreate = function(req, res) {
  var eventid = req.params.eventid;

  if (eventid) {
    Review.create({
      event_id: mongoose.Types.ObjectId(eventid),
      someField: eventid
      ...` This would just add the objectId to someField.
Comment: Sorry for the delayed response - yes I'm using expressjs. I'm following your edits and now understand the purpose of using save instead of create a bit more. The only part I trip up on is that for me EventReviewSchema is undefined since that is defined in the model not the controller.


Mongo 3.2 join with specific item

Question: Imagine two collections in Mongo 3.2 called student and class.  What is the query that would return all student documents that are in a specific class.
The aggregate with $lookup seems to want to operate on all documents in the collection.  For instance returning all students in every class instead of the specific one.
How can I request the resulting student documents that are in a specific class with id=23945647b27e7e652a9aeb65?
Class:
{
    "_id" : ObjectId("23945647b27e7e652a9aeb65"),  // Given this
    "name" : "Algebra",
    "students" : [ "13945647b27e7e65869aeb65", "03945647b27e7e65029aeb65" ]
}

Student:  // Return this
{
    "_id" : ObjectId("13945647b27e7e65869aeb65"),
    "name" : "foo"
}
{
    "_id" : ObjectId("03945647b27e7e65029aeb65"),
    "name" : "bar"
}

Some failed attempts:
db.student.aggregate([{$match:{"$ref": "class", "_id": ObjectId("23945647b27e7e652a9aeb65")}},{$lookup:{from: "class",localField:"students",foreignField: "_id", as: "stuffFromRight"}}}])

db.student.aggregate([{$lookup:{from: {"$ref": "class", "_id": ObjectId("23945647b27e7e652a9aeb65")},localField:"students",foreignField: "_id", as: "stuffFromRight"}}])

This one gets PARTIAL credit as it does do the correct lookup.  BUT, ..., it does not limit the result to the specific class I want.
db.student.aggregate([{$lookup:{from: "class",localField:"students",foreignField: "_id", as: "stuffFromRight"}}])

Answer: There are a few issues with the example.

The type between the array in class and the student object itself is not the same.  You wouldn't be able to compare a string to an ObjectId and expect the desired result.
$lookup performs an $eq on the two fields.  In the example, that means that the lookup is trying to compare:
["13945647b27e7e65869aeb65","03945647b27e7e65029aeb65"] == ObjectId("13945647b27e7e65869aeb65")

Because of both of the points above, this query would fail and it would end up searching all the documents.
In order to use the students array from the class side, you would need to first fix the array to match type, then you would have to first unwind the array before performing a lookup.  Here is an example:
db.class.aggregate([
    {$match:{ "_id": ObjectId("23945647b27e7e652a9aeb65")}},
    {$unwind: "$students"},
    {$lookup: { from: "student", localField: "students", foreignField: "_id", as: "stuffFromRight"}}
])

With the result above, you could then use a project to reduce it to only show the student records if you want to, but it may also be worth pulling the class and students together since you will likely need to query the class anyway in the output.
Comment: students is a hex string which is equivelent to "new ObjectId( hexStr )" but causes a empty result in the last lookup phase.  The unwind produces several copies of the class object but with and empty "stuffFromRight" field.

What is needed is a String->ObjectId transformation.
Comment: @redboy There is not an option in an aggregation to convert a string to ObjectId or vise versa.  Ultimately, the data needs to be fixed so that it has not lost it's type.  You may need to pull the students array into your application, then query the students once the types are correctly set on each element in the array of student ids.

Mongo 3.2 join with specific item


Investigate the reason for a number of undefined expressions in mathematics

Question: Why are the following terms undefined in mathematics?

$$ \dfrac{a}{0},0^0$$ such that $a$ is real number.

if   $n$ to be even number then $\sqrt[n]{x}$ is not negetive number. For example $\sqrt[2]{25}$ is $5$ but is not $-5$.

If $a$ is a negative number and $\dfrac{m}{n}\in Q $ but $\dfrac{m}{n}\notin Z $ then, $(a)^{\dfrac{m}{n}}$ is not defined.
Comment: Asked many many many times... If $\dfrac a 0 = b$, then $b \times 0 =a$. What is the value of $b \times 0$ ? See [Division by zero](https://en.wikipedia.org/wiki/Division_by_zero)
Comment: $0^0$ usually is defined and is taken to be $1$
Comment: What are you looking for here?  These examples are not of the same type...$\sqrt {x^2}=|x|$ is a *definition*.  In your other cases, attempts to attach meaning to your expressions leads to algebraic complications.  See [this partial duplicate](https://math.stackexchange.com/questions/556957/why-not-define-0-0-to-be-0) for instance.
Comment: For #1 and #3: just like not every string of words in English makes sense, so not every string of symbols in math makes sense. Just because we can write it doesn't mean it means something. $\frac{1}{0}$ can't mean anything because if it meant some number $x$ so that $\frac{1}{0}=x$ then by usual laws of algebra you'd have $1=0$, so saying $\frac{1}{0}$ equals a number means breaking other laws of math. This is why it isn't done, and similarly for all the other examples you wrote in #1 and #3.
Comment: This is multiple questions in one, which is something we prefer not to have in this community. It would be best if you could focus on one specific undefined expression in particular.
Comment: Have a look at [this](https://math.stackexchange.com/q/11150/8581).
Answer: $0^0=1,$ so I would not say it is undefined. More on this later.
Why is $\frac{x}0$ undefined? What does it mean for it to be undefined? To understand the answer to this question, we will need to delve a bit into group theory. I will do my best to explain the basics of what a group is.
Firstly, we start with a mathematical structure $(\mathbf{M},\star)$ called a magma. Here, $\mathbf{M}$ is any set, and $\star$ is a binary operation, which takes a pair $(m_0,m_1)$ as the input, where $m_0,m_1\in\mathbf{M},$ and returns some $n\in\mathbf{M}$ as the output. Using the notation that we use for functions, we would write $\star(m_0,m_1)=n.$ However, in the context of arithmetic and algebra, there is a notation for this that is more common: $m_0\star{m_1}=n.$ Examples of binary operations are addition $(+),$ multiplication $(\cdot),$ function composition $(\circ),$ convolution $(\ast),$ and there are many others.
Some magmas have something called an identity element. An identity element $e\in\mathbf{M}$ of a magma $(\mathbf{M},\star)$ is a constant such that $e\star{m}=m\star{e}=m$ for all $m\in\mathbf{M}.$ In the context of addition $(+),$ such an identity element is typically denoted as $0,$ and in the context of multiplication $(\cdot),$ it is denoted as $1.$
Now, you are ready to understand what a group is. A magma $(\mathbf{M},\star)$ is called a group when it satisfies the following axioms:

There exists some $e\in\mathbf{M}$ such that for all $m\in\mathbf{M},$ $e\star{m}=m\star{e}=m$ (Axiom of identity element).
For all $m\in\mathbf{M},$ there exists some $n=m^{-1}\in\mathbf{M}$ such that $m\star{m^{-1}}=m^{-1}\star{m}=e$ (Axiom of invertibility) ($m^{-1}$ is called the $\star$-inverse of $m$).
For all $m,n,p\in\mathbf{M},$ $(m\star{n})\star{p}=m\star(n\star{p})$ (Axiom of associativity).

Groups are an extremely important type of abstract mathematical structure with all sorts of applications everywhere. Why are they important for your question? Because underlying all of arithmetic and algebra is the theory of magmas, groups, and other structures that are similar. To give you a sense of familiarity, I want to give you some examples of groups you work with regularly.

The structure $(\mathbb{Z},+)$ forms a group with identity element $0.$ Here, $\mathbb{Z}$ are the integers. So the integers form a group with respect to addition.
The structure $(\mathbb{Q}\setminus\{0\},\cdot)$ forms a group with identity element $1.$ Remember that $\mathbb{Q}\setminus\{0\}$ are the nonzero rational numbers. They form a group with respect to multiplication.
The set of polynomials of degree up to $n$ form a group with respect to $+.$
The set of functions of real numbers with real variables forma  group with respect to $+.$

This is all good, but in most applications, you actually have two binary operations, $+$ and $\cdot,$ instead of only one. So in actuality, you have two magmas: $(\mathbf{M},+)$ and $(\mathbf{M},\cdot).$ Also, in most applications, the set $\mathbf{M}$ is a set of numbers, or a set of functions. In elementary arithemtic, you usually have $\mathbf{M}$ be the set of integers $(\mathbb{Z}),$ the set of rational numbers or fractions $(\mathbb{Q}),$ the set of real numbers $(\mathbb{R}),$ or the set of complex numbers $(\mathbb{C}).$ What all of these elementary structures have in common is that they have two binary operations: $+$ and $\cdot.$ Also, they all share an additional axiom that connects the two operations together:

For all $m,n,p\in\mathbf{M},$ $p\cdot(m+n)=(p\cdot{m})+(p\cdot{n})$ and $(m+n)\cdot{p}=(m\cdot{p})+(n\cdot{p})$ (Axiom of distributivity).

This axiom is what allows you to say things such as $2\cdot2=2\cdot(1+1)=2\cdot1+2\cdot1=2+2=4.$ With this, we are now prepared to get a deeper understanding of what it means to "divide" two numbers, and how that results in division by $0$ not being possible. Notice, for example, that the fractions $\mathbb{Q}$ have a $+$-identity we call $0,$ and a $\cdot$-identity we call $1,$ and $1$ has a $+$-inverse we call $-1.$ In other words, $(\mathbb{Q},+)$ forms a group with identity element $0,$ and $(\mathbb{Q},1)$ forms a magma with identity element $1,$ and the two magmas are linked together by the axiom of distributivity. This linkage of the two binary operations is what allows us to do basic arithmetic, and other forms of mathematics. However, this linkage also makes it impossible for $(\mathbb{Q},\cdot)$ to be a group, because $0$ has no $\cdot$-inverse. With the group axioms of $(Q,+)$ and the axiom of distributivity, and no other assumptions, it can be proven that $0$ is an absorbing element of $(\mathbb{Q},\cdot),$ so unless you allow $0=1,$ you can never have some $m\in\mathbb{Q}$ such that $0\cdot{m}=m\cdot0=1.$ To put it more formally:
Theorem: if $(\mathbb{Q},+)$ is a group with identity element $0$ and $(\mathbb{Q},\cdot)$ is a magma with identity element $1,$ and the two magmas are linked by the axiom of distributivity, then $0\cdot{m}=m\cdot0=0.$
Proof: since $0$ is the additive identity, it follows that $0=0+0.$ Therefore, $0\cdot{m}=(0+0)\cdot{m}.$ By the axiom of distributivity, $(0+0)\cdot{m}=0\cdot{m}+0\cdot{m},$ hence $0\cdot{m}=(0\cdot{m})+(0\cdot{m}).$ Now, remember that $(\mathbb{Q},+)$ is a group, and thus, satisfies the axiom of invertibility, which implies $0\cdot{m}+n=0$ for some $n\in\mathbb{Q}.$ Therefore, $(0\cdot{m})+n=[(0\cdot{m})+(0\cdot{m})]+n.$ By the axiom of distributivity, $[(0\cdot{m})+(0\cdot{m})]+n=(0\cdot{m})+[(0\cdot{m})+n]=(0\cdot{m})+0=0\cdot{m},$ so $(0\cdot{m})+n=0\cdot{m},$ but $(0\cdot{m})+n=0,$ so $0=0\cdot{m}.$ The prof for $0=m\cdot0$ is completely analogous, and is left as an exercise to the reader.
Since $0\cdot{m}=m\cdot0=0$ for every $m\in\mathbb{Q},$ we can immediately conclude that $0$ has no multiplicative inverse, no $\cdot$-inverse. We do not need to know anything else about $(\mathbb{Q},\cdot)$ to know this. Why does this matter, though? Why do we care about $0$ having no multiplicative inverse? Well, because the "operation" we call "division" is actually a form of multiplication: it is a shorthand for writing multiplication by the inverse. Explicitly, $\frac{x}{y}:=x\cdot{y^{-1}},$ where $y^{-1}\cdot{y}=y\cdot{y^{-1}}=1.$ Therefore, whenever you write the expression $\frac{x}0,$ you are actually writing a shorthand for $x\cdot0^{-1},$ where $0^{-1}$ denotes the multiplicative inverse of $0:$ the quantity $y$ such that $0\cdot{y}=y\cdot0=1.$ But we just established no such a quantity exists, and such a quantity can never exist, because of the above theorem. Even if we extended the rational numbers to a new class of numbers, say $\mathbb{S},$ if we want to keep $(\mathbb{S},+)$ as a group, and if we want to keep the axiom of distributivity, then $0\cdot{m}=m\cdot0=0$ will remain true in this new structure. So applying the approach of extending to new structures does not work, because of the theorem. As such, the expression $\frac{x}0$ is just meaningless. It is not allowed in our mathematical vocabulary, it is the equivalent of gibberish.

Now onto talking about $0^0.$ Here, it is important to first establish what the symbol $x^n$ is intended to mean. For a second, let us assume that $x\in\mathbf{X},$ where $(\mathbf{X},\cdot)$ is a magma satisfying the axiom of identity element and the axiom of associativity. Then the expression $x\cdot{x}$ is well-defined. Also, $x\cdot(x\cdot{x})=(x\cdot{x})\cdot{x},$ so when we use the notation as a shorthand $x\cdot{x}\cdot{x},$ there is no danger of the expression being ambiguous. In other words, associativity gives us that $x\cdot{x}\cdot{x}$ is well-defined, and the same goes for expressions such as $x\cdot{x}\cdot{x}\cdot{x}$ and $x\cdot{x}\cdot{x}\cdot{x}\cdot{x},$ and so on.
Notice how the above products can get very tedious to write down as the number of multiplications applied increases. So mathematicians devised a notation that would allow us to abbreviate such expressions. The notation that they ultimately settled on is $x^n.$ So we can say $x\cdot{x}=x^2,$ and $x\cdot{x}\cdot{x}=x^3,$ and $x\cdot{x}\cdot{x}\cdot{x}=x^4,$ and $x\cdot{x}\cdot{x}\cdot{x}\cdot{x}=x^5,$ and so on. This is very much a non-rigorous definition, but if $n\geq2,$ then $x^n$ denotes an expression $x\cdot{x}\cdots{x}$ where there are $n$ occurrences of $x$ in the expression.
One issue you already have encountered at this point, is that the notation does not accommodate for $n=1$ or $n=0,$ which is inconvenient, since in mathematics, it is extremely common to index things with the set $\mathbb{N}=\{0,1,2,3,..\}.$ So we would like for the notation $x^1$ and $x^0$ to also be meaningful. But the problem is that multiplication $(\cdot)$ is a binary operation: it takes pairs of inputs. There is no meaningful sense in which I can talk about $\cdot$ taking a single real number $x$ as an input, for example. So it is evident that if we want $x^1$ and $x^0$ to be meaningful expressions, then we need to change our definition of $x^n.$
Notice, though, that the axiom of associativity has been assumed to hold in this case. So we the expression $x\cdot{y}\cdot{z}$ is not ambiguous: it does not matter whether we interpret it as $(x\cdot{y})\cdot{z}$ or as $x\cdot(y\cdot{z}),$ since $(x\cdot{y})\cdot{z}=x\cdot(y\cdot{z}).$ So here is what we can do: to make things rigorous, we can define a function $\bullet_3$ such that $\bullet_3(x,y,z)=x\cdot(y\cdot{z})=(x\cdot{y})\cdot{z}.$ Similarly, you can define $\bullet_4(w,x,y,z)=w\cdot(x\cdot(y\cdot{z})),$ and so on. Actually, while we are at it, why not define $\bullet_2(x,y)=x\cdot{y}$? With this, we now have that $$\bullet_m(x_0,x_1,...,x_{m-1})\cdot\bullet_n(x_m,x_{m+1},...,x_{m+n-1})$$ $$=\bullet_{m+n}(x_0,x_1,...,x_{m-1},x_m,x_{m+1},...,x_{m+n-1})$$ for $m,n\geq2.$ This encodes the fact that $(x_0\cdot{x_1}\cdots{x_{m-1}})\cdot(x_m\cdot{x_{m+1}}\cdots{x_{m+n-1}})=x_0\cdot{x_1}\cdots{x_{m+n-1}}$ formally, but the advantage of this is that $\bullet_n$ is systematically defined as a function whose input is an $n$-tuple, an ordered collection of $n$ objects. So if we can get around to defining $\bullet_1$ and $\bullet_0,$ functions with a single input, and no input, respectively, then we may be able to define $x^1$ and $x^0.$ To do this, we simply need to use the recursion given to us above. It amounts to having $$\bullet_n(x_0,x_1,...,x_{n-1})\cdot\bullet_1(x_n)=\bullet_{n+1}(x_0,x_1,...,x_{n-1},x_n)$$ and $$\bullet_n(x_0,x_1,...,x_{n-1})\cdot\bullet_0()=\bullet_n(x_0,x_1,...,x_{n-1})$$ for all $x_0,x_1,...,x_n\in\mathbf{X}.$ From here, it is straightforward to see that $\bullet_1(x)=x$ and $\bullet_0()=1.$ This allows us for a rather direct definition of $x^n.$ We say $$x^n:=\bullet_n(x,x,...,x).$$ Now, it is easy to see that $x^1=\bullet_1(x)=x,$ and this is true for every $x\in\mathbf{X}.$ Similarly, $x^0=\bullet_0()=1$ is true for every $x\in\mathbf{X},$ So if $0\in\mathbf{X},$ then it follows that $0^0=1.$
So with all of that being said, why is it taught by many teachers and why is it said by so many sources on the Internet that $0^0$ is undefined? The reason has to do with a misunderstanding of a concept in calculus. For this, we must talk about limits. Unfortunately, explaining in detail what a limit is would make my answer unacceptably long, probably twice as a long as it already is. So the rest of my answer is going to proceed with the assumption that you know what a limit is and how it works. If you have not been sufficiently exposed to the topic of limits, then I would suggest that you first try to get educated on that subject separately, and then you come back to the question of why people say $0^0$ is undefined later, at an appropriate level of understanding.
Firstly, it should be noted that in the context of calculus, the notation $a^b$ is used ambiguously and inconsistently. I spent several paragrphs telling you that $a^b=\bullet_b(a,a,...,a)$ for $a\in\mathbb{N}.$ But the notation $a^b$ in calculus is also used to abbreviate the expression $\exp[\ln(a)\cdot{b}],$ where the function $\exp$ is defined as satisfying a certain equation. Unfortunately, it is also common to write $\exp(x)$ as $e^x,$ hence the origin of the inconsistency and ambiguity with the notation.
With this usage of the notation, $0^0$ is indeed undefined, since $\ln(0)$ is undefined. But since we are talking calculus here, there is some hope that one can use limits to define $0^0.$ So we consider two sequences $a_n$ and $b_n,$ such that they both have $0$ as their limit, and then we consider the sequence $c_n=a_n^{b_n}=\exp[\ln(a_n)\cdot{b_n}],$ and look at whether it converges. It turns out that it can be proven that every positive real number is a possible limit for $c_n$ in this case. Therefore, it is not necessarily the case that $c_n=a_n^{b_n}$ will converge to $1$ if $a_n,b_n$ converge to $0.$ To put it succinctly, $$\lim{a_n}^{b_n}\neq[\lim{a_n}]^{[\lim{b_n}]}.$$ The reason this happens is because $$\lim\ln(a_n)\cdot{b_n}\neq[\lim\ln(a_n)]\cdot[\lim{b_n}],$$ since $a_n\to0$ means $d_n=\ln(a_n)$ diverges, and so $\lim{d_n}$ does not actually exist. This fact is often spelled out by teachers in classroom or on the Internet by the words "$0^0$ is an indeterminate form."
The argument there is that continuity therefore cannot be used to define $0^0,$ so it is undefined. However, there are immediately problems with this line of reasoning. For one, the definition $a^b:=\exp[\ln(a)\cdot{b}]$ is generally problematic, and it leads not only to $0^0$ being undefined, but it also leads to things such as $(-1)^2$ being undefined, since $\ln(-1)$ is also undefined, and using complex numbers would not be helpful since the complex logarithm is not well-defined. In fact, the above definition necessitates that $a\gt0$ be satisfied. For two, the above line of reasoning with two sequences is not the correct way to try to exploit limits to define $0^0.$ The reason there are any problems with $0^0$ under this definition at all is because $\ln(0)$ is undefined. So the simplest solution is to have $$a^b=\lim_{x\to{a}}\exp[\ln(x)\cdot{b}].$$ This immediately solves the problem: $0^0=1$ under this definition, and $0^x=0$ for all $x\gt0.$ Sadly, this does not solve the problem for $(-1)^2$ as mentioned above, but this is irrelevant.
Many people object to the above by saying that $x\mapsto0^x$ would be discontinuous at $0$ with the above, so $0^0$ would still be undefined by the above definition. But this argument relies on misunderstanding what continuity is. A function can be defined at a point and not be continuous at that point. In fact, by definition, a function can only be continuous or discontinuous at a point if said point is in its domain.
Finally, I should note that while most people on the Internet will die on the hill that $0^0$ is undefined, when you look at the mathematical literature (by this, I mean, the collection of written works published at reliable scholarly journals of mathematical research), you will encounter $0^0=1$ treated as a fact far more often than you will encounter $0^0$ being left as undefined. It really is not that important of an issue, though, as it ultimately boils down to a problem with inconsistent usage of notation, rather than to any particular mathematical theorem. Take that as you will.
I will not address the other questions you had regarding fractional exponents, since you can already find plenty of in-depth answers in MSE for those, and in my opinion, exponent notation should be reserved for integer exponents anyway. My answer would become unreadably long otherwise (if it is not already).


Proof that intervals of the form $[x, x+1)$ or $(x, x+1]$ must contain a integer.

Question: Show that any real interval of the form $[x, x+1)$ or $(x, x+1]$ must contain a integer.
Here is my proof (by contradiction)
We start by saying, assume the interval of the form $[x, x+1)$ or $(x, x+1]$ does not contain a integer. Now suppose $x$ is an element of $\mathbb{Z}$, then x is in the interval $[x, x+1)$ and since $x$ is an integer, then $x+1$ must also be an integer.  Thus $(x, x+1]$ must also contain a integer. This is a contradiction, it contradicts our assumption.  Therefore the statement is true.
Can someone help me on this.  Thanks in advance.
Comment: Hint: euclidean algorithm.
Answer: These two statements are equivalent:

$[x, x+1)$ or $(x, x+1]$ always contains an integer
$[x, x+1]$ always contains an integer.

For the proving, we can suppose, that $x \notin \mathbb{Z}$(otherwise $x$ is a trivial solution). Then, we can find an $y$, such that, $y > x, y \in \mathbb{Z}$. Take the following set: {$y \in \mathbb{Z}, y > x$}. Since this set is bounded from below(and obviously not empty), it must have a minimal element, let this element be $m$.
We prove, that $m \in [x,x+1]$.
Since $x \notin \mathbb{Z},  |m-x| < 1$. Therefore, $m \in [x,x+1], m \in \mathbb{Z}$. QED.
Comment: Question is $m \in [ x, x + 1 )$, not $ m \in [x, x + 1 ]$.

Note that $2 \in [ 2, 3 ]$ but $3 \in [ 2, 3 ]$, while $2 \ne ( 2, 3 ]$ and $3 \ne [ 2, 3 )$.

In this context $[ x, x + 1 )$ or $ ( x, x + 1 ]$ is not the same as $[ x, x + 1 ) \cup ( x, x + 1 ]$

But still an upvote!!! :)
Comment: If $x$ is an integer, the question is trivial, so we don't need to discuss that, in other cases, that won't happen. But you are right, thanks.
Answer: As you've observed, if $x$ is an integer, then so is $x+1$, so in that case we are done. Otherwise let $n$ be the smallest integer such that $n>x$, which must exist because there are integers greater than $x$ and the interval $(x,\infty)\cap\mathbb Z$ is well ordered. I claim that $n<x+1$. If this were not true then we'd have $n-1>x$, contradicting the choice of $n$. Thus $n\in (x,x+1)$ and we are done.
Comment: @Abhi no problem.
Comment: Sorry, I did not read your post before giving my answer; mine seems a bit like a re-wording of your answer.
Comment: @Gary it doesn't seem that way to me. In any case, no harm done.
Answer: Note that
$$ 0 \le \{ x \} < 1,$$
where $\{ x \}$ is the fraction of $x$, thus $\{ x \} = x - \lfloor x \rfloor$, and $\lfloor x \rfloor$ is the floor of $x$.

Thus
$$0 \le x - \lfloor x \rfloor < 1,$$
or
$$x \ge \lfloor x \rfloor > x - 1.$$
Therefore
$$\lfloor x \rfloor \in ( x - 1, x ],$$
but also
$$\lfloor x+1 \rfloor \in ( x, x + 1 ],$$
and $\lfloor x+1 \rfloor$ is an integer.

But we also have
$$0 \le - x - \lfloor - x \rfloor < 1,$$
or
$$x \le - \lfloor - x \rfloor < x + 1.$$
Therefore
$$- \lfloor - x \rfloor \in [ x , x + 1 ),$$
and $- \lfloor - x \rfloor$ is an integer.

So there is always an integer element of either $ [ x, x + 1 ) $ or $ ( x, x + 1 ]$.
Comment: The part that you assume (before the horizontal line) requires proof. If you try prove it you'll notice that it's essentially what you are trying to prove in the first place.
Comment: Reformulation of @MattSamuel's comment: How would you even define the fractional-part function if you didn't already know what the OP is trying to prove?
Answer: Assume $[x,x+1)$ does not contain an integer. Then $x$ is not an integer and neither is $x+1$. Then $[x,x+1]$ does not contain an integer. Assume WOLG, that $x=0.a_1a_2...$ , i.e., $x>0$. Then we must have $x+1 <1 $ (otherwise there would be an integer in the interval). But $x>0$ , so $x+1>1$, so there must be an integer in the interval. Similar argument for $(x,x+1]$.
Answer: You have proved the statement only for $x\in\Bbb Z$.
If $x\notin\Bbb Z$, consider the set $A=\{t\in\Bbb Z: t>x\}$. This set is bounded below and not empty, and it is well-ordered. Let $n=\min A$. Try to prove that $n$ is in the interval.
Perhaps you should also visit this question.


pm-update fails "sh: --backend=2: command not found"

Question: The pm-download command is working so I can update modules individually, but I can't do it in bulk. Both drush 6.2.0 and 6.1.0 give an error.
The output of drush up --debug is the following.

Bootstrap to phase 0. [0.01 sec, 2.24 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drush() [0.01
  sec, 2.37 MB] [bootstrap] Cache HIT cid:
  6.2.0-commandfiles-0-da12a99782b48770f5d9ad8965ca5448 [0.02 sec, 2.39 MB]           [debug] Bootstrap to phase 0. [0.09 sec, 6.4 MB]
  [bootstrap] Bootstrap to phase 6. [0.14 sec, 6.4 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_root()
  [0.14 sec, 6.41 MB]                     [bootstrap] Initialized Drupal
  7.24 root directory at /path/to/site [0.16 sec, 7.43 MB]    [notice] Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.16 sec, 7.44
  MB]                     [bootstrap] Initialized Drupal site default at
  sites/default [0.16 sec, 7.44 MB]
  [notice] Cache HIT cid:
  6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.16 sec, 7.45 MB]          [debug] Cache HIT cid:
  6.2.0-commandfiles-2-699657487b88e8b0c2ede2984aa12913 [0.16 sec, 7.45 MB]           [debug] Drush bootstrap phase :
  _drush_bootstrap_drupal_configuration() [0.17 sec, 7.47 MB]            [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_database()
  [0.17 sec, 7.51 MB]                 [bootstrap] Successfully connected
  to the Drupal database. [0.17 sec, 7.51 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_full()
  [0.18 sec, 8.14 MB]                     [bootstrap] Cache HIT cid:
  6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.37 sec, 26.15 MB]         [debug] Cache HIT cid: 6.2.0-commandfiles-5-8aee30ce3a469e89d0725cfb79ceb51b [0.37 sec, 26.16 MB]          [debug] Drush bootstrap phase :
  _drush_bootstrap_drupal_login() [0.38 sec, 26.62 MB]                   [bootstrap] Successfully logged into Drupal as Guest (uid=0) [0.38
  sec, 26.63 MB]                          [bootstrap] Found command:
  pm-update (commandfile=pm) [0.38 sec, 26.63 MB]
  [bootstrap] Calling hook drush_pm_update [0.71 sec, 26.97 MB]
  [debug] Loading release_info engine. [0.9 sec, 29.07 MB]
  [notice] Loading version_control engine. [0.9 sec, 29.17 MB]
  [notice] Loading package_handler engine. [0.91 sec, 29.19 MB]
  [notice] Executing: wget --version Including
  /usr/local/Cellar/drush/6.2.0/libexec/commands/pm/updatecode.pm.inc
  [0.93 sec, 29.21 [bootstrap] MB] Calling hook
  drush_pm_updatecode_validate [0.94 sec, 29.31 MB]
  [debug] Returned from hook drush_pm_updatecode_validate [0.94 sec,
  29.31 MB]                               [debug] Calling hook drush_pm_updatecode [0.94 sec, 29.32 MB]
  [debug] Cache HIT cid:
  6.2.0-alias-path--2c8463220c4fed24dfb54242bc0f682e [0.94 sec, 29.36 MB]             [debug] Backend invoke:   --backend=2 --verbose
  --debug --root=/path/to/site          [command]
  --uri=site.local  pm-updatestatus 2>&1 [1.26 sec, 29.37 MB]   --backend=2 --verbose --debug --root=/path/to/site --uri=site.local            [notice] pm-updatestatus 2>&1 [1.26 sec, 29.38 MB] Illegal string
  offset 'site' backend.inc:1013 [1.27 sec, 29.38 MB]
  [warning] The command could not be executed successfully (returned:
  sh: --backend=2: command not found   [error] , code: 127) [1.27 sec,
  29.38 MB] Returned from hook drush_pm_updatecode [1.27 sec, 29.36 MB]                                        [debug] Changes made in drush_pm_updatecode have been rolled back.
  [1.27 sec, 29.37 MB]                 [rollback] Command dispatch
  complete [1.27 sec, 29.34 MB]
  [notice] Returned from hook drush_pm_update [1.28 sec, 27.27 MB]
  [debug] Command dispatch complete [1.28 sec, 27.24 MB]
  [notice]  Timer  Cum (sec)  Count  Avg (msec)   page   1.113      1
  1113.33 Peak memory usage was 31.64 MB [1.28 sec, 27.24 MB]                                               [memory]

The issue happens under OS X Mountain Lion and PHP 5.4.20, and continued after upgrading to Mavericks.
Answer: This is happening because Drush is trying to find the local Drush executable via $drush = realpath($_SERVER['argv']['0']);.  In this context, realpath is returning FALSE, because $_SERVER['argv']['0'] does not exist.
As a workaround for this particular problem (which is that pm-update cannot call updatedb), you could run drush pm-updatecode followed by drush updatedb.
Note
If you work around the problem instead of solving it, you will also run into this same issue with other commands, such as sql-sync.
Comment: This is on a local install, it happens when using an alias or when running from the drupal directory.
Comment: Run the command again with the --debug flag; show the full command you are running, and all of the output. Also, please specify your php and Drupal versions, and what O.S. you are running on.  Drush shouldn't be including --backend=2 unless you are using a site alias with a 'remote-host' entry set, so the results you are seeing are unexpected.
Comment: Thanks for taking the time to help greg, I added the info to the OP.
Comment: I'm not sure why Drush can't find your executable. You could try to diagnose this via `drush ev 'return $_SERVER["argv"]["0"];'`
Comment: `drush ev 'return $_SERVER["argv"]["0"];'` returns `'/usr/local/Cellar/drush/6.2.0/libexec/drush.php'`
Comment: `drush pm-updatecode` gives the same error as `drush up`: `The command could not be executed successfully (returned: sh: --backend=2: command not found`.
Comment: I don't know; it shouldn't be doing that, and does not behave that way on any system that I've observed.  You're going to have to do more debugging to find out why you are getting different results.
Comment: It's now working again after I set the path to the local drush binary under %drush-script in the aliases. Should that be necessary?
Comment: No, it should not be necessary. If you set %drush-script to an empty string, that might explain the symptoms you are seeing above. Since you've found a workaround, I'd go with it.
Comment: That solved it, I deleted the %drush and %drush-script aliases for my local server from the drushrc.php file. Thanks!
Comment: I ran into this on my local and stopping and then restarting MySQL resolved it.
Answer: I used drush pm-updatecode --debug from inside the Drupal root and it shows the failure. I think drush can't find out where it is. The first line of the output is this:
    "C:\Users\dj\AppData\Roaming\Composer\vendor\drush\drush\drush"
    --backend=2 --verbose --debug --root="E:\DJs
Documents\public_html\Drupal_80" --uri=http://default
The "default" seems to be the problem.
Also,
drush ev 'return $_SERVER['argv']['0']);'

returned nothing (no error either).


Help with formula for audio mixing

Question: I have $2$ formulas (mentioned in this page):
http://www.vttoth.com/digimix.htm

$Z = 2AB$ if both $A<0.5$ and $B<0.5$
$Z = 2(A+B) – 2AB – 1$ otherwise

where $A$ and $B$ are numbers between $0$ and $1$ (including $0$ and $1$) eg:
$0$
$0.2$
$0.9$
$0.34$
$1$
Now, I can understand formula $1$ (if $A$ and $B$ are BOTH greater than $0.5$, then $Z$ is $2AB$, right?)
What I can't understand is the part from the second formula that reads $2(A+B)$:
Add $A$ with $B$ and then multiply by $2$ : $2\cdot(A+B)$
is this correct or am I missing something?
Any help?
Comment: It says $Z=2AB$ if $A$ and $B$ are both *less* than $0.5$.
Comment: That's correct, my mistake!
Comment: Side note: the usual solution to mixing audio (and other effects) is to perform intermediate calculations at a greater resolution, then dither on the way back down to the desired output range. For instance, the Pro Tools mix engine uses 48-bit fixed-point arithmetic internally.

Multiplying the signals seems... weird.
Answer: Your description of the evaluation of $2(A+B)$ is correct: first add $A$ and $B$, then multiply by $2$. Since you didn't write why you think you may be missing something there, it's hard to say more about that.
However, your description of the first formula is incorrect. The symbol $<$ denotes the relation "less than", not "greater than".
Comment: I wouldn't spend too much time looking for mistakes in your implementation -- I'd be surprised if this formula leads to sensible audio mixing. The multiplication should lead to artefacts. You speak of attenuation -- it's my understanding of the description that the whole point of this unconventional approach is to attenuate one signal when the other one is present, so I don't think this in itself should be cause for concern. Regarding $2\cdot A\cdot B$: yes, this is equivalent to $2(A\cdot B)$.
Comment: I said that I think I'm missing something because the output audio is not sounding right. There's some attenuation in the first group of samples (A), that are mixed with the second group (B). Also in the fist formula there's  2*A*B Is this the same as writing 2(A*B) ?
Comment: @André: I don't understand. Both the question and the page it links to say $Z=2(A+B)-2AB-1$. Where is $Z=2AB-2AB-1$ coming from?
Comment: @joriki: Mistyping, of course.

Help with formula for audio mixing


Question about sums of Gasussian Mixture models

Question: This question is strongly based on the result given in HERE
Due to some research I am currently conducting, I've found myself in a situation, where I deal with mixtures of gaussian densities, called Gaussian Mixture Models, or GMM for short (mixtures of gaussian densities, with the constraint that weights in a mixture sum to 1). At some point, I've begun to wonder whether or not a sum of GMM's will still be a GMM. Then I've stumbled upon the above reasoning. Based on that we can see that
$Z=X+Y$, where $X=\sum_{i=1}^N \pi_i \mathcal{N}(x;\mu^X_i,\Sigma^X_i)$ and $Y=\sum_{j=1}^N \phi_j \mathcal{N}(x;\mu^Y_j,\Sigma^Y_j)$ (*)
will be a new mixture distribution with $N^2$ component (where both $X, Y$ has $N$ components), the weights are the products of the old weights $\pi_i\phi_j$, and the distribution of the component $(i,j)$ is the distribution of the sum of independent random variables $X_i+Y_j$. So expanding that we are dealing now with:
$$Z=\sum_{i=1}^N\sum_{j=1}^N\pi_i\phi_j(\mathcal{N}(x;\mu^X_i,\Sigma^X_i)+\mathcal{N}(x;\mu^Y_j,\Sigma^Y_j))=
\sum_{i=1}^N\sum_{j=1}^N\pi_i\phi_j\mathcal{N}(x;\mu^X_i,\Sigma^X_i)+\pi_i\phi_j\mathcal{N}(x;\mu^Y_j,\Sigma^Y_j)$$
Now when we skip density parts, we can easily see that we have twice the sum of $\pi_i\phi_j$, where each of those sum to $1$, so in total our new weights sum to $2$. Of course we can generalize it to the sum of $M$ such models, which yields us a mixture model, where weights sum to $M$. Due to that, I have two questions:

Is this still a random variable as is? What I mean by that, is whether or not this new creation requires some normalization constant to be in $[0,1]$ interval. Based on that it seems to me, that normalization (by multiplication by $\frac{1}{M}$ where $M$ is the number of mixture components in sum) is strongly required, but I may be wrong. If yes, then this will again boil down to the new GMM model, which we can work on easily, with well-known techniques, if I am correct.
If not, is there a way to still use theory and properties/algorithms connected with regular GMM's with such creation? Structure of it seems to be very similar, if not the same, if we disregard constraint on weights summation. Due to that, it seems to be a pretty straightforward idea, to just normalize the weights and still use well developed and well-known techniques, but will it hold, theoretically?

(*) Note that here, we denote by $\mathcal{N}(x;\mu^Y_j,\Sigma^Y_j)$ we denote the density function of a multivariate gaussian variable, with mean $\mu_j^Y$ and covariance matrix $\Sigma_j^Y$
Answer: I think there may be a confusion in your reasonning.
When you write that $X = \sum_i \pi_i \mathcal{N}(\mu^X_i, \Sigma^X_i)$ you actually mean that the density of $X$ is a weighted average of normal densities :
$f_X = \sum_i \pi_i \varphi_{\mu^X_i, \Sigma^X_i}$.
But when you write that $Z = X + Y$ you mean that the random variable $Z$ is the sum of $X$ and $Y$ (thus the density of $Z$ is the convolution product of the densities of $X$ and $Y$)
When you write that $Z = \sum_i \sum_j \pi_i \phi_j (\mathcal{N}(\mu^X_i, \Sigma^X_i) + \mathcal{N}(\mu^Y_j, \Sigma^Y_j))$ the two uses of the summation are mixed. The $\sum_i ...$ refers to the summation of densities when the "$+$" between the $\mathcal{N}(...)$ refers to summation of random variables (and could be replaced by a convolution product).
So, from $Z = \sum_i \sum_j \pi_i \phi_j (\mathcal{N}(\mu^X_i, \Sigma^X_i) + \mathcal{N}(\mu^Y_j, \Sigma^Y_j))$ you get that, if the mixtures components of X and Y are independent,
$$Z = \sum_i \sum_j \pi_i \phi_j (\mathcal{N}(\mu^X_i + \mu^Y_j, \Sigma^X_i + \Sigma^Y_j)$$
which is a mixture with $N^2$ components, and $\sum_i \pi_i \phi_i =1$ so all is good.
So a sum of mixture of gaussian is a mixture of gaussians if the sum of any component of $X$ and any component of $Y$ is still gaussian. In particular, this is the case when there are independent.
Comment: Okay, that's quite a lot to unwrapping here, especially, as those terms seem to still overlap in my mind, so sorry for unnecessary confusion made by that. Firstly thanks for your great answer, secondly let me know if now I understand that correctly:
convolution product (sum of) rv's X,Y whose densities are weighted averages of normal densities yields rv Z, whose density is also weighted average, and it's component densities are $\mathcal{N}(\mu^X_i + \mu^Y_j, \Sigma^X_i + \Sigma^Y_j)$ with weight $\pi_j\phi_j$, given that the mixture components in both rv's are mutually independent.
Comment: Yes that is correct.
The assumption of indepedency between components of $X$ and $Y$ is sufficient, but not necessary, it could be a little bit restrictive...