Laravel 5.8 - Specified type Model for route paramteters

Question: I have a routing conflict issue in my Laravel application (version 5.8).
Here are the 2 routes that are problematics :
Route::post('/projets/{projet}/{redirect}','ProjetController@update')->name('projets.update');
Route::post('/projets/export/excel', 'ProjetController@exportExcel')->name('projets.exportExcel');

The first parameter "projet" is supposed to be a Model Object "Projet" and "redirect" is a String.
But i don't have specified the type of these parameters and i would like to know if someone have an idea on how i can specified that the "projet" parameter is an Object "Projet" (if this is possible ?).
Thanks in advance
Comment: Wildcard routes need to come after any other route that might match it.
Comment: @aynber yes i have change the routing configuration like you say, it works fine now thanks ! And do you if this is possible to specify the type Model Object for a routing parameter ?
Answer: I think, in your ProjetController update method you can use this signature:
public function update(Request $request, App\Projet $projet, string $redirect){
   // Use posted values with $request Object,
   // Use $projet model
   // Use $redirect string

}

And you can explore details in documentation.
Comment: hi thanks for your answer, already done : `public function update(ProjetRequest $projetRequest, Projet $projet,String $redirect)` but wasn't working with this...
Comment: What about your parameters? Can you show us your request url?
Comment: Thanks for your answers, the issue is solved now, the problem came from the routing conflict configuration.


Best fit with GLM in R

Question: I'm trying to know what is the best GLM fit with this simple dataset and tests in R:
a=c(1.168668,1.467459,1.357719,1.253049,1.205406,1.395816,1.302802,1.268686,1.257424,1.155373,1.049089,1.077470);
b=c(0.664,0.523,0.511,0.558,0.603,0.644,0.480,0.561,0.562,0.686,0.651,0.623);
c=c(0.699,0.585,0.573,0.602,0.660,0.666,0.566,0.627,0.638,0.699,0.706,0.672);
r=c(1,2,3,4,5,6,7,8,9,10,11,12);

dataset <- data.frame(a,b,c,r)

#First test
mfit0 <- glm(data=dataset,formula=a~b/c);

#Second test
mfit1 <- glm(data=dataset,formula=a~b);

mfit0 summary returns:
Deviance Residuals:
      Min         1Q     Median         3Q        Max
-0.131345  -0.018809  -0.003038   0.038533   0.119793

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.2754     0.8713  -0.316   0.7591
b             8.2938     3.6341   2.282   0.0484 *
b:c          -8.8360     3.3800  -2.614   0.0281 *

Null deviance: 0.170905  on 11  degrees of freedom
Residual deviance: 0.060651  on  9  degrees of freedom
AIC: -21.396

and mfit1 summary returns:
Deviance Residuals:
     Min        1Q    Median        3Q       Max
-0.12962  -0.03927  -0.01512   0.02112   0.21300

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.9272     0.2791   6.905 4.17e-05 ***
b            -1.1559     0.4712  -2.453   0.0341 *
    Null deviance: 0.17091  on 11  degrees of freedom
Residual deviance: 0.10671  on 10  degrees of freedom
AIC: -16.616

Then I try to apply a wald.test (Test of WALD), where:
mfit0:
chi2=16.36 and p-value=0.0003
mfit1:
chi2=6.01 and p-value=0.0142
So, What is the best model or what is the model fits it better?.
Is p-value from mfit0 and Wald test good o better than mfit1?.
Thanks in advance.
Comment: I do not understand your question since both models have different dependent variables and are therefore not comparable.
Comment: Ok, true ! Let me change
Comment: Why do you use a Gaussian GLM and not simply an OLS model?
Comment: @Roland, Im trying this model right now. Before I tried `lm` models, but I want to learn if glm works better for my small dataset.
Comment: No, a Gaussian GLM won't work better. Apart from the numerics (which can make it worse), the results should be identical.
Comment: So, @Roland , what do you recommend? Only a few values , could be not good .
Comment: You actual goal is not defined. Thus, there is nothing that can be recommended.
Comment: My goal roland is to know if `a` is modelled by  `b` or `b/c` , and if is `b` or `b/c` better for it, @Roland
Comment: Define "better". Apparently your actual goad is prediction?
Comment: Ok, call it prediction @Roland.
Answer: What exactly is your goal? Is it to assess the predictive ability of each model?
If it is, you could always try cross-validation. Or else split the dataset into training and testing data(70/30), and compare them. Although you'll need a bigger dataset to really see any sort of comparable difference I'd say
Comment: My goal are two: 1st: check if use `b` or `b/c` is better or not to define `a`. and 2nd: if can I predict the value (regression) of `a` with `b` or `c`

Best fit with GLM in R


Adobe Dynamic link between PremierPro and AfterEffects is not working

Question: When I work with video editing Adobe Premiere Pro CC 2014,when i right click on the video after adding the video to timeline ,I look for  replace with aftereffect composition but option is disabled .
I google for the solution the said to add the shortcuts of files in the dynamiclink folder which is in the path of C:\Program Files (x86)\Common Files\Adobe\dynamiclink but I do not find that folder.
So I made one like folder as they said and tried but that did not solve my problem.
Softwares I Use

Adobe After Effects CC 2015
Adobe Premiere Pro CC 2014

Hope I explained the problem in clear if not please mention in comments id you need any further information
Answer: Hey I also faced this problem,I found a solution in the youtube and I followed the following steps hope this helps you ,it worked for me but it may or may not works for you based on your configuration
The First feasible solution is as follows

Prepare shortcuts for the both softwares Adobe Premiere Pro cc
2014 & Adobe After Effects cc 2015 by going to their respective
folders in the desktop
Copy those shortcuts.
Look for dynamiclink folder in the directory C:\Program Files
x86\Common Files\Adobe\dynamiclink if the folder is not present
prepare one with the same name dynamiclink.
Now paste those shortcuts into the folder.
Now refresh and restart the application.

If problem persists again ,then the problem is due to incompatability of the versions you are trying to link dynamically.
Answer: Finally I figured the solution
When I Upgraded to Adobe Premiere Pro cc 2015 The Dynamic link is perfectly working
The problem is with the versions of development
Upgrade from

Adobe Premiere Pro CC 2014 to Adobe Premiere Pro CC 2015
Comment: That make sense, if the softs are not on the same version, there would be compatibility issues
Comment: @KevinM Ya you are absolutely right.But I do not know that before I just tried with latest version It worked finally.


Check if one of divs contains my values in nightwatch

Question: I have problem with testing my webapp with nightwatch.js. I need to iterate  over all div elements on the page to check if there is the one who contains all child elements I added before. For example I have:

 text1

 second_text1

 text2

 second_text2

And I want to check if one of divs contains both: 'text2' and 'second_text2'. I tried to add iter function like here: Assert text value of list of webelements using nightwatch.js but I don't know how to check child elements in this div and assert only if none of divs contains my values.
Answer: Unfortunately, nightwatch does not support promises or general asyncness very well. The blog post here summarises some of the pain points.
Fortunately, it is possible using a combination of browser.elements and browser.perform.
var assert = require('assert');

module.exports = {
    'foobar': function (browser) {
        var isTextFound = false;
        browser
            .url('http://localhost:3000')
            .waitForElementVisible('body', 1000);

        browser.elements('css selector', '.myclass', function (res) {
            res.value.forEach(function (jsonWebElement) {
                var jsonWebElementId = jsonWebElement.ELEMENT;
                browser.elementIdText(jsonWebElementId, function (jsonElement) {
                    var text = jsonElement.value;
                    if (text.indexOf('text1') !== -1 && text.indexOf('second_text') !== -1) {
                        isTextFound = true;
                    }
                });
            });
        });
        browser.perform(function () {
            assert.ok(isTextFound, 'Text found');
        });

        browser.end();
    }
}

Let's go through some of the key points
require('assert')
This is required because nightwatch asserts only operate on DOM elements and hence you can not assert a boolean. This also means that the assertion will not show up on the report, however if it is false, it will throw an error and this will come up.
browser.perform(function(){...})
This puts the assertion onto the command queue so that the assertion will happen afterwards. If this was not there, the evaluation will happen immediately and the assert will fail.
browser.elements('css selector, '.myclass', function(res){...})
This is using the elements api. Please note that the api under the webdriver protocol section do not return web elements directly but return the Selenium representation of web elements (WebElement JSON objects) and hence we have to use special methods such as elementIdText to get information out of them.


Why transpose at the octave?

Question:
If an instrument has a range too high or too low for composers to easily write its music on bass or treble clef, the music may be written either an octave higher or an octave lower than it sounds, in order to reduce the use of ledger lines. —Wikipedia

So I'm playing piano, and there's suddenly a passage where I need to play the notes written on the bass staff, but an octave lower. The notation for this is the bass clef, possibly ornamented with a written notation to play an octave lower.
Or I'm playing some instrument that normally plays in two octaves, one corresponding to the treble clef and the other an octave higher than the treble clef, and — both are written on treble clefs, one above the other??
This seems terribly confusing. Why not use another clef symbol, one that unambiguously indicates the correct octave? (I'm assuming such a symbol exists; if not, why not?)
Comment: Given the variety of content in each of the answers, I think the original question is a bit unclear.  Would you be able to edit your question to more clearly articulate what it is you are looking for?
Comment: The symbols actually exist. Beside the different C key positions (alto and tenor being most frequently used), see [octave-transposing keys](http://www.music.vt.edu/musicdictionary/text1-9/8.html). They are seldom used in favour of markings like 8va, the range either marked with a dashed line or a terminating loco.
Comment: Another method (possibly addressed by the Wikipedia) is simply by convention: Double bass and contrabassoon are notated like violoncello/basson, but sound an octave lower. Every player learns this, so there is no need to reflect it in notation.
Comment: @jjmusicnotes, done.
Comment: @msh210 - That's much clearer - I'm glad we were able to clear up the miscommunication.
Answer: There is a (modern) convention for representing octave shifts "at the clef":

an "8" above the clef is equivalent to "8va",
an "8" below the clef is equivalent to "8vb",

and applies throughout the piece.
Comment: Per a suggestion that I clarify my question, I've edited it. You might wish to have a look at the new version and see whether you wish to edit your answer.
Comment: Right, though this convention isn't all that widely adapted. Guitar is often written without an `8` below the violin clef, bass (be it electric– or double bass) almost always without the `8` below the bass clef, etc..
Comment: The proper indication to play an octave lower is _8_ or _8va_ placed below the note or notes in question.  Although it is popular, _8vb_ is nonsensical because the _a_ in _8va_ doesn't mean "higher."
Answer: It's not confusing as long as it's consistently done in a particular way for particular instruments whose players are used to the notation.
For example, classical guitarists don't care that when they play the middle C, what actually comes out of the instrument is the C below middle C.
It would be confusing if different pieces for the instrument, or different publications of the same music, had different conventions.
The differing conventions might be confusing to composers who write for many instruments. But (the composer hopes!) music is read and performed many more times than it is written, so the conventions of those who read are more important.
Comment: This makes sense, +1, and thanks, but what about instruments that only sometimes transpose, like the piano, whose bass clef sometimes means one octave down?
Comment: Per a suggestion that I clarify my question, I've edited it. You might wish to have a look at the new version and see whether you wish to edit your answer.
Answer: Alternative clefs have been proposed, but are not in common use. In the appendix of Rossing's The science of sound, there are clefs called the "super-treble" which is notated as two consecutive treble clefs, and the "supra-super-treble" written as three clefs, which indicate one and two octaves above standard treble clef, respectively. Similarly, there are extensions to the bass clef. Since other solutions are traditionally accepted (8va notation and C-clefs), there is really no reason to use Rossings unconventional notations.
To add to the confusion, I thought from the title of the question that I should mention the tritave that arises in the Bohlen-Pierce scale. In other words, why do we transpose at the octave, and not some other interval?
Comment: Per a suggestion that I clarify my question, I've edited it. You might wish to have a look at the new version and see whether you wish to edit your answer.
Comment: The program "Master Composer" for the Commodore 64 had treble and bass staves marked with the appropriate staffs, and also had a staff marked TR+ above the treble staff (line notes CEGBD reading up IIRC) and one marked BA- below the bass (CAFDB reading down).  I've never seen that notation elsewhere.  I would think having a staff marked with with two consecutive treble clefs reading an octave above a staff with one could be nice for handbell music, since such a staff could stack above a treble cleff with two ledger lines between.
Comment: The double treble clef has seen use in the past to indicate transposition down an octave (for tenor voice).  Further fuel for confusion.
Answer: Two aspects that have not yet been mentioned:

For a performer to sight-read music, the performer must know at a glance that e.g. a note on the top line is F, the top space is E, etc.  Examining the position of each note relative to e.g. the center of the C clef would be way too slow.  From a sight-reading standpoint, it's easier for most performers to deal with a smaller number of note assignments (e.g. just treble and bass clef) than to have some pieces where the top line is F, some where it's A, some where it's E, some where it's G, etc.)
In some cases, two instruments or vocalists that are told to play the same notes will in fact be expected to play an octave apart.  For example, when grown men and women are singing in unison, most of the men will usually sing an octave lower than most of the women.  Likewise, if a cello and string bass are given the same notes, the string bass will usually be expected to play them an octave below the cello.  There is thus a convention that, except when otherwise noted, male parts written for the treble clef, or string bass parts written for the bass clef, should be assumed to play an octave below what's written.

Note that it's common for male parts to be written "at pitch" using the bass clef; the use of the bass clef rather than the treble clef indicates that the part is being written assuming the men's lower range.  Since there isn't any common clef lower than the bass clef, however, one cannot very well use the clef to indicate object transposition or lack thereof for that instrument; music that wants something other than the standard octave transposition must include a directive saying so.
Comment: Lots of people learn to sight-read C clefs, and it used to be standard to learn at least soprano, alto, and tenor clef in addition to treble and bass.  It's not that hard.  But C clefs only help with parts that are lower than treble clef and higher than bass clef.  This question is asking about parts that are higher than treble or lower than bass.
Answer: There's a bit of confusion that I feel OP has with regard to the quote. The quote describes transposing instruments, who are always written higher or lower than they sound, and 8va and 8vb notation, which are temporary effects that displace music by an octave. The property of the instruments that transpose by an octave is not the same as just changing clef on, say, piano. 8va and 8vb notation can occur for almost any instrument, but is most commonly used in instruments for which playing something an octave higher or lower is not a matter of a whole new physical motion (ie. octave valves, pianos). Instruments that transpose at the octave (like guitar, bass, etc) are done this way specifically to avoid always having to write 8va and 8vb.
Comment: Sometimes it may make sense to interpret music as "transpose octaves ad lib".  Instruments like electric guitars vary in how well they can handle extremely high parts.  If a guitar solo goes up to C6 (actual pitch), it may sound really epic if played on some guitars, but on other guitars it might sound better if played an octave lower (with C5 as the top note) but passed through an "octave fuzz" pedal which doesn't really transpose up an octave, but would add a lot of even harmonics to the sound.
Comment: The proper indication to play an octave lower is _8_ or _8va_ placed below the note or notes in question.  Although it is popular, _8vb_ is nonsensical because the _a_ in _8va_ doesn't mean "higher."
Comment: @phoog IMO, "nonsensical" is a bit extreme. 8vb could plausibly represent "ottava bassa" (or "octave below"), where 8va has always been "ottava" for "octave". Yeah, that wasn't the *original* usage, but who's to say 8vb is improper when it tends to be more self-evident than the original method? Most signs in music don't differentiate between "above" and "below" placement; the original 8va method is a strange exception, where 8vb is a more typical pattern of differing symbols for "up/down" differentiation.
Answer: I feel this question could be re-phrased quite successfully. However, I think the answer lies in the other clef sign - called the C clef,  as used by, for example, viola players, which puts 'middle C' wherever the composer wishes - for example on the middle line of the five. This obviates the use of ledger lines, up or down, the pitch of the instrument is central to the clef sign.
Possibly the question is asking why not alternate and use different signs for the same instrument. This would be totally unnecessary . 8va etc.is more than adequate.To me when this is used, on the piano, it becomes a transposition. Only temporarily, though, unlike, say, a guitar, which actually uses a tiny 8 under the treble clef to show that the whole music is transposed by an octave.
The important factor is surely to use all of the staff to hang notes on for an instrument to play when reading, rather than needing to count up or down how many ledger lines are there. This is sorted for most instruments with a 3 or 4 octave range using one clef (treble or bass), and 8va /8vb signs. With a piano of 7 octaves, the problem is overcome using two clefs, AND 8va etc.
Comment: Per a suggestion that I clarify my question, I've edited it. You might wish to have a look at the new version and see whether you wish to edit your answer.
Answer: You can put an 8 on the clef to indicate that it is higher:

From https://www.freemusicdictionary.com/definition/octave-treble-clef/ :

A normal treble clef is said to be an "octave treble clef" when a number 8, or sometimes 8va, is placed above or below the clef symbol, which indicates to the musician to play an octave higher or lower. If the the number 8 (or 8va) is placed above the clef the musician is directed to play the notes an octave higher than they are written. If the number 8 (or 8vb) is placed below the the clef the musician is directed to play an octave lower than written.

Wikipedia, however, suggests that the clef is used to indicate that the note will sound higher than written due to the instrument:

To indicate that notes sound an octave higher than written, a treble clef with an 8 positioned above the clef may be used for penny whistle, soprano and sopranino recorder, and other high woodwind parts.
Answer:
This seems terribly confusing. Why not use another clef symbol, one that unambiguously indicates the correct octave?

This is only your opinion, or guess. What you are proposing is replacing one set of symbols with another set. Neither of them are actually ambiguous. The alternative can easily be just as confusing to someone, perhaps even yourself.
An annotation like └ ─ ─ ─ 8vb ─ ─ ─ ┘ under a group of notes clearly shows where the transposition begins and ends and it can be inferred to which notes it applies.
Clefs have their own problems: they change the letter note values of staff lines. In the standard treble clef, the lowest staff line is an E, whereas in the standard bass clef, it is a G. Clefs take up horizontal space and two are needed to indicate the temporary change and the return to the original clef.
Someone confronted with a clef change might complain of the confusion caused by the changing note values of the staff lines, and opine that it would be less confusing to have an octave transposition indicated over a range of notes instead.
No matter the notation, the performer's brain has to adjust to the staff lines temporarily having different absolute note values. I suspect that the source of your difficulty may be that adjustment, rather than the means by which it is indicated. Once you are in the middle of that passage, you have gone past the transposing indication and are reading the individual note values. If you are struggling at that point, it must actually be the altered semantics of the staff lines that is the problem. In your mind you have associated the staff lines with absolute positions on the piano keyboard and are reluctant to liberate them to refer to other octaves.
Reading through transpositions is just another reading skill that has to be practiced.
Comment: The proper indication to play an octave lower is _8_ or _8va_ placed below the note or notes in question.  Although it is popular, _8vb_ is nonsensical because the _a_ in _8va_ doesn't mean "higher."
Comment: @phoog Fixed. 8va just means *octava*, I'm guessing? I cribbed the 8vb from something I read here.

Why transpose at the octave?


Xcode 9 Swift 4 - Reposition views by dragging

Question: Im quite new to iOS development. But have years of programming experience.
Anyway, Im having a hard time finding a solution for my problem.
In my app i render rows of colored circles based on data from the server.
Each of these circles has different properties set to them on the server.
One of these is the "offset" property.
This should be used to render the circle with a distance from its left sibling, or the start of the parent view if its the first.
Each circle should then also be able to be moved by dragging it to the right or left. But never less then 0 from its left sibling.
In android this was very easy, just set the left-margin on drag, and all was good.
But in xcode im having a very hard time figuring out how to get this done.
Im sure its me thats way to inexperienced. So I hope someone that has a bit more knowledge about swift can help me with this.
Heres some images to make clear what Im looking to achive.
First render where one circle has an offset

The gesture where the 3. last circle is drages to the right

The result of the gesture

I need this to move seamless, so not reposiotioning after the gesture ends, but move along with the finger.
As you can see, the circles right of the one that is drages, keep their relative position to the one that is moved.
Thank you.
Comment: Btw, the offset unit is based on the width of a circle.
So offset: 1 means a left-offset of the same width as one circle, offset: 0.5 means a left-offset of half the width of a circle.
Answer: There are couples of ways to do this.The First possible solution can be using the Swipe gestures to move the objects.
override func viewDidLoad() {
    super.viewDidLoad()

    let swipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeGesture.direction = [.Down, .Up]
    self.view.addGestureRecognizer(swipeGesture)
}

func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
}

Use these Gestures to move along the objects with your fingers either you can use .left and .right gestures depending upon your need.

The Second solution for drag components can be a Pan Gesture

func detectPan(recognizer:UIPanGestureRecognizer) {
  var translation  = recognizer.translationInView(self.superview!)
  self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
}

The translation variable detects the new coordinates of the view when panning. The center of the view will be adjusted according to the changed coordinates.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
  // Promote the touched view
  self.superview?.bringSubviewToFront(self)

  // Remember original location
  lastLocation = self.center
}

When the view is clicked, the current view will be displayed in front of the other views and the center of the view will be assigned to the lastlocation variable
Hope this helps.


$k$ colorings of the non empty subsets of $[n]$ gives the same color to two disjoint sets and their union.

Question: This question was already asked but I didn't get enough information from the answer. Here is a link to the question.
Here is the question restated. Show that for $n$ large enough, every $k$ coloring of the non empty subsets of $[n]$ will give the same color to two disjoint sets and their union.
This is my idea so far. I want to choose $n=R_{k}(3:2)$. Defined to be the smallest $n$ such that any $k$ coloring of the edges of $K_{R_{k}(3:2)}$ yields a monochromatic triangle. Given any k-coloring $f$ on the powerset of $[n]$. Define an edge coloring $f'$ on $K_{n}$ by, $f'(ab)=f(\{a,b\})$.
This produces a monochromatic triangle. So there exists $a,b,c$ such that $\{a,b\},\{b,c\}\{a,c\}$ all have the same color. I was hoping to execute this sort of coloring on the two sets of $[n]$ then the three sets and so on until I have enough triangles to get some disjoint sets but it didn't work.
Any hint would be very nice. Thank you
Comment: @BrianM.Scott yes I wrote $f$ is a $k$-coloring on the powerset of $[n]$.
Comment: @BrianM.Scott yes correct. Changing now.
Answer: Define $f'(ab)=f(\{a+1,a+2,\dots,b\})$ for $0\le a\lt b\le n$. This colors the edges of a complete graph on $n+1$ vertices, so you can take $n=R_{k}(3:2)-1$.
Comment: Very Good hint. I would like twice if I could.
Answer: Ross's answer in that link gives you a big hint, here is a complete solution.
We prove by induction the existence of a $n_k$, and also get a recurrence relation for some $n_k$ which works.
For $k=2$ we have $n_2=9$ works.
Now, the inductive step:
$P(k)\Rightarrow P(k+1)$.
Define $n_{k+1}=(k+1)(2n_k-1)+1$. By the pigeon hole principle, there are at least $2n_k$ single elements sets which have the same color.
If any of the two corresponding $2$ elements sets have the same color, we are done. Otherwise, the corresponding two elements sets have $k$ colors.
Lets label the elements $x_1,...,x_{2n_k}$. Then we have $n_k$ pairs of elements:
$$A_1=\{x_1,x_2 \}, A_2= \{x_2,x_4 \},...., A_{n_k}=\{x_{2n_k-1}, x_{2n_k} \}$$
Now consider all the subsets of $[n_k]$, where a set $S \subset [n_k]$ is colored by the color of $\cup_{j \in S} A_j$.
Apply $P(S)$ and you are done: If $A,B$ are disjoint and $A,B$ and $A \cup B$ are colored with the same color, then
$$\cup_{j \in A} A_j \,;\, \cup_{j \in B} A_j$$ are disjoint and
$$\cup_{j \in A} A_j\,;\, \cup_{j \in B} A_j \,;\, \left[\cup_{j \in A} A_j \bigcup \cup_{j \in B} A_j \right]$$
have the same color.
An $n_k$ which works is given by
$$ n_2=9 \,;\, n_{k+1}=(k+1)(2n_k-1)+1 \,.$$
As
$$ n_{k+1}=(k+1)(2n_k-1)+1< 2(k+1)n_k \,.$$
you can prove by induction that
$$n_k < 9 \cdot 2^{k} \cdot (k!)$$
so $n \geq 9 \cdot 2^{k} \cdot (k!)$ for example works.


Retrieving Solidity Event Data with Ethers.js

Question: I'm new to Solidity and Ethers.js, so if there are any amateurish mistakes, that would be why.
I'm trying to build a dApp that runs a function on my smart contract, retrieves the data that is emitted from the event, and then displays it on my front-end. I've gotten it to run on Localhost so far. Currently, MetaMask connects to my front-end, but it throws an error when I try to confirm a transaction with the contract.
Create Function (JS):
    async function create() {
        ///Acquiring values
        postBody = document.getElementById("in-1-pbd").value;
        postSubcat = document.getElementById("in-2-sc").value;
        console.log(postBody + ", " + postSubcat);
        ///Connecting with Ethereum
        await requestAccount()
        if (typeof window.ethereum != 'undefined') {
          const provider = new ethers.providers.Web3Provider(window.ethereum);
          const signer = provider.getSigner();
          const contract = new ethers.Contract(blokracyAddress, Blokracy.abi, signer)
          const transaction = await contract.createBallot(postSubcat, postBody)
          await transaction.wait()
        ///Building and presenting the ballot
        contract.on("Creation", (message, idnum ) => {
          console.log("Creation Event Data: ", message, idnum);
          buildBallot(Wallet.publicKey, idnum, postBody);
          });
        } else {
          window.alert("Non-Ethereum browser detected. You should consider installing MetaMask.")
        }
      }

Request Account Function:
      async function requestAccount() {
        await window.ethereum.request({ method: 'eth_requestAccounts' });
      }

Create Function (Solidity):
///Event Declaration
    event Creation(string message, uint idnum);
///Functionality
///Creating a Ballot:
    function createBallot(
        string memory _subcategory, string memory _post
    ) public {

        ///Set Operator
        operator = msg.sender;

        ///Increment ballotNum
        ballotNum ++;

        ///Apply specifics to ballot
        ballot[ballotNum] = Ballot(
            ballotNum, _subcategory, operator,
            _post, 0, 0, 0, 0
        );

        ///return string and ballotNum
        emit Creation("Ballot was successfully posted!", ballotNum);

    }

Any insight would be amazing. Like I said, I'm new and trying to learn as much as I can about dApps by building this project.
Answer: You can try this approach for calling function of smart contract in front-end with the help of web3.
const web3 = new Web3(sNetworkRPCURL);
const oDefaultWeb3 = new Web3(window.ethereum);
let oContractObject;
let sWalletAddress;

async function metamaskConnection(){
    const aReqAccount = await window.ethereum.request({
        method: "eth_requestAccounts",
    });
    sWalletAddress=aReqAccount[0];

}
async function create() {
        ///Acquiring values
        postBody = document.getElementById("in-1-pbd").value;
        postSubcat = document.getElementById("in-2-sc").value;
        console.log(postBody + ", " + postSubcat);
        ///Connecting with Ethereum

        if(typeof window.ethereum=="undefined"){
            console.log("METAMASK IS NOT FOUND");
            return;
        }

        oContractObject = new web3.eth.Contract(aContractABI,sContractAddress);
        let oNewContractObject = new oDefaultWeb3.eth.Contract(aContractABI,sContractAddress);

        let estimatedGas;

        try {
            estimatedGas = await oNewContractObject.methods
                .createBallot(postSubcat, postBody)
                .estimateGas({
                    from: sWalletAddress
                });

            console.log("Estimated Gas: ", estimatedGas);
        } catch (error){

            console.log(error);

            return;
        }
        try {
            await oNewContractObject.methods
                .createBallot(postSubcat, postBody)
                .send({
                    from: sWalletAddress,
                    gas: estimatedGas,
                })
                .on("transactionHash", (txHash) => {
                    console.log("Transaction Hash: ", txHash);
                })
                .on("receipt", async (txReceipt) => {
                    console.log("Receipt: ", txReceipt);

                })
                .catch("error", (err) => {
                    console.error(err);

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

        }
    }

And I want just clarification on web3 object and oDefaultWeb3 objects which I have taken in my code. fist web3 object I will use it for view or call() methods. And other one is useful for send() methods.
So, Now I hope this approach will helpful for you to developing dApps and many more.
Answer: You can get events like this:
const from = "some address"
const filter = uni.filters.Transfer(from)

const logs = await uni.queryFilter(filterFromAddress1orAddress2)

If you want all the parameters, including the non-indexed, you need to create an interface and parse the logs:
const interface = new ethers.Interface(ABI)

const parsedLogs = logs.map(log => {
    return interface.parseLog({ data: log.data, topics: log.topics });
})


How long is an appoggiatura in triple time?

Question: I am currently playing in a baroque group.
The question has arisen as to how long an appoggiatura should be in triple or compound meters.
According to Wikipedia (https://en.wikipedia.org/wiki/Appoggiatura),

The time subtracted is generally half the time value of the principal
  note, though in simple triple or compound meters, for example, it
  might receive two thirds of the time.

Is there a "rule" as to when it should receive one third of the time, and when two thirds?
Answer: Although I don't play in Baroque ensembles, my experience with Baroque keyboard music tells me that the appoggiatura takes up two-thirds of the value.
A discussion on Music Manuscript Notation in Bach seems to corroborate this:

The appoggiatura takes half the time of the following note, except when followed by a dotted note. It then usually takes two-thirds of the value of the note.

Thus the appoggiatura (the non-chord tone itself) takes two-thirds of the value, and the chord tone to which it resolves only occupies the final one-third of the value.
Comment: Thanks very much! It seems intuitively strange to me, but maybe that's just because I'm taking the notation too literally, rather than thinking about the musical importance.
Comment: "Thus the appoggiatura (the non-chord tone itself) takes two-thirds of the value, and the chord tone to which it resolves only occupies the final one-third of the value." IMO this is too prescriptive. The actual length might be 2/3, 1/3, or even 1/6 or 1/12 of a long dotted note. It depends on the musical context, and what is happening in the rest of the harmony and/or counterpoint. In fact the appoggiatura can even take *all* of the written note, if that is followed by a rest which is replaced by the resolution of the ornament!
Comment: I agree wholeheartedly. Later in the link I gave it says "a certain freedom may be allowed in the applicaton of these rules, to preserve the improvisatory character of the appoggiatura."


Debugging in-built java apis

Question: I am using the java.security package to verify some digital signatures. Basically I am calling the verify method of the Signature class. I want to understand the internal logic of the verify method. Therefore I have extracted the Signature.class from the rt.jar, decompiled it and then put it in proper package structure in my eclipse project. However, it is not compiling and complaining about "cannot resolve" errors. I am fixing them one by one by decompiling other inbuilt java classes but this seems to be endless. Is this the correct approach to debug in-built java api's or is there some other recommended approach ?
Comment: Why are you decompiling the class file? you can just get the real file from the src.zip that comes with your installation of Java.
Answer: You can attach the JDK sources in Eclipse: There should be a src.jar in your JDK installation. That way you can conveniently browse and debug them. Does not include some of the javax and com.sun classes, but it is a start.
Re-compiling and replacing JDK classes is very difficult.
Answer: Did you see the java.security.debug flag?

... if you wish to monitor security access, you can set the java.security.debug System property. To see a list of all debugging options, use the help setting, the all setting allows you to see everything:

<code>java -Djava.security.debug=help foo

all       turn on all debugging

access    print all checkPermission results
jar       jar verification
policy    loading and granting
scl       permissions SecureClassLoader assigns

The following can be used with access:

stack     include stack trace
domain    dumps all domains in context
failure   before throwing exception, dump stack
          and domain that didn't have permission
</code>
Answer:
Is this the correct approach to debug in-built java api's or is there some other recommended approach ?

I'd added source of the API using attach source  into the eclipse and use the default debugger to debug the app
Comment: No this isn't what you are doing. I am asking to take the source of jdk from src.zip as commented above without decompiling it. attach it to eclipse add the break point and start the project to debug
Comment: Jigar is correct.  If you are using open source projects, just download the source to a location on your local box.  Attach the source to the JARs inside Eclipse, and you can then step through code to see what is actually going on.  I've done this to great success with Hibernate.
Comment: This is exactly what I'm doing..I am decompiling and adding the source code of that API in my project. But it is giving other errors and when I fix those it is still giving new ones. So I was asking if there is any alternative approach.

Debugging in-built java apis


Best way to maintain voicing in this example, without awkwardness

Question: I have tried this with crossing the LH over, and under, to hit the A# indicated by the arrow; have also tried playing the A# with RH. The latter is much easier but makes it incredibly hard to maintain the voicing. The former is very awkward. Hoping that maybe someone is near a piano and could try this measure out, to offer an opinion of what approach I should take. Seems like it shouldn't be that difficult, but for some reason, it is just giving me trouble. Thanks.
Answer: I would use RH only.
You need preparation of finger 5 playing the A-sharp.
This can be done by 5 hovering over G-sharp when 2 plays B. Can get better preparation by angling the hand (see photo) and then 3 or 4 depending on what's next.
I'd favour 4 because it's less physically possible to play legato with 4 than 3, to detach from the high A-sharp.


Writing SATB arrangements so that the bass voice is still audible

Question: When writing the bass voice part for an SATB arrangement, what should be done so that the bass singers voice is not "swallowed" by the other 3 voices - being the lowest of all? (Also most choirs in my country are church based, and they tend to have fewer bass singers compared to the sopranos and altos).
Comment: Mike the basses?  Tell the dang sopranos to sing more quietly?  Redesign the hall so its acoustics are more accommodating of lower frequencies?   You can see that there's a lot of ways to go here.
Comment: Sounds good.. and to support these efforts by the choir leader, is there anything the composer/arranger can do with the score sheet?
Answer: If you look at standard SATB arrangements of hymns, you will notice that the bass often moves in contrary motion to the melody, and often in rhythmic intervals in the middle of phrases when no one else is moving. This really makes the bass part pop in a way that does not distract from the song itself.
Also pick up and study some of Bach's chorales, and you will see what I mean, I think.
Comment: But I have always liked how it worked for the bass.  And as for canonical writing, you are starting to get into the fugue, where each voice - numbering three, four, six, and more, has its own independent legitimacy.
Comment: Sounds interesting, i think that strategy is effective in making the bass stand out at some occasion. I also heard that the "canon" style (not sure what the English term is) also works - here the bass singers start the line 3-4 beats after the other 3 voice parts, and consequently finish at 3-4 beats after the other 3 parts so they still stand out a little bit. Probably something like a reciprocal "question and response" style. Hope this makes sense :)
Comment: Well, as I was writing my response, I realized you could say the same about all three of the supporting voices..
Answer: Write higher.  People commonly write the tenor part too low, which then forces the bass even lower, into a quieter part of their range (it doesn't help that usually most of the members of the bass section are not true basses, but rather baritones without good control of their upper range).
Comment: What about writing a baritone part then - I typically have to switch tenor/bass depending on the song!
Comment: @Mr.Boy: Do you mean the tenor and bass singers take turns in singing?
Comment: No I mean my range can't reach the high tenor notes or the low bass notes so I have to figure out on each song which part I can actually sing :)
Comment: i see. I think most male singers are baritones, and interestingly the baritone part rarely comes up in choral song sheets..not sure why..
Answer: Use a well spaced writing technique. Especially between Bass and Tenor.
Remember that in a modern SATB choir, Soprano and Tenor are the brighter voices and Alto and Bass the darker.
So you have not a timbral continuum from Bass to Soprano.
This is very important when you want to write a transparent texture.
Comment: Between Bass and Tenor you can reach a (max) 10th interval without any serious problems.
Comment: Andrea is right. It also helps if the interval between the tenor and bass reinforces the bass (i.e., try to arrange that they meet at the octave or fifth at important points in the bass line; try to maintain a separation of at least a fifth).
Comment: Just to make sure i understood you correctly- did you mean the distance between tenor and bass should be large enough?
Answer: As you mentioned a church choir, you can cheat.  Double the sung bass line with a quiet 16' organ stop!


In how many ways can the officers of the student council be selected?

Question: This is the question,
A student council has $10$ members. From this one President, one Vice-President, one Secretary, one Joint-Secretary and two Executive Committee members have to be elected. In how many ways this can be done?

$151200$
$75600$
$37800$
$18900$

And this is the answer on almost every website

Given, A student council has $10$ members. From this one President, one
Vice-President, one Secretary, one Joint, one Secretary and two Executive
Committee members have to be elected.
$\implies
6$ members are elected out of $10$ members. The number of ways to
elect $6$ members out of $10$ members = $P(10,6) = 151200$.

This seems wrong to me. I think the answer should be like,
Out of $10$ we first select $1$ president, then out of $9$ one vice president, out of $8$ one Secretary, out of $7$ one joint Secretary and then out of $6$ two Executive Committee members.
This give us  $\binom {10}{1} \times \binom {9}{1} \times \binom {8}{1} \times \binom {7}{1} \times \binom {6}{2} = 75600$.
Am I wrong somewhere?
Answer: Since an answer affirming the book answer has been put, I disagree with it.
Nowhere is it mentioned that particular seats are associated with the two Executive Committee members, your answer is correct, let us confirm it in a skightly different way, first choose the six who will be on the council, and then select people with "solo" designations, the remaining two will just be members
$\binom{10}{6}\cdot6*5*4*3 = 75600$


How can i check Server not responding condition?

Question: In my app am getting data from a webserver using json. so each time i communicate with sever i would get a json and iam using it in right way.But some time my sever is down .Then how do i check whether the server is online or down before sending request from app other wise app will crash?
Please help me?
Comment: Why does the app crash?  That sounds like you are mishandling this common situation.
Comment: because in view didload methode it has to send request to server
Comment: Yeah, you are mishandling this condition.
Comment: @mango means doing `HTTP/Network Request ` in `main Thread.` ?
Comment: what you mean by mishandling?please let me know?
Comment: @bunty Madan : iam using HTTP  POST method
Comment: By mishandling I mean fix the reason for the crash.  This is the problem you are facing.
Comment: problem for crash is null json when server is offline
Comment: So how do you think you could handle that correctly?
Comment: Perhaps show come code. How do you send the request to the server, how to you read the response, how do you handle a timeout, where does the crash occur, ... ?
Answer: Try this  ,setup a timer that cancels your connection(interation with server) after a specific time period
<code> connection = [[NSURLConnection alloc] initWithRequest: request delegate: self startImmediately:NO];

timer = [NSTimer scheduledTimerWithTimeInterval:10
                                     target:self
                                   selector:@selector(onTimeExpired)
                                   userInfo:nil
                                    repeats:NO];

[connection start];

// When time expires, cancel the connection
-(void)onTimeExpired
{
    [self.connection cancel];
}
</code>
so whenever server is not responding json will be null.Or even in low speed internet connectivity json will get corrupted so what iam suggesting is like cancel the connection if you are not able to connect with server.
Comment: This is a hack.  The OP should fix the reason for the app crash.
Comment: trojanfoe:mango mensioned that they are using json calls ,so whenever server is not responding json will be null.Or even in low speed internet connectivity json will get corrupted so what iam suggesting is like cancel the connection if you are not able to connect with server.
Comment: NSURLRequest already has a timeoutInterval parameter, which is 60 seconds by default. There should be no need to use another timer.
Comment: @mango... Martin is right just used the default one and in order to resolve the crash, man what you need to do, as the place where you not get response just redirect to some other page/screen... And, one more thing you can do is to get the response status code... Try it, and hope prob will be sorted out, and please let us know in any concern mate


Test of heteroscedasticity for a categorical/ordinal predictor

Question: I have different number of measurements from various classes. I used one-way anova to see if the means of the observations in each class is different from others. This used the ratio of the between-class variance to the total variance.
Now, I want to test whether some classes (basically those with more observations) have a larger variance than expected by chance. What statistical test should I do? I can calculate the sample variance for each class, and then find the $R^2$ and p-value for the correlation of the sample variance vs. class size. Or in R, I could do
summary(lm(sampleVar ~ classSize))

But the variance of the esitmator of variance (sample variance) depends on the sample size, even for random data.
For example, I generate some random data:
dt <- as.data.table(data.frame(obs=rnorm(4000), clabel=as.factor(sample(x = c(1:200),size = 4000, replace = T, prob = 5+c(1:200)))))

I compute the sample variance and class sizes
dt[,classSize := length(obs),by=clabel]; dt[,sampleVar := var(obs),by=clabel]

and then test to see if variance depends on the class size
summary(lm(data=unique(dt[,.(sampleVar, classSize),by=clabel]),formula = sampleVar ~ classSize))
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.858047   0.056605  15.159   <2e-16 ***
classSize   0.006035   0.002393   2.521   0.0125 *

There seems to be a dependence of the variance with the class size, but this is simply because the variance of the estimator depends on the sample size. How do I construct a statistical test to see if the variances in the different classes are actually dependent on the class sizes?
If my the variable I was regressing against was a continuous variable instead of the ordinal variable classSize, then I could have used the Breusch-Pagan test.
For example, I could do
fit <- lm(data=dt, formula= obs ~ clabel)
Answer: It's important to keep in mind that you are going to have to write down some model for the variances, and as the variances cannot be estimated independently of the means, you will simultaneously need a model for the means.
Are you willing to assume that the distribution of measurements within any particular class is normal?  I assume so, since you analyzed the data with an anova, but this is an important assumption that affects how you can compare variance between classes.
I assume that you want to estimate the class means independently, though there's not enough information in the question to be sure that you don't treat the effect of class as random (rather than fixed).  Importantly, decisions like this could affect your inference about the variances!
Now that you've narrowed down a model for the means, you need to focus down to a specific model for the data by figuring out how to model the variances.  Do you want a model where class variances differ strictly according to some linear predictor (e.g. the variances are given exactly by a linear function of the class size?), or a model where each class has its own independent variance, or a model like the one you describe where the class variances are modeled as a linear regression (with homogeneous normal error) on the class size, or... ?
In general, it is hard to get good estimates for variance parameters. MCMC fitting routines often (presumably correctly) yield higher uncertainties for variance parameters than homologous frequentist estimates. Therefore, I suggest that an MCMC fitting routine with vague priors might be the best way to get the inference you seek.
The BUGS/JAGS likelihood associated with the linear regression you describe (where class means are estimated separately and class variances come from a linear regression on class size) would look like this:
for(i in 1:n_samples){
sample[i] ~ dnorm(mu[class[i]], tau[class[i]])
}

for(j in 1:n_classes){
  tau[class[i]] <- 1/var[class[i]]
  var[class[i]] ~ dnorm(m*class_size[j]+b, tau2)
}

Then you want inference on the parameter m.  But this is just one highly specific model for a particular form of the means and variances!
Comment: Thank you! Is there a frequentist closed form solution assuming a normal distribution of data and linear relation between variance and class size or other ordinal variable. I also have a continuous variable for which I want to test the dependence of the variance. In each case, the data is divided into classes. So `fit <- lm(Obs ~ clabel)` and then I want to use the equivalent of the BP test. But is the Breusch Pagan test valid when the first regression is against a categorical variable?
Comment: I'm really not too sure about a frequentist closed-form solution.  I also don't know much about possible categorical extensions of the Breusch Pagan test.  It wouldn't surprise me if there is a version of that test available in standard statistical software that can handle categorical predictors, but I don't know how to find it.  Notice that the Breusch Pagan test checks for association between the variance and the class mean, not between the variance and the number of observations in the class.  Your OP suggests you might be interested in the latter (?) in which case B-P is not appropriate.
Comment: As I understand it, Breusch Pagan tests association between the variance and possible predictors. Which is fine for continuous predictors, but in my case the the predictor (class-label) is categorical. I can treat class size as another predictor for BP, but I also have other possible predictors. I'm sorry the question is sort of asking two different things.
Comment: Yup, you're completely right.  My mistake.  In a quick refresher on the Breusch Pagan test I misread "association with INdependent variables" as "association with DEpendent variables".
Comment: I mean BP test is built on the assumption of an iid normal distribution of the residuals. All I need to know is the distribution of the residuals when the predictor is categorical. I think they are still Gaussian, but we expect different variance depending on the sample size for each category. If not, BP test should still be valid. If the variances vary for the null model, then BP test should be modified.
Comment: You're right that the influence of sample size on sample variance does not interfere with our ability to assume (if we think our assumption is justified) that the population variance are equal.  This equality of population variance is what is assumed by anova, linear regression, etc.  It is also the null model against which BP tests.  There shouldn't be any additional issues applying BP to data with a categorical predictor, as far as I know.


What terms are there for changes in tempo?

Question: I know that there are many terms that can be used to talk about the tempo of a piece of music but what words are there for change in tempo?
The only ones that I can think of are:

Accelerando
Rallentando
Ritardando
Calando
Stringendo
Smorzando
Rubato

Are these all correct in regards to changes in tempo and are there any others?
Comment: Wikipedia has a full list here: https://en.wikipedia.org/wiki/Tempo Scroll down until you see "Terms for change in tempo"
Answer: They're all correct, though some have meanings beyond just speed.  Smorzando means slower AND softer - 'dying away'.
Meno mosso, piu mosso, ritenuto refer to sudden rather than gradual changes in speed.  This can cause confusion as both ritenuto (sudden) and ritardando (gradual) are abbreviated to 'rit.'   The only clue may be the presence or absence of an extension line.  A gradual change has an extent, a sudden one doesn't.
Comment: I've seen so many "rit."'s interpreted as ritardandos that don't have extension lines.
Answer: They are indeed tempo change markings, but some of them mean something along with tempo change.
Accelerando means to speed up, to accelerate. That's pretty intuitive.
Rallentando and Ritardando both mean to slow down, but they have slightly different connotations. Rallentando is a sort of fade out type of slowing down, whereas Ritardando is a more deleberate slowing down.
Calando means more than just slowing down. If you want a fadeout to a certain point in both dynamic and tempo, this is a good marking to use. You could mark ritard. and dimin. which would get you a very similar result, but Calando is a way of getting across both a diminuendo and a ritardando without marking ritard. or dimin. Calando literally means to calm down.
Stringendo is another marking that means to accelerate. But more specifically, it means that the music should get more excited. This is often interpreted as Accelerando + Crescendo, because both Accelerando and Crescendo add excitement and/or tension to the music, especially when combined.
Smorzando is another fadeout marking. It literally means dying away. Now, when to use Calando vs. Smorzando? I personally do this:

If the music is to fade to a slow pianissimo ending, I mark Smorzando
If the music is to fade to a quieter dynamic and a slower tempo(as an example, a forte allegro fading into a piano adagio) but isn't near the end yet, I mark Calando

Rubato is a bit different than all the others because the tempo change isn't unidirectional with Rubato. Rubato means that the tempo is flexible. How flexible it is depends on many factors, like for example Liszt's rubato is more flexible than Chopin's rubato and Beethoven has only the slightest bit of rubato.
Comment: Weird--I've only seen rallentando in contexts where the music pointedly does not fade out (and possibly crescendos), to the point where I've never been punished for interpreting rallentando as "rally". Also, I've read that stringendo means that acceleration is optional.
Comment: Well I looked up the difference between ritardando and rallentando and it talked about the typical definition and how that brings confusion and then it went into the literal translation from Italian and that's where I found the ritardando is deliberate whereas rallentando is fading out. And then I looked up the definition of stringendo and it said right there that it is most often interpreted as Accelerando + Crescendo but means for the music to get more excited. Excitement and acceleration fit like 2 pieces of a puzzle.
Answer: There's a particularly common tempo change marking I'm surprised isn't in the OP: allargando. It marks a gradual slowing and broadening of the music. An interesting example is the optional, parenthesized allargando marking near the end of the C major section of Edward Elgar's Pomp and Circumstance March No. 3 in C Minor, which I've heard orchestras inconsistently follow (just like you'd expect).


Views report for Ubercart Order product totals for date range?

Question: I have been trying to create a view that will provide me with the total number of each product SKU ordered within a specified date range. Let's say there were three orders within the specified date range:
Order 101
Product ABC - Qty 1
Product XYZ - Qty 3

Order 102
Product ABC - Qty 1
Product XYZ - Qty 0

Order 103
Product ABC - Qty 10
Product XYZ - Qty 2

The View result would look something like this:
Total Number Ordered Per SKU for (date range)
Product ABC - 12
Product XYZ - 5

It is important for the results to be based on the SKU of the product, not the product title.
I have played around a bit with Views Aggregation on a "Type: Orders" view, but I am not knowledgeable enough to make it do what I need to do. Perhaps there is an easier way?
The purpose of this view will be to have an "at-a-glance" of which products need to be prepared for fulfillment, and how many of each, for the filtered date range.
Thanks!
Answer: I found my answer. I used the Views Aggregator Plus module (https://www.drupal.org/project/views_aggregator). I applied "Group and Compress" and "Tally Members" in the "Group Aggregation" column within the Views Aggregator Table options for the SKU field, and I applied "Sum" in the "Column Aggregation" column for the Quantity field. This provided me with the exact result I was looking for.


How to have a dialog box displayed automatically when a page is reached without having to click the link?

Question: Using Dialog API and advice from @leymannx, I added this link to a node (node99):
Last minute information

and it works fine: when clicked, the dialog box shows up!
Now, I'd like to have the dialog box displayed automatically when the node is reached without having to click the link.
@No Sssweat suggested to make jQuery to click the link for you on page load $(".use-ajax").click();
After some errors ($ is not a function), I finally used this:
(function ($) {
  $('.use-ajax').trigger("click");
})(jQuery);

It works but not as expected: the node 27 (the link has href="/node/27") is displayed instead of node99, not in a modal over node99.
What am I missing?
Comment: Try to add an id and target with it, maybe `use-ajax` class used else where, add `id="my-dialog-modal"` and in the js change it to `$('#my-dialog-modal').trigger("click");`
Comment: Nothing better. Even worse: I don't have anymore node27 replacing node99. And when I go back to previous version - with `$('.use-ajax')`, same result: I'm stuck on node99. I'm confused...
Answer: Your JS needs to be formatted like this:
(function ($, Drupal) {
  Drupal.behaviors.myThemeBehavior = {
    attach: function (context, settings) {
      $('.use-ajax', context).once('auto-open').each(function () {
        $(this).click();
      });
    }
  };
})(jQuery, Drupal);

Your library needs to be defined like this:
example:
  js:
    js/example.js: {}
  dependencies:
    - core/jquery #Just ot be save
    - core/drupal.dialog.ajax #Required for dialogs


Problem Using Pivot_Table in Python: is there any way to keep the original order of the data and not having multiindex?

Question: I am trying to recreate my data frame. Below is the original dataframe:
df = pd.DataFrame([['January','Monday',0,1,20],['January','Monday',1,2,15],['January','Wednesday',0,1,35],['March','Monday',0,1,23],['March','Monday',1,2,50],['March','Monday',2,3,60] ,['April','Wednesday',0,1,75]],columns = ['Month','Day','Data1','Data2','Random'])

     Month        Day  Data1  Data2  Random
0  January     Monday      0      1      20
1  January     Monday      1      2      15
2  January  Wednesday      0      1      35
3    March     Monday      0      1      23
4    March     Monday      1      2      50
5    March     Monday      2      3      60
6    April  Wednesday      0      1      75

I am aiming to achieve the below result:
     Month        Day  0    1    2
0  January     Monday  1  2.0  NaN
1  January     Monday  1  2.0  NaN
2  January  Wednesday  1  NaN  NaN
3    March     Monday  1  2.0  3.0

I tried to use the pivot_table as below, but of course it did not work as pivot_table does not allow any duplicate for the index and I will also have multiindex which causes problems in my later process.
df1 = pd.pivot_table(df, values = 'Data2', index = ['Month','Day'], columns = ['Data1'])

Data1                0    1    2
Month   Day
April   Wednesday  1.0  NaN  NaN
January Monday     1.0  2.0  NaN
        Wednesday  1.0  NaN  NaN
March   Monday     1.0  2.0  3.0

Is there any other way to get my aimed result? Many thanks in advance.
Comment: I don't understand what you are trying to achieve. Row 0 and 1 is the same in your desired result. Can you try to elaborate.
Comment: Exactly, row 0 and 1 is indeed the same. If I use pivot_table, there will be no duplicate. Basically, I want the data to be classified based on Month and Day. The new data frame will have new columns that are based on the value from column Data1 of the original data frame. For example for month January and day Monday, its Data1 is 0 and 1 while Data2 is 1 and 2, the new data frame will still show 2 rows of Month January and day Monday (like the original data frame), and in each row the column 0 is filled with 1 and column 1 is filled by 2. I hope this clarifies.
Answer: You can try using groupby with unstack:
df.groupby(['Month','Day','Data2'])['Data2'].first().unstack().reset_index()

Output:
Data2    Month        Day    1    2    3
0        April  Wednesday  1.0  NaN  NaN
1      January     Monday  1.0  2.0  NaN
2      January  Wednesday  1.0  NaN  NaN
3        March     Monday  1.0  2.0  3.0


Multiple  attributes?

Question: I have a page with a Google Tour in an iframe. I've set iframe's name as "vtour". The iframe is inside a div whose ID I've set to "tour".
Below the iframe I have some links that jump to certain locations in the Google Tour (within the iframe). This works fine, except that now only the bottom bit of the iframe is on screen since I've scrolled down the page somewhat in order to access the links below it. So I would like these links to jump me higher up on the page by targeting the div's ID so the full iframe is in view.
Is it possible to have a link target both the content inside an iframe and the iframe's location on the page using the div ID? Or, since my iframe is near the top of the page, the target attribute "_top" could also work.
Answer: No, the target attribute can only point to one target browsing context at a time. You'll probably need to use a JavaScript click handler to scroll the page programmatically as the link navigates the iframe.

Multiple  attributes?


Michael Hartl Tutorial Chapter 6 - Syntax error

Question: I'm working on Michael Hartl's Tutorial.  I'm on Chapter 6.  I am up to user validation. The code below is what I was told to use, but it doesn't work.  I get the error message syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError).  I don't see a syntax error. Any suggestions?
require 'spec_helper'

describe User do
  before do
    @user = User.new(name: "Example User", email: "firstname.lastname@example.com")
  end
  subject { @user }
  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should be_valid }

  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end
  describe "when email is not present" do
    before { @user.email = " " }
    it { should_not be_valid }
  end
  describe "when name is too long" do
    before { @user.name = "a" * 51 }
    it { should_not be_valid }
  end
  describe "when email format is invalid" do
    it "should be invalid" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.
                     foo@bar_baz.com foo@bar+baz.com]
      addresses.each do |invalid_address|
        @user.email = invalid_address
        @user.should_not be_valid
      end

  describe "when email format is valid" do
    it "should be valid" do
      addresses = %w[firstname.lastname@example.com firstname.lastname@example.com firstname.lastname@example.com firstname.lastname@example.com]
      addresses.each do |valid_address|
        @user.email = valid_address
        @user.should be_valid
      end

  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end
    it { should_not be_valid }
  end
end

Comment: You really need to work on formatting your code. Line things up to make them readable and you'd be able to find your missing `end`
Comment: @nickm: I think you should stop that activity (adding the tag). A similar tag was discussed on [meta](https://meta.stackoverflow.com/questions/294548/derail-railstutorial-org), some time ago.
Comment: @NickM: and now maybe quickly undo the changes, before meta notices? :)
Comment: Fair enough @Sergio Tulentsev
Comment: I removed the tag from the posts I added it to, but I don't have permissions to edit/delete the tag itself.
Answer: I recommend that you indent your code, that way it'll be much more obvious where end keywords should go (and you'll see immediately that you're missing one). (Hartl does throughout the book.)
For example:
require 'spec_helper'
describe User do
  before do
    @user = User.new(name: "Example User", email: "firstname.lastname@example.com")
  end
  subject { @user }
  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should be_valid }
  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end
end

If the indentation doesn't match up anywhere, it should jump out at you, then you'll know there's a problem.
Answer: require 'spec_helper'

describe User do
  before do
    @user = User.new(name: "Example User", email: "email@example.com")
  end
  subject { @user }
  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should be_valid }

  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end
  describe "when email is not present" do
    before { @user.email = " " }
    it { should_not be_valid }
  end
  describe "when name is too long" do
    before { @user.name = "a" * 51 }
    it { should_not be_valid }
  end
  describe "when email format is invalid" do
    it "should be invalid" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.
                     foo@bar_baz.com foo@bar+baz.com]
      addresses.each do |invalid_address|
        @user.email = invalid_address
        @user.should_not be_valid
      end
    end # you've missed it
  end # and this one

  describe "when email format is valid" do
    it "should be valid" do
      addresses = %w[firstname.lastname@example.com email@example.com email@example.com email@example.com]
      addresses.each do |valid_address|
        @user.email = valid_address
        @user.should be_valid
      end
    end #
  end # and two more

  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end
    it { should_not be_valid }
  end
end

Answer: In Ruby, do .. end specifies a block. It goes like:
... do

.. Some Code Here ...

end

You should indent your code and have better look at the missing end.
In general, Its a convention in Ruby to use 2 spaces Or a tab character with length of 2 spaces to indent your code.


mybatis using dynamic sql foreach

Question: How to use foreach in mybatis mapper? I mean what parameters I should send there?
For example I've got this select statement
<select id="findObjectsWithIds" resultMap="SimpleObjectResult">
    SELECT * FROM testschema."XSimpleTable"
    WHERE ID in
    <foreach item="item" index="index" collection="list"
        open="(" separator="," close=")">
            #{item}
    </foreach>
</select>

I've got interface with method
List<SimpleObject> findObjectsWithIds(List<String> ids);

I've got implementation of the interface
@Override
public List<SimpleObject> findObjectsWithIds(List<String> ids) {
    SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
    try {
        SimpleMapper simpleMapper = sqlSession.getMapper(SimpleMapper.class);
        return simpleMapper.findObjectsWithIds(ids);
    } finally {
        sqlSession.close();
    }
}

And when I make an attempt to run - I've got this error

How to use foreach properly?
Answer: The problem is solved.
I added annotation param
List<SimpleObject> findObjectsWithIds(@Param("list") List<Integer> ids);

And also I sent String representation of indices instead of Integer.

mybatis using dynamic sql foreach


Cannot implicity convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'

Question: Possuo o seguinte método abaixo com o propósito de retornar notificações que devem ser exibidas para determinado cliente e notificações que devem ser exibidas para todos os clientes.
public List<TNotification> GetNotifications(TClient client)
{
    var notificacoesClient = Session.CreateCriteria<TNotification>()
        .CreateAlias("TClientNotifications", "clientNotifications", JoinType.LeftOuterJoin)
        .SetFetchMode("clientNotifications.Client", FetchMode.Eager)
        .CreateAlias("clientNotifications.Client", "client", JoinType.LeftOuterJoin)
        .Add(Restrictions.Eq("client.Id", client.Id))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>()
        .ToList();

    var notificacoesAll = Session.CreateCriteria<TNotification>()
        .Add(Restrictions.Eq("IsToAll", true))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>()
        .ToList();

    return notificacoesAll.Union(notificacoesClient);
}

Porém na instrução return notificacoesAll.Union(notificacoesClient); está retornando a seguinte mensagem:

Cannot implicity convert type
  'System.Collections.Generic.IEnumerable'
  to 'System.Collections.Generic.List'.
  An explicit conversion exists (are you missing a cast?)

Como poderia resolver esta questão?
Answer: Este erro acontece porque notificacoesAll.Union(notificacoesClient) retorna um IEnumerable<TNotification>, mas a assinatura do seu método espera List<TNotification>.
Logo, você tem duas alternativas:

Alterar a assinatura do seu método para retornar IEnumerable<TNotification>
Transformar o resultado da sua união em uma lista:
return notificacoesAll.Union(notificacoesClient).ToList();

Mais um detalhe: creio que não seja necessário chamar ToListnas queries do seu exemplo, pois List já retorna  uma lista (é redundante).
Answer: Tire o .ToList() das lista e deixe apenas no retorno
Algo assim:
public List<TNotification> GetNotifications(TClient client)
{
    var notificacoesClient = Session.CreateCriteria<TNotification>()
        .CreateAlias("TClientNotifications", "clientNotifications", JoinType.LeftOuterJoin)
        .SetFetchMode("clientNotifications.Client", FetchMode.Eager)
        .CreateAlias("clientNotifications.Client", "client", JoinType.LeftOuterJoin)
        .Add(Restrictions.Eq("client.Id", client.Id))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>();

    var notificacoesAll = Session.CreateCriteria<TNotification>()
        .Add(Restrictions.Eq("IsToAll", true))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>();

    return notificacoesAll.Union(notificacoesClient).ToList();
}

Comment: siga essas regras para [criação ou edição de perguntas e respostas](http://pt.stackoverflow.com/editing-help) +1 pela resposta.


Estou tentando fazer um cadastro em C, mas o código não deixa colocar o endereço

Question: Estou tentando fazer um cadastro em C, mas o código não deixa colocar o endereço e quando coloco a opção pra finalizar o cadastro o programa trava e para de funcionar. O que estou fazendo de errado?
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char endereco, nome, cpf;
    int rg, cnh, codigo, opcao, dn;

    printf("Nome do Cliente: ");
    scanf("%s",&nome);

    printf("\nEndereco do Cliente: ");
    scanf("%s",&endereco);

    printf("\nNumero da Identidade (somente numeros):");
    scanf("%s",&rg);

    printf("\nNumero do CPF: ");
    scanf("%s",&cpf);

    printf("\nNumero da CNH (somente numeros): ");
    scanf("%s",&cnh);

    printf("\nCódigo do Cliente (somente numeros): ");
    scanf("%s",&codigo);

    printf("\nData de Nascimento (somente numeros): ");
    scanf("%s",&dn);

    printf("\nFinalizar Cadastro");
    printf("\n1 - Salvar");
    printf("\n2 - Cancelar\n");
    scanf("%s", opcao);
    if(opcao=1)
    {
        printf("Cadastro realizado com sucesso!");
    }
    else(opcao=2);
    {
        printf("Cadastro cancelado.");
    }
}

Answer: O if tem que ter 2 iguais, ou seja if(opcao == 1). Trabalho só com PHP, mas acredito que em C também é assim, apenas um sinal de igual =, quer dizer que você está acrescentando algo aquilo, dois sinais de igual == está verificando se é igual.
Outra coisa é que tem um ponto e virgula no seu else acredito que também esteja errado.
Outra coisa errada é que o else não pode ter uma condição, ele é apenas else (se não). Você teria que usar o else if
if(opcao == 1){
    printf("Cadastro realizado com sucesso!");
} else if(opcao == 2) {
    printf("Cadastro cancelado.");
}

Linguagem C - Operadores
Comment: Fiz as modificações e as opções não funcionam. O programa para de funcionar.
Comment: @ClarissaGalvao como eu disse, eu só trabalho com PHP, essa parte do if - else se você consertou, creio que agora está Ok. Outra parte do código eu não sei te informar se está certo ou não, porque eu não conheço muito bem a linguagem C.
Comment: Em C não existe `===`. Só existe `=` para atribuição e `==` para comparação.
Comment: Corrigido, Victor!
Answer: Primeiro, = é operador de atribuição, enquanto que == é de comparação. Assim sendo, você deveria usar if (opcao == 1) ao invés de if(opcao=1).
No seu else está faltando um if depois e tem um ; a mais. Como resultado, o else(opcao=2);{ troca o valor de opcao para 2 e executa o que está dentro do { que se segue. Não é isso o que você quer. O que você queria é else if (opcao == 2) {.
Segundo, que você está confundindo caracteres com strings. Ao invés de char endereco, nome, cpf;, deveria usar char endereco[50], nome[50], cpf[12];. O motivo é que esses campos são representados cada um por uma sequência de caracteres (string), e não por um caractere isolado. O número que aparece é o tamanho máximo da string. Lembre-se que em C, todas as strings têm um terminador nulo que consome um caractere, e portanto é importante deixar espaço para ele.
Outro erro é isso:
scanf("%s", opcao);

O que você queria era isso:
scanf("%d", opcao);

Entretanto, ler qualquer coisa com o scanf é uma coisa bem torturosa de fazer. É muito fácil fazer essa função horrorosa dar pau.
Uma alternativa é usar fgets para ler a entrada, no entanto, é necessário retirar-se a quebra de linha do final (uma função específica é capaz de fazer isso). No entanto, isso significa que cada string deve ter dois caracteres a mais do que o seu limite: um para o terminador nulo e outro para a quebra-de-linha que o fgets acrescenta.
Use atoi para converter string em número.
Eis o seu código corrigido:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removerNL(char *c) {
    c[strlen(c) - 1] = 0;
}

int main() {
    printf("Nome do Cliente: ");
    char nome[50];
    fgets(nome, 50, stdin);
    removerNL(nome);

    printf("\nEndereco do Cliente: ");
    char endereco[50];
    fgets(endereco, 50, stdin);
    removerNL(endereco);

    printf("\nNumero da Identidade (somente numeros):");
    char rg[20];
    fgets(rg, 20, stdin);
    removerNL(rg);

    printf("\nNumero do CPF: ");
    char cpf[13];
    fgets(cpf, 13, stdin);
    removerNL(cpf);

    printf("\nNumero da CNH (somente numeros): ");
    char cnh[20];
    fgets(cnh, 20, stdin);
    removerNL(cnh);

    printf("\nCódigo do Cliente (somente numeros): ");
    char scodigo[5];
    fgets(scodigo, 5, stdin);
    removerNL(scodigo);
    int codigo = atoi(scodigo);

    printf("\nData de Nascimento (somente numeros): ");
    char data[10];
    fgets(data, 10, stdin);
    removerNL(data);

    printf("\nFinalizar Cadastro");
    printf("\n1 - Salvar");
    printf("\n2 - Cancelar\n");

    char sopcao[5];
    fgets(sopcao, 5, stdin);
    removerNL(sopcao);
    int opcao = atoi(sopcao);

    if (opcao == 1) {
        printf("Cadastro realizado com sucesso!\n");
    } else if (opcao == 2) {
        printf("Cadastro cancelado.\n");
    } else {
        printf("Opcao desconhecida %d.\n", opcao);
    }

    printf("Nome: %s\n", nome);
    printf("Endereco: %s\n", endereco);
    printf("RG: %s\n", rg);
    printf("CPF: %s\n", cpf);
    printf("CNH: %s\n", cnh);
    printf("Codigo: %d\n", codigo);
    printf("Nascimento: %s\n", data);
}

Observe que no código acima, eu coloquei um monte de printf no final para mostrar o que ele gravou. Se você rodar esse programa com essa entrada:
Nome do Cliente: Vanessa da Silva
Endereco do Cliente: Rua do C++, 27
Numero da Identidade (somente numeros): 34467885-7
Numero do CPF: 25022198258
Numero da CNH (somente numeros): 6879326283
Código do Cliente (somente numeros): 34
Data de Nascimento (somente numeros): 10081973
1

Eis a saída:
Finalizar Cadastro
1 - Salvar
2 - Cancelar
Cadastro realizado com sucesso!
Nome: Vanessa da Silva
Endereco: Rua do C++, 27
RG: 34467885-7
CPF: 25022198258
CNH: 6879326283
Codigo: 34
Nascimento: 10081973

Veja aqui funcionando no ideone.
Comment: Pra que serve esse:         void removerNL(char *c) {
    c[strlen(c) - 1] = 0;
}
Comment: @ClarissaGalvao Para retirar a quebra de linha que o `fgets` coloca no final da string lida.
Comment: Você é uma passoa incrivel! Valeu!
Comment: @ClarissaGalvao Se esta resposta resolveu o seu problema e não te restar mais nenhuma dúvida, marque-a como aceita/correta ao clicar no "✅" aqui do lado, o que também marca a sua pergunta como respondida/solucionada. Se por outro lado, ainda não estiver satisfeita, deixe um comentário e vamos esclarecer.
Answer: Você não pode cadastrar um CPF como um inteiro, mesmo que seja sem pontos, já que isso retornaria um inteiro mto grande. Você até poderia usar um unsigned long int, mas caso seu sistema seja de 32 bits. Poderia acontecer um buffer overflow. Use a dica do amigo acima, pq esse é o melhor jeito de ser feito seu programa. E sempre se atente ao uso da memória em C.


Rails url path: obj_new_path versus new_obj_path

Question: I'm creating a messageboard in Rails and have a model called Post and created one called Reply dependent on Post.
Can somebody explain the difference between the automatically created URL paths?
replies_new_path

and
new_post_path

I checked the class and controller names and Rails has done the correct pluralization of Reply.
I do not understand the difference in the order. Any clues?
Comment: It's pretty straight forward - A post `has_many` replies (I assume). So since the post is singular but there is many replies, rails convention dictates that it's `replies_new_path` and `new_post_path`
Comment: @Niall You are pretty right!
Comment: Cool! I'll post an answer to help anyone who sees this in the future.
Answer: It's pretty straight forward - A post has_many replies (I assume), so since the post is singular but there are many replies, rails convention dictates that it's replies_new_path and new_post_path.
Comment: +1 (though I think it should be "there are many" instead of "there is many")
Comment: I thought that it would be because I have resources :post but the replies are defined using get in the config/routes.rb file. Is the order important? What is the convention, new first or object first? BTW, thanks for the reply.


__init__.txt in Robot Framework

Question: I have the following structure:
test_init
|__________resources
|          |__________ keywords.robot
|__________tests
           |__________ __init__.txt
           |__________ TestInit.robot

The keywords.robot contains:
*** Keywords ***
Keyword for init
   Log  init

The __init__.txt contains:
*** Settings ***
Documentation  This is from init file
Resource  ${EXECDIR}/resources/keywords.robot

The TestInit.robot contains:
*** Test Cases ***
Testing the Init
   Log  Vimal
   Keyword for init

And from command line in the test_init directory, if I execute as follows:
> pybot tests

I get the error saying that:
No keyword with name 'Keyword for init' found

I was thinking, the initialization file imports the resource file as well. But the init file is recognized for the documentation and I get that in my report.
I'm bit confused on the usage of initialization file, kindly help me to understand it much better.
Answer: The use of init file is to manage setup, teardown and tags on your whole folder/suite (and subfolders).
Init files can not be used to import resources (they have to be loaded in the file you use them).
Documentation has been made more clear since 2.8.7: see the Initialization Files section of the user guide.
Comment: But in the documentation, they say "The main usage for initialization files is specifying test suite related settings similarly as in test case files, but setting some test case related settings is also possible. Variables and keywords created or imported in initialization files are not available in the lower level test suites, __but resource files can be used if there is a need to share them.__". Also, in the example, they shown like importing a library. I don't see both are possible.
Comment: what this sentence means (maybe not clearly enough) is that resources/libraries can be *used* in __init__ files, which allows you to use keywords from these resources/library within the init file. But it does not imply that those same keyword will be available in the other files/suites.
Comment: I'm also confused on this sentence. As this statement implies, the init file should allow the resource files to be imported.
Comment: I agree documentation isn't exactly clear. What it tries to say is that if you want to share keywords/variables, you can use a resource file and import it in your init files and test case files. Keywords/variables in init files are never automatically available for lower level suites. Please submit an issue here about bad documentation and we'll improve it: https://github.com/robotframework/robotframework/issues
Comment: This was fixed by https://github.com/robotframework/robotframework/commit/c0184fcd908251b719707c8b18bf7b8c1193cb2e

__init__.txt in Robot Framework


Listar em Mysql tabelas que não tenham AVG

Question: Tenho duas tabelas em MySQL assim:
LOCAL
id | nome

NOTA_LOCAL (notas dadas pelos usários para cada local)
id | id_local | nota

Estou listando os locais e já mostrando a média de notas que cada local recebe, assim:
SELECT *, AVG(local_nota.nota) AS 'nota' FROM local
LEFT JOIN local_nota ON local.id = local_nota.id_local
GROUP BY local_nota.id_local
ORDER BY local.nome ASC

Os locais que possuem notas ele lista, mas não lista os locais que ainda não receberam notas, o que mudar no código?
Answer: Tente fazer desta forma
SELECT local.nome, AVG(nota_local.nota) AS nota FROM local LEFT JOIN nota_local ON local.id = nota_local.id_local GROUP BY local.nome ORDER BY local.nome

Comment: Oi, não entendi a diferença entre o meu código e o seu, são iguais... só mudou alguns detalhes que não surtiram mudanças.
Answer: O problema estava no GRUP BY, alterei para agrupar ao id do LOCAL, assim:
SELECT *, AVG(local_nota.nota) AS 'nota' FROM local
LEFT JOIN local_nota ON local.id = local_nota.id_local
GROUP BY local.id
ORDER BY local.nome ASC

Comment: Seria bom marcar como aceita sua solução para que o post não fique indefinidamente em aberto


Sums of Random Variables from Order Statistics of Dice Rolls

Question: Let's say you have a set of order statistics $ X_{(1)}, \dots, X_{(N)} $ drawn from a discrete uniform distribution $ \text{unif}(1,S) $. If you choose $ X_{(n_1)}, \dots, X_{(n_k)} $ from this set, how would you find the distribution $ Y = \sum_{j=1}^k X_{(n_k)} $?
As an example to make it clearer, I've been trying to develop a tabletop RPG system and I'm thinking that the player could level up their stats in a few different ways. One way I'm imagining is that players can roll--for example--4 d6's and then must start off with $ X_{(1)} + X_{(2)} $, then being able to upgrade to something like $ X_{(2)} + X_{(3)} $. I'd like to work this out in general to see if it's balanced, but given that $ X_{(1)}, \dots, X_{(k)} $ are not i.i.d., this has been difficult.
[Edit]
I have still been considering this question, and I've been able to make some slight progress by considering a transformation of the sample space. In particular, let
$$ S = \{ X \in \textbf{N}^K : 1 \leq X_1 \leq \dots \leq X_K \leq T \} $$
If $ m_Y(r) $ counts the multiplicity of $ r $ in the vector $ Y $ (e.g., $ m_{(1,3,3)}(3) = 2 $), the p.m.f. of this distribution is,
$$ f(Y) = \frac{1}{T^K} \binom{K}{m_Y(1), \dots, m_Y(T)} $$
Questions about order statistics from the original distribution then become questions about the marginal probabilities of a given index. E.g., something like $ \Pr(X^{(1)} = 2) $ becomes $ \Pr(Y_2 = 2) $. Then the marginal distribution of $ Y_i $ is
$$ f_{Y_i}(z) = \sum_{\substack{y \in S\\ y_i = z}} f(y) $$
This helps a bit, and it's more of an answer I had initially, but if there's a way of simplifying this sum I have been unable to find it.
Comment: What information would you need to decide if it's "balanced"? Or is that more a general impression from looking at the distributions?
Comment: It'll probably be about 50/50 between calculations and what feels right as I move on. I know I could just write a program to bruteforce the results, but a formula (even if not closed form) would be nice, and I'm now curious about the solution.
Answer: Can you get what you want from the expectations? From "Tables of Moments of Sample Extremes of Order Statistics from Discrete Uniform Distribution," by Turan, Calik, and Gurcan (available at https://openaccess.firat.edu.tr/xmlui/bitstream/handle/11508/8469/ATuran.pdf?sequence=1) I found for a sample of size $n=4$ that $$E[X_{(1)}]={ { \left( 6S^4+15S^3+10S^2-1 \right)}  \over {30S^3}}$$ and $$E[X_{(4)}]={ { \left( 24S^4+15S^3-10S^2+1 \right) } \over {30S^3}}$$
I couldn't find any published formulas for the intermediate order statistics, but the 4 six-sided dice example is small enough to do by enumeration. This confirms the 4 expectations are  $$E[X_{(1)}]={{2275} \over {1296}}=1.7554$$
$$E[X_{(2)}]={{3759} \over {1296}}=2.9005$$
$$E[X_{(3)}]={{5313} \over {1296}}=4.0995$$
$$E[X_{(4)}]={{6797} \over {1296}}=5.2446$$
Comment: This is certainly a step towards something. I'll mark it as the accepted answer unless someone finds something more explicit.


Como realizar sobrecarga de métodos com PHP?

Question: Como realizar sobrecarga de métodos com PHP?
Para poder declarar métodos com o mesmo nome mas com parâmetros diferentes.
Comment: Não existe sobrecarga de métodos em PHP, somente sobrescrita.
Comment: O PHP não tem sobrecarga. Tem apenas os jeitinhos gambiarras de simular
Answer: PHP é uma linguagem dinâmica, portanto isto não faz sentido.
Até existe um conceito chamado overloading mas que é um pouco diferente do que você está pensando, mas consegue resultado semelhante.
Em linguagens dinâmicas os parâmetros podem receber qualquer tipo então a resolução do que fazer com eles deve ser dado em tempo de execução através de seleção (if, switch, elemento de array ou outra forma).
Se realmente quer ter métodos que fazem quase a mesma coisa com parâmetros diferentes tem que trocar o nome. Mas o mais comum é que um método faça mais de uma coisa baseado no parâmetro. É, eu sei, para quem está acostumado com tudo organizado em funções únicas parece estranho mas muitas vezes fica até interessante e poupa código.
Normalmente costuma-se dizer que um parâmetro é do tipo mixed. Este tipo não existe de fato, é apenas um indicativo que pode-se usar mais de um tipo de dado ali. Exemplo:
mixed str_replace(mixed $search, mixed $replace, mixed $subject[, int &$count])

Coloquei no GitHub para referência futura.
A função mostra que é possível enviar parâmetros com tipos variados e o retorno da função também pode variar. Pode parecer uma bagunça mas simplifica o uso da linguagem permitindo que uma função realize a tarefa de várias maneiras diferentes. Evidentemente que os erros só podem ser verificados em tempo de execução.
Cada um com suas vantagens e desvantagens.
Answer: Como já dito anteriormente, não existe sobrecarga de métodos no PHP.
O que pode ser feito é utilizar os argumentos das funções de maneiras dinâmicas, como já vi em alguns frameworks, como CakePHP e Laravel 4.
Exemplo:
<?php

class MyClass{

    protected $values = array();

    function value()
    {
       $count = func_num_args();

       // obtém dados
       if ($count == 1) {

            $key = func_get_arg(0);

            return $this->values[$key];
       }

       // define dados
       if ($count == 2) {

            list($key, $value) = func_get_args();

            $this->values[$key] = $value;

            return $this;
       }

    }
}

$class = new MyClass;

$class->value('key', 'stackoverflow português');

echo $class->value('key'); // Stackoverflow português

print_r($class);

Ou seja, através das funções func_get_arg, func_get_args e func_num_args, você pode acessar os argumentos passados nas funções, muito embora os mesmos não sejam previamente declarados na criação da função (no meu exemplo, não há argumentos na declaração do método MyClass::value).
No PHP 5.6, temos um bom recurso no PHP chamado de Variadic Function.
Ao invés de usar as três funções que pegam os argumentos citados, apenas utilizamos o operador ....
Exemplo refatorado para o PHP 5.6:
class MyClass{

    protected $values = array();

    function value(...$args)
    {
       $count = count($args);

       // obtém dados
       if ($count == 1) {

            $key = $args[0];

            return $this->values[$key];
       }

       // define dados
       if ($count == 2) {

            list($key, $value) = $args;

            $this->values[$key] = $value;

            return $this;
       }

    }
}

Ao meu ver, a dificuldade de se implementar isso seria documentar o código do seu método ou função.
Teste esses códigos no PHPSandBox


React default function

Question: I am discovering React and I am wondering. The default function renders the html. However, let's say I want to create different function within the default function, how does this work? Like I would like to have the default function (adminDashboard), with two actual functions in it (one for  showHeader, and another one for a ShowButton). How would I structure it in order for it to render?
here is my code:
import React from 'react';

function AdminDashboard() {

return
   <ShowActionBtns/>;
   ;

}

function ShowActionBtns (){
return(

                       home

)
}

function Header (){
return(

                       home

 )
}

export default AdminDashboard;

Comment: "The default function renders the html" - thats incorrect, you decide what renders the HTML when you import the component, ie you can have named imports (without default import) and still render the components.
Comment: ok in my case I have an adminDashboard component. I would like to have several function (header, button, table) within that component. what is the best practice? To create those function and then render them at the end ? I am a bit confused as tp what the default function does.
Comment: There is no such thing "default function", `export default` is JS syntax, see MDN link in my answer. And asking about "best practice" is discouraged in StackOverflow since its opinion based. Go through React docs and see recommendations.
Answer: You only need to export the other components.

Notice that custom components names should be capitalized.

export default function AdminDashboard() {...}
export const ShowActionBtns = () => {...}

// Usage
import AdminDashboard, {ShowActionBtns} from './Components.js'

// Same, just both named imports
export function AdminDashboard() {...}
export const ShowActionBtns = () => {...}

// Usage
import {AdminDashboard, ShowActionBtns} from './Components.js'

See export on MDN
Comment: OK, but can I do that for instance. I edited the post you can see above.

React default function


Como armazenar e utilizar um vetor no Firebase no Android?

Question: Estou com um problema no desenvolvimento do meu app que não consigo resolver e não encontrei algo que me ajudasse. Tal app estava funcionando tranquilamente com dados armazenados em variáveis, mas ao incluir o Firebase tive alguns problemas em armazenar um array.
Fiz um algorítimo em uma classe que recebe e processa dois vetores que, inicialmente, são armazenados em variáveis:
A ideia é poder armazenar um vetor(array) no firebase e poder utilizá-lo normalmente no meu app, sendo que eu possa utilizar as propriedades do mesmo, como obtenção de valores array(i), tamanho array.length, etc...
pois preciso para alimentar outra classe:
public class Busca_Horario {

    public String[] timeSelect(String[] entrada1, String[] entrada2){

}

Vários tutoriais na internet utilizam comandos do firebase obsoletos e não me serviram.
Por favor me ajudem!
Answer: O Firebase não tem um recurso para distinguir entre uma String e um Array, então você terá que criar seus próprios vetores.
Eu geralmente separo os valores utilizando um ;: -07:35;07:14;08:25;09:65;.....n
Então, quando você for buscar estes valores, basta dar um split na String recebida:
 String[] valoresFirebase = getFirebaseValues().split(';');

Fazendo com que crie seu vetor.
Answer: Com base na resposta do Matheus, segue o meu resultado funcional:
Adicionei uma simples string em uma child no Firebase e utilizei o seguinte comando para buscar esse string e transforma-lo em array do tipo String[].
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String string = dataSnapshot.getValue().toString();
        String[] array = string.split(",");

        for (int i = 0; i < array.length; i++ )
        System.out.println(array[i]); //Para observar o seu resultado
    }

Assim, o método split() separa o array a cada vez que encontra a "," (virgula, neste caso, ou qualquer outro termo) em uma posição do array String[] array.
Comment: Boa Edeson, fico feliz em ter ajudado.