How to get Average of grouped results in Linq query

Question: I have a linq query that gets ratings from the previous 12 months:
var ratingsByMonth =
    from month in Enumerable.Range(0, 12)
    let key = new { Year = DateTime.Now.AddMonths(-month).Year, Month = DateTime.Now.AddMonths(-month).Month }
    join groupedRating in ratings on key
            equals new
            {
                groupedRating.RatingDate.Year,
                groupedRating.RatingDate.Month
            } into g
    select new {
        Date = key,
        Rating = g.Select(x=>x.Rating)
    };

ratingsByMonth returns the following JSON from my data set:
{Date: {Year: 2016, Month: 11}, Rating: [4]}
{Date: {Year: 2016, Month: 10}, Rating: [5, 5, 4]}
{Date: {Year: 2016, Month: 9}, Rating: []}
{Date: {Year: 2016, Month: 8}, Rating: []}
{Date: {Year: 2016, Month: 7}, Rating: []}
{Date: {Year: 2016, Month: 6}, Rating: []}
{Date: {Year: 2016, Month: 5}, Rating: []}
{Date: {Year: 2016, Month: 4}, Rating: []}
{Date: {Year: 2016, Month: 3}, Rating: []}
{Date: {Year: 2016, Month: 2}, Rating: []}
{Date: {Year: 2016, Month: 1}, Rating: []}
{Date: {Year: 2015, Month: 12}, Rating: []}

However I'm trying to aggregate the Rating field into an Average.  I've tried this:
return Json(new
{
    Average = ratingsByMonth.Average(x=>x.Rating),
    Dates = ratingsByMonth.Select(x => Date)
});

But I get the following error highlighted on the Average - line:

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable' to 'long?'

The output that I am looking for is:
{Date: {Year: 2016, Month: 11}, Rating: 4}
{Date: {Year: 2016, Month: 10}, Rating: 3.5}
{Date: {Year: 2016, Month: 9}, Rating: 0}
{Date: {Year: 2016, Month: 8}, Rating: 0}
{Date: {Year: 2016, Month: 7}, Rating: 0}
{Date: {Year: 2016, Month: 6}, Rating: 0}
{Date: {Year: 2016, Month: 5}, Rating: 0}
{Date: {Year: 2016, Month: 4}, Rating: 0}
{Date: {Year: 2016, Month: 3}, Rating: 0}
{Date: {Year: 2016, Month: 2}, Rating: 0}
{Date: {Year: 2016, Month: 1}, Rating: 0}
{Date: {Year: 2015, Month: 12}, Rating: 0}

Edit:
Have tried changing to the following:
return Json(new
{
    Average = ratingsByMonth.Select(x => x.Rating).SelectMany(x => x).Average(),
    Dates = ratingsByMonth.Select(x => x.Date.Month)
});

However, this just gives me a single 'Average' value across the whole data set, rather than an average per date.
Edit:
Here is sample data:
RatingID    Rating  RatingDate
5           5   2016-10-09 20:11:29.590
11          0   2016-10-09 20:14:42.503
21          5   2016-10-09 20:24:15.667
60          4   2016-10-28 11:01:21.220
64          4   2016-11-03 16:30:47.657

So for November the average should be 4, and October should be 3.5 (5+0+5+4 / 4)
Comment: There is a mismatch between the json and what you show in the linq. is it Date or GroupCriteria? Also show the desired output given the example data. I think your may be looking for a SelectMany and then Average
Comment: Thanks, have updated
Answer: In the original query you probably want to do this.
//other code removed for brevity
select new {
    Date = key,
    Rating = g.Count() > 0 ? g.Average(x => x.Rating) : 0
};

And then return the result
return Json(ratingsByMonth);

Comment: Have tried this, but everytime I run an Average() at this point, I get Sequence contains no elements.  Have tried adding .Where(x=x.Rating != 0)
Comment: Ok. Can I see a small sample of ratings data
Comment: I've updated to show the exact output from ratingsByMonth and the desired output.  Note that for Oct, ratingsByMonth is ignoring one of the 0 entries.
Comment: Perfect!  Thank you very much.
Answer: The issue here is that the property Rating is itself a sequence, not a discrete value that you can ask the Average method to consider.
It sounds like you actually want to do something like: flatten all of the Rating collections into a single sequence and then take the average across all of the resulting values.
Something like:
var avg = ratingsByMonth.Select(x => x.Rating).SelectMany(x => x).Average()

This uses Select to produce a sequence of Rating arrays. SelectMany then flattens the list, after which you can take the average.
Comment: Thanks for looking, have updated my question with the results, wasn't quite what I was after. :-)


$E(X|Y)=0$ and $E(X|Z)=0$ imply $E(X|Y,Z)=0$?

Question: Is it true that
$$
E(X|Y)=0\quad\text{and}\quad E(X|Z)=0
$$
imply $E(X|Y,Z)=0$? From iterated expectations, I understand that $E(X|Y,Z)=0$ implies both $E(X|Y)=0$ and $E(X|Z)=0$ but I don't know how to think about it in the reverse direction.
Comment: Maybe I am wrong but does $E(X|Y) = E(X|Y\land (Z \lor \neg Z))$ ?
Comment: @davcha These are random variables, not propositions.
Answer: Here is a counterexample: assume that $Y$ and $Z$ are independent, non Dirac, centered, and consider $$X=YZ.$$ Then $E(X\mid Y)=YE(Z)=0$ and $E(X\mid Z)=ZE(Y)=0$ while $E(X\mid Y,Z)=X$.
Comment: thanks Did and thanks for your comments on the other answer. I need to study this subject more for sure.


How do I add watermark to the image with insert module

Question: I use the combination of Wysiwyg and Insert modules to insert image.
How do add watermark while upload the image?
Can the watermark selected in certain taxanomy?
Answer: Your question is threefold:
Adding a watermark
For this, I suggest using ImageCache Actions module. Of the effects it provides, first one is:

Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

Selecting watermark
Image field does not know about taxonomy field when it decides how to render it's content. You could hack it together in your template. I would rather go for Formatter Field - not exactly what you described, but use case on module page seems to fit your needs:

For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Preventing original image from being downloaded
Drupal modifies user-provided content on display, not on save. This means your original image will be up there, without watermark. Image Style Access claims to be the solution:

This module provides access control for image files. Each access configuration can be set to allow or deny access to images and their derivatives by:

Disclaimer: I never used this one .


Variant of Peter-Weyl theorem

Question: In Bump, Automorphic forms and representations, Thm. 2.3.3 (p. 174), there is a theorem to the effect that the right regular representation of $G$ on the Hilbert space
$L^2(\Gamma \backslash G, \chi)$ decomposes into a Hilbert space direct sum of irreducible subrepresentations. Here $G$ is, say, a connected Lie group with $\Gamma$ a cocompact discrete subgroup, and $L^2(\Gamma \backslash G, \chi)$ is the Hilbert space of square-integrable (on a fundamental domain for $\Gamma \backslash G$) functions on $G$ with the property that $f(\gamma g) = \chi(\gamma)f(g)$ for $\gamma \in \Gamma$. In Bump we have $G = PGL_2^+(\mathbf{R})$ but I don't think this matters in the context of this question. The method of proof is by applying the spectral theorem for compact operators to the operator $\rho(\phi)$ obtained by integrating the right regular representation $\rho$ against an appropriate compactly-supported smooth function $\phi$ on $G$. I think the exact same proof can be applied to prove part II of the Peter-Weyl theorem on Wikipedia: any unitary Hilbert space representation of a compact group $G$ can be decomposed as a Hilbert space direct sum of irreducible subrepresentations.
Is there a way to use part II of the Peter-Weyl theorem to directly deduce the theorem in Bump? $L^2(\Gamma \backslash G, \chi)$ is isomorphic as a vector space to $L^2(\Gamma \backslash G)$, but I don't know if this isomorphism can be chosen to be $G$-intertwining.
Also, can one also show in this case that the irreducible components of $L^2(\Gamma \backslash G, \chi)$ are finite-dimensional?
Answer: $\chi$ has finite image ? $H=\ker(\chi)$.
Given an irreducible representation of $G$ (acting on the right) on $L^2(H\setminus G)$, as $H\setminus \Gamma$ is abelian ie. $H \gamma\gamma'=H \gamma'\gamma$, the map $$\Pi_\chi f(x) = \sum_{\gamma\in H\setminus \Gamma} \chi(\gamma)f(H\gamma x)$$ sends it either to $0$ or to an irreducible representation of $G$ on $$L^2(\Gamma\setminus G,\chi)=\{ f\in L^2(H\setminus G), \forall \gamma\in \Gamma,x\in G, f(H\gamma x)=\chi(H\gamma)f(Hx)\}$$
Comment: Thanks! Makes sense. Do you think there is a way to get something like this to work when $\chi$ doesn't have finite image? Of course it is a natural assumption to make, but I don't know whether it is reasonable because I don't know the rest of the theory -- maybe you can enlighten me on this?
Comment: It seems to me that any analogous formulaic expressions for $G$-intertwinings between the two spaces would have very serious convergence problems... Conceivably with some convergence factors, one could find some vanishing-of-L-function condition or such essentially equivalent to finiteness and non-zero-ness of some _part_ of the intertwining. That is, a condition for the same repn of $G$ to occur in both, and be mapped to each other by the intertwining. I have no idea why this could happen, in contrast to the finite-image case, where we have commensurability of the kernel and $\Gamma$...

Variant of Peter-Weyl theorem


Which guitar to pick for playing flamenco?

Question: Where I live there are several music shops. Although they sell a great variety of guitars, none has the category "flamenco guitar."
I'd like to buy a guitar to play flamenco. What features shall I look for to get that hard flamenco sound instead of softer, sustained classical guitar sound?
Apparently, I cannot try all the guitars in the store, but I can ask for specific things such as front, side and back plate materials, width of zero fret etc.
Basically, my question is, how can I narrow down my choices for a flamenco guitar without playing it?
Answer: You want low action, probably the most significant difference in a proper flamenco guitar. If available, get cypress (most common for "flamenca blanca" guitars) and you'll need a plate (golpeador) but you can always just slap one on yourself. Stear clear of anything with a trussrod in it. You don't want a lot of weight in a flamenco guitar. Usually the top of a flamenco guitar is light and it has less weight in the bracings.
When everything is said and done, it's how you play the instrument that will define whether you sound flamenco or not, not the instrument itself.
As a point of history, it's interesting to look at when the difference between flamenco and classical guitars emerged. Antonio de Torres made no distinction between the two and luthiers will use derivatives of his design for both kinds of guitars. They only started going their separate ways in the 20th century, and it is only with Andres Segovia, who single-handedly created this artificial rift between classical and flamenco, that the guitars really start to change. The point being that until not that long ago classical and flamenco guitar was the same thing.
Answer: You won't need to play all the guitars in the store, as most won't be suitable. The guys in the shop ought to be able to offer you half a dozen to try, acoustic obviously. If they can't or won't, then that's not the shop to even consider buying from!
The strings will most likely be nylon or carbon, as opposed to steel, and some there's a choice between wound and plain 3rds. If you don't play flamenco already, it might be best to work on it with the classical guitar, as eventually, you'll discover whether you like soft or hard strings better - they're not sold in guages, but tensions.
Comment: If you play, surely you have a pretty shrewd idea. If they don't, then they need to do some homework, otherwise they're not getting your custom.
Comment: You say there are several music shops.But you ask how you can narrow choices without playing. I'd say you cannot. The guitars need to be played.
Comment: I do play flamenco, and when I asked for a flamenco guitar where I used to live, they offered me specific guitars to choose from. But here, when I ask for flamenco guitar, they say that they don't know what the difference is.
Comment: I do not have any other choices.
Comment: By asking for specific features, I can narrow down. For instance, I can say "please show me the guitars with back plates made of spruce."
Comment: That's hardly going to narrow things down. Don't think a spruce back is any better for flamenco.
Comment: Unfortunately, I am not seeking advice on *where* to buy. Rather, I'm seeking advice on materials and features of a good flamenco guitar.


I keep getting "Exception in thread "main" java.util.NoSuchElementException"

Question: So I'm trying to make a simple program in Java that reads a text file (from a command line argument) and the user can check to see if a number they input is in the text file.
File inputFile = new File(args[0]);
Scanner scanman = new Scanner(inputFile); //Scans the input file
Scanner scanman_2 = new Scanner(System.in); //Scans for keyboard input
int storage[] = new int[30]; //Will be used to store the numbers from the .txt file

for(int i=0; i<storage.length; i++) {
  storage[i]=scanman.nextInt();
  }
System.out.println("WELCOME TO THE NUMERICAL DATABASE"+
                  "\nTO CHECK TO SEE IF YOUR NUMBER IN THE DATABASE"+
                  "\nPLEASE ENTER IT BELOW! TO QUIT: HIT CTRL+Z!");
while(scanman_2.hasNext()){
  int num_store = scanman_2.nextInt();
  boolean alert = false;
  for (int i=0; i<storage.length; i++) {
     if(storage[i]==num_store){
        alert=true;
        }
     }
  if (alert) {
     System.out.println("Yep "+num_store+" is in the database\n");
     }
  else {
     System.out.println("Nope, "+num_store+" is not in the database\n");
     }
  }
System.out.println("See ya!");
  }
}

Everytime I attempt to run it I keep getting:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Database.main(Database.java:17)

I've done a program similar to this and had no problems. Does anyone know what I'm doing wrong?
Answer: You are repeatedly calling nextInt(), but not testing to see if there is a next int. Change this
for(int i=0; i<storage.length; i++) {
  storage[i]=scanman.nextInt();
}

to this
for(int i=0; i<storage.length  &&  scanman.hasNext(); i++) {
  storage[i]=scanman.nextInt();
}

You'll need to determine if this is acceptable given your requirements, and if not, figure out why storage.length and the number of int-inputs are different than you expect.
Answer: Adding the scannerName.hasNext() to my for loop fixed the issue.


Was Hooper offside for Australia's first disallowed try?

Question: During the England Vs Australia rugby union international on 18th November 2017 at Twickenham, Michael Hooper scored a try for Australia that was disallowed due to him being offside. According to the BBC's Guide to the offside law...

A player is offside if he is in front of a team-mate who last played the ball AND they actively try to play the ball

When Tevita Kuridrani kicked the ball forward ("played the ball") then Hooper was clearly offside as he was ahead of the kicker, however, he did not play this ball! When Marika Koroibete did play the ball, Hooper was behind him and hence in an onside position.
So, was Hooper offside? A video of the try can be found here
Answer: I believe the match officials decision is correct under a strict interpretation of the 10-metre law, 11.4(a), since in the video you link to Hooper appears to continue running forwards, rather than attempting to move back behind a line ten metres from the (onside) opposition players until another player puts him onside by moving in front of him. This is certainly an unlucky decision to go against the team though, and it would have been understandable if it had gone the other way.
Comment: @KevinAnthonyOppegaardRose because slowing his run isn't the same thing as turning around and walking back towards his own try line. The relevant bit of the  law says "(b) *While moving away*, the offside player cannot be put onside by any action of the opposing team. However, before the player has moved the full 10 metres, the player can be put onside by any onside team-mate who runs in front of the player." and unlike, say, deciding whether a pass was forward, there's not strictly meant to be leeway for momentum.
Comment: Indeed, he was offside and never put onside again. However, giving the try would have made no sense, and gone against the point of an offside law, it's not understandable at all.
Comment: Interesting, Hooper did definitely slow down, but he never went behind the original kicker nor was there ever more than 10 meters between him and the ball so I think you are correct.
Curious, had he gone behind the kicker would he then be onside or does the 10 meter rule mean he would still be offside and if so, what happens when they are closer to the try-line than 10 meters? Surely he cant be expected to run back behind a 10 meter line?
Comment: @KevinAnthonyOppegaardRose Any onside player can put another player onside by moving past them while they retire, not just the original kicker (law 11.4b). Players aren't necessarily expected to get the full ten metres before this happens, but they do need to be seen to make an effort to get back onside, rather than simply waiting around for play to catch up with them.
Comment: @origimbo hmmm, so why was Hooper offside? He clearly slowed his run until he was onside before speeding up again. This is the confusion I am having.
Answer: In relation to your question on the offside ruling against Michael Hooper, it was a correct (albeit tough) call.
My analysis is as follows:

In general play, a player if offside if he's in front of a team-mate who last played the ball.
Under Law 11.1(c), when a team-mate of an offside player kicks ahead, the offside player must not move forward until the player has been put onside.
Under Law 11.2(c), when the kicker or team-mate who was onside runs in front of the offside player, the player is put onside. However, the offside player cannot be put onside if he has already moved forward.
In this case, MH was offside when TK kicked ahead.
MH put his hands in the air to acknowledge he was offside but kept moving forward.
MK was behind TK so onside when he gave chase.
MK quickly ran past MH which would have put MH onside if he had stopped moving forward as soon as TK kicked.
Unfortunately, there was a short period before MK run past him where MH kept moving ahead.
This was the basis for offside ruling and the try being disallowed.
To add extra confusion, there was some comment in the media to the effect that MK had kicked the ball which put MH back onside.
This is not relevant as the offside player in this situation can't be put back onside by his teammate.


Ancora de rolagem

Question: Bom dia,
estou tentando fazer um indice clicavel com rolagem em meu blog.
Porém o codigo que fiz não funciona quando cria a pagina, ele altera a url ao invez de ir para o ID informado. Qual seria a melhor forma de resolver isso?
Segue link da pagina de teste -> https://www.mundoinfantilstore.com.br/premium-meninos
Segue codigo:

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

div com a âncora!

Teste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste teste

div com a âncora!

Teste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste teste

div com a âncora!

Teste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste teste

div com a âncora!

Teste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste testeTeste teste teste teste teste

Comment: Seu código está fazendo `/#ancora` e deveria ser `/premium-meninos#ancora`
Answer: Cara usa esse exemplo aqui.
é muito simples
$('a[href^="#"]').on('click', function(e) {
    e.preventDefault();
    var id = $(this).attr('href'),
            targetOffset = $(id).offset().top;

    $('html, body').animate({
        scrollTop: targetOffset - 100
    }, 500);
});

Usei essa referencia aqui caso queira mais detalhes.
https://www.origamid.com/codex/scroll-suave-para-link-interno/

Ancora de rolagem


ffmpeg animated gif is blotchy

Question: I am generating an animated gif from an mp4 ... but due (I think) to color reduction (gif requires -pix_fmt rgb24) the result is somewhat ... blotchy?  like running an image through an oil paint (or maybe "posterize") special effect filter.  I think that the quality could be better, but I don't know what to tweak.
Not sure about this ... but ooking at the color palette of the resulting gif in an image editor it does not even appear to have attempted to create a color palette specific to this clip, but instead is attempting to us a generic palette ... which wastes a lot of pixmap space.  That is, if I am interpreting this correctly.
Any tips on preserving the original video image instead of getting a "posterized" animated gif?
Comment: See [How do I convert a video to GIF using ffmpeg, with reasonable quality](http://superuser.com/a/556031/110524)?
Comment: You may be interested in [this](http://stackoverflow.com/questions/6079150/how-to-generate-gif-from-avi-using-ffmpeg).
Answer: To get better looking gifs, you can use generated palettes. palettegen filter will generate a png palette to use with the paletteuse filter.
ffmpeg -i input.mkv -vf palettegen palette.png
ffmpeg -i input.mkv -i palette.png -lavfi paletteuse output.gif

Answer: You can try using -vf format=rgb8,format=rgb24.
Comment: This doesn't improve the quality for me.

ffmpeg animated gif is blotchy


Função imprimir lista circular

Question: Pessoal estou com uma dúvida de onde e como devo mudar para essa função de imprimir lista circular fique correta.
Está abaixo é uma função imprimir de uma lista ligada:
void imprime_lista(tipo_lista* p)
{
while (p != NULL)
{
    printf("%d\n", p->info);
    p = p -> prox;
}
printf("\n");
}

Answer: Só muda que o critério de parada do laço de repetição vai ser quando chegar ao primeiro. É necessário também trocar o whilepor do, porque a lista já começa no primeiro elemento e com o while não irá imprimir nada.
void imprime_lista(tipo_lista* p)
{
    if(p==NULL)
        return;
    tipo_lista* primeiro = p;
    do
    {
        printf("%d\n", p->info);
        p = p -> prox;
    }while(p != primeiro);
    printf("\n");
}

Comment: Talvez convenha verificar antes de entrar no `do {} while` se `primeiro` não é `NULL` e pôr `(p && p != primeiro)` como critério de parada; assim, se `p` for vazia ou não for uma lista circular de  verdade, a função não se perde.
Comment: Se passar uma lista vazia o programa vai dar erro mesmo. Adicionei um if para corrigir isso. Outra coisa que pode estar causando o erro é que uma lista que não é circular foi passada.
Comment: Provavelmente sua lista circular está errada em algum ponto
Comment: A função de inserir está errada, ela está inserindo como uma lista simples e não como circular, então depois do último elemento a lista vai para NULL e é onde o erro acontece.
Comment: Deu certo, porém deu a mensagem de o programa parou de funcionar, na `main`estou chamando `imprime_lista(p);`
Comment: Continua a mesma coisa
Comment: Da uma olhada por favor: https://pastebin.com/9VKC7uBK
Comment: @LucasTrigueiro eu mudei a função inserir, o atual código está assim: [códigocompleto]: https://pastebin.com/GBd9xjCH   Agora não sei onde está acontecendo o erro se é na função imprime ou insere. Se você executar não sai nada na tela. Valeu.
Comment: O erro é na insere, porque você verifica se é null e retorna e como a lista começa em null o programa nunca vai sair disso.

Função imprimir lista circular


How Do I Use CancellationTokenSource With DbContext.Database.SqlQuery(Sp, Param)?

Question: How Do I Use CancellationTokenSource With DbContext.Database.SqlQuery(Sp, Param)?
I'm using EF6.2 and running a stored procedure with a return type.
var task = Db.Database.SqlQuery<ResultType>(sp, params).ToListAsync();

foreach(var result in task.Result)
{
   var row = result;
}

Our current solution has cancellation tokens but doesn't return anything:
var task = Db.Database.ExecuteSqlCommandAsync(sp, tokenSource.Token, param);

SqlQuery only has the one method signiture, and I cant see anything about canceling in the documentation
How do I use the first method  AND include a cancellation token? Edit: Or is there another method I should use?

Additional Info: Our current solution ExecuteSqlCommandAsync() returns a task that just has a "completed" int status as the return type. The stored procedures I'm calling was just an INSERT... but I need to change it to a SELECT so we can produce files with the results.
So I need a EF method that returns a task of type "ResultType" so I can foreach through them and produce our files.
SqlQuery<>() does this... but without the ability to add a cancellation token (by the looks of it anyway, hence the question)
Comment: @Will I'm sorry if it wasn't clear - ExecuteSqlCommandAsync() returns a task with a result of int (int for the complete status of the task). Its for UPDATE or INSERT sps, whereas the sp I want to call is a SELECT.
Comment: @PeterBons that's not the final code, I was more to show that I do want a type returned. We will be using the task correctly in the actual code
Comment: Maybe, maybe not... You can test it by using Profiler to see if just getting the task hits the database. There's lots of magic in EF land. Anyhow, good luck.
Comment: You have to pass the token to .ToListAsync(). Only when .ToListAsync(cancellationToken) is called the query is materialized and send to the server. But beware that the option to pass a cancellationtoken might not have the effect you are hoping to see, see https://stackoverflow.com/questions/25387636/ef6-tolistasync-cancel-long-query-not-working TL;DR: the query will still run to completion at sql server database level.
Comment: *"Our current solution has cancellation tokens but doesn't return anything:"* well, that seems like your problem. You should probably assume that *in fact, it isn't a joke method to put your off the scent*. It **does** return things. You're not using it correctly. Your first step is to examine your variables at runtime when calling both methods to ensure you're not screwing something up simple. Next step is to use Sql Profiler to examine both queries as they hit the database. What are the differences? Why are they different?
Comment: @Will I've updated the main description to further explain the situation
Comment: Aaaah, that makes a lot of sense.  Looking at your first call, it struck me that the async part of that method chain isn't the `SqlQuery` part, but `ToListAsync`. There's probably an overload that takes the token.
Comment: @Will the first part (before ".ListAsync") returns a task. At that point it seems we are out of EF/SQL and into normal C# tasks. I can't see any method/variable on the task returned to add a token
Comment: @PeterBons how did I miss that?! Thank you Peter! I'll do further research tomorrow and test using the tokens
Comment: @PeterBons I'm happy with your answer, would you like to post your comment as an actual answer so I can mark it?
Answer: You have to pass the token to .ToListAsync(). Only when .ToListAsync(cancellationToken) is called the query is materialized and send to the server.
But beware that the option to pass a CancellationToken might not have the effect you are hoping to see, see this Q&A/ TL;DR: the query will still run to completion at sql server database level.
Comment: Is there anything that could help us cancel the query generated by entityframework when we call ToListAsync()? I'm seeing in search that it only cancels the task in program but not the query in SQL


Average age of top five European football leagues?

Question: Toulouse France team with average age of 23.91 was the youngest team on pitch for domestic league 2016-17. Some article claimed Germany had the most number of team with the lowest average age.  But I'm interested in knowing,
What was the average age of top five European football leagues for domestic league 2016-2017?
Answer: From a ranking done by CIES Football Observatory manually calculating the result is as follows:

France Ligue 1: 24.1805 years
Spain La Liga: 24.2455 years
Germany Bundesliga: 24.968 years
Italy Serie A: 27.3375 years
England Priemier League: 27.857 years

I will recalculate again to verify. But this result shows France Ligue 1 was the league with lowest average on the pitch among Top 5 leagues for 2016/17.
Data table used for calculation [Source]:
Picture of the table is obtained from CIES Football Observatory.


GameScene.sks and GameScene.swift

Question: Having issues with the GameScene.sks and GameScene.swift. I was attempting to add a title screen to my project and it went downhill from there. The title screen works fine but the issue is when I edit the Gameviewcontroller.swift.
This is how I want it to look, mind you I deleted the gamescene.sks at the start of the project but I realized you need sks file when you switch between scenes
This is how it ends up looking when I re-add the gamescene.sks
Here is the GameViewController.Swift to the working file before added the TitleScreen
import UIKit
import SpriteKit
import GameplayKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = GameScene(size: view.bounds.size)
        let skView = view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        skView.presentScene(scene)
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }
}

Here it is after changing the view to load up the title screen first:
import UIKit
import SpriteKit
import GameplayKit

class GameViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

         if let scene = titleScreen(fileNamed: "titleScreen") {

                //Configure view
                let skView = self.view as! SKView
                skView.showsFPS = true
                skView.showsNodeCount = true
                skView.ignoresSiblingOrder = true
                // Set the scale mode to scale to fit the window
               // scene.scaleMode = .aspectFill

                scene.size = self.view.frame.size
                // Present the scene
                skView.presentScene(scene)

            }

    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }
}

Comment: Inspect anchor point in both ways. Use same scene scale mode. Check if positions of nodes are the same. If all of those matches, then you will have to see the same results. Also scene and a view size is a different thing so pay attention to that as well.
Answer: I think it may be that you aren't configuring your GameScene instance...
scene.scaleMode = .resizeFill is only called in your gameviewcontroller... yes?
that means only there is your FIRST scene getting configured.
In your title scene, wherever it is that you are presentScene, you need to configure your next scene...
func configureScene(_ scene: SKScene) -> SKScene {
  scene.scaleMode = .resizeFill
  scene.anchorPoint = CGPoint(x: 0.5, y: 0.5) // Or whatever you want..
  scene.size = UIWindow().frame.size // Or whatever size you want.
  return scene
}

Implement:
// Where self is an SKScene...
self.presentScene(configureScene(desiredScene))

Also as WW said, frame and scene sizes are different, and will affect how everything looks.

GameScene.sks and GameScene.swift


Forms api validate float

Question: when using the Drupal FAPI and needing a float number field you have to use type textfield.  What's the best way to validate that this data is a float during hook_form_validate9)?  Is there a built in function. or do you have to do is_float()?
Thanks.
Answer: Because form input is always a string, is better to use is_numeric().
See is_float() note.
Answer: Drupal does not have an is_float() wrapper function. So yes, if you want to check to see if a string is a float, use PHP's native is_float().
Answer: The FAPI provides the ability to define a validation callback on any element.  Many of the validation callbacks you would like to use already exist.
See:  https://api.drupal.org/api/drupal/includes!form.inc/function/element_validate_number/7.x
You would use it like this:
$form['my_numeric_field'] = array(
  '#type' => 'textfield',
  '#title' => t('My Numeric Field'),
  '#element_validate' => array('element_validate_number'),
);

Forms api validate float


Source Code Browser

Question: I'm looking for a piece of relatively simple software to browse large C++ project. What I would like is something that is somewhere between a simple text editor and a full-blown IDE like Eclipse. I would like syntax highlighting, a way to see all classes/methods defined in a file, a way to find where a particular method is called from and where a variable is declared/defined.
Any ideas?
Thank you!
Comment: Why is a full-blown IDE not suitable?
Comment: It might be a matter of opinion, but I would call everything that fulfills your requirements a full blown IDE (not necessarily a nice one depending on what other features it has, but still).
Comment: Possible duplicates: http://stackoverflow.com/questions/390707/c-source-code-comprehension-tools/1317763 http://stackoverflow.com/questions/1271513/c-code-visualization/1274445
Answer: If you want to know where a particular method is called from, you are going to require some heavy lifting from the IDE. Intellisense like features always compile the code under the hood to give you the benefits of finding where code is called, and where it is defined. I don't consider that lightweight really.
Answer: Try Geany.  It's a fairly light text editor with a gentle learning curve that has syntax highlighting, and at least a way to see what's defined in a file; it may have the rest available, too.  And it's available for multiple operating systems, since you don't specify.

Source Code Browser


Remove dates from rss

Question: can someone help me on how to remove or manually edit the post dates displayed on my drupal feeds? No I am not using views to create it.
Answer: Go to your content type you feed and click on "Manage Display". There you have different possibilities to change the way how your content looks in different view modes. You probably need to activate the view mode for RSS Feeds to change anything.

Remove dates from rss


How to get Flex 3 ComboBox width to adjust based on bound dataProvider contents having changed?

Question: In Flex 3, I've created a ComboBox within an MXML component similar to the following:
<mx:ComboBox id="comboBox" dataProvider="{_choices}" />

<mx:Script>
<![CDATA[
  import mx.collections.ArrayCollection;
  // etc...
  public function get choices():ArrayCollection { return _choices; }

  [Bindable]
  private var _choices:ArrayCollection =
    new ArrayCollection( [ { data: "ALL", label: "All" } ] );
  // etc...
]]>
</mx:Script>

</mx:HBox>

In the parent MXML application, I'm modifying the contents of the choices property:
myComponentId.choices.removeAll();
myComponentId.choices.addItem({data: "NY", label: "New York"});
myComponentId.choices.addItem({data: "CA", label: "California"});
// etc...

The binding is working in that the ComboBox is automatically picking up the new contents added at runtime, however it is not adjusting its width.  The initial width of the ComboBox is wide enough only to show the initial item "All" declared in the component.  However, I want and would have expected the ComboBox to re-size automatically during binding to be able to show "California", but it isn't.
How can I get the ComboBox to update its width after I have added new wider labels to its dataProvider?  Thank you!
Comment: how about setting width to 100% ... as in comboBox.percentWidth = 100;
Comment: Everybody: Sorry for not coming back to this sooner.  I've just gone through the solutions and marked the one that worked for me.
Comment: http://ifeedme.com/blog/?p=19 -there are nice solutions
Comment: Thanks. That is a nice solution, but to a different problem: Trying to get the dropdown to be a different size than the collapsed control.  I wanted the entire control, collapsed or not, to be the size of the widest item after I changed the contents.  @CapnNefarious's answer of **invalidateSize()** did the trick.
Answer: You probably just need to call invalidateProperties(), invalidateDisplayList(), invalidateSize(), or some combination of the three (I'm something of a flex newbie myself), to force an update to the component's measurements after changing the data provider or its contents.
myComponentId.invalidateSize();
myComponentId.invalidateDisplayList();
myComponentId.invalidateProperties();

Comment: +1.  Calling **invalidateSize()** after modifying the choices did update the width.  The other two didn't.
Comment: For what it's worth, this does not seem to work in Flex 4 using the mx:ComboBox control.
Answer: I would add a setter for choices and call validateNow() on the ComboBox at the end of the setter:
public function set choices(value:ArrayCollection):void
{
    _choices = value;

    comboBox.validateNow();
}

Comment: Calling **validateNow()** on the combobox after modifying the choices did *not* update the width.
Answer: I encountered the same problem and neither of these worked for me. I managed to solve this by creating a new event handler
menuComboBox.addEventListener(ResizeEvent.RESIZE, updateListWidth);

The method called in this event simply resizes the dropdown.width property.
private function updateListWidth(event:ResizeEvent):void {
        menuComboBox.dropdown.width = menuComboBox.width;
}

Comment: I tried your code and it didn't solve the problem.  Actually, assuming I'm reading this code right, it's not quite the problem I was having.  The combo-box, after having its contents modified, didn't have the right size even when *collapsed*.  It wasn't just the dropdown component that was at issue.


calling var that is function

Question: I have this script and need to be able to call the $play variable as a function i.e. restart the set interval the pause function works fine but I can't get it to restart on clicking play.
    if( itemsCount > 1 ) {
        // addNavigation
        var $navPlay= $('body').find('.play'),
        $navPause= $('body').find('.pause'),
        $imgWrapper= $rgGallery.find('div.rg-image'),
        $play = window.setInterval(function(){
            _navigate('right');
        }, 500);

        $navPlay.on('click', function( event ) {
            $play;
            return false;
        });

        $navPause.on('click', function( event ) {
            clearInterval($play);
            return false;
        });
    }
},

Comment: `$play` here isn't a function, it's an identifier for the interval you've set.
Comment: how do i use the identifier to call the function?
Comment: you don't. The interval has been set when you called setInterval, and his now called every 500ms to execute `_navigate`. So I assume what you want is a way to reactivate this interval on demand (when you receive a click, here)?
Comment: yes spot on sorry i don't know the right terminology
Answer: Haven't exactly had the time to create an example to replicate something similar to your use case, but something along these lines should do.
    function starter() {
        return (window.setInterval(function () {
            _navigate('right');
        }, 500));
    }

    // stuff
    if( itemsCount > 1 ) {
            // addNavigation
            var $navPlay        = $('body').find('.play'),
                $navPause       = $('body').find('.pause'),
                $imgWrapper     = $rgGallery.find('div.rg-image'),
                $play           = starter(); // auto-start (set to null if not desired)

            $navPlay.on('click', function( event ) {
                if (!$play) { // probably don't want to set this twice
                  $play = starter();
                }
                return false;
            });

            $navPause.on('click', function( event ) {
                if ($play) {
                    clearInterval($play);
                    $play = null;
                }
                return false;
            });
    }
    // stuff

Comment: My way still allows you to use the variable :) But great answer!
Comment: @Shawn31313: there's a slight danger with yours though: calling `$play` will override the previous `timeout`, so you won't be able to release it if you didn't before hand (would be a programmer error, just as it would be one with mine to not capture the return and then not be able to release either, but I prefer it that way).
Comment: True(: Well eh could you at least up mine :)
Comment: oh ok...well i like your too. so +1 for you. :D
Answer: If you want to use a variable as a function then just use function(){}
if (itemsCount > 1) {
    // addNavigation
    var timeout,
        $navPlay = $('body').find('.play'),
        $navPause = $('body').find('.pause'),
        $imgWrapper = $rgGallery.find('div.rg-image'),
        $play = function () {
            timeout = window.setInterval(function () {
                _navigate('right');
            }, 500);
        };

    $navPlay.on('click', function (event) {
        $play();
        return false;
    });

    $navPause.on('click', function (event) {
        clearInterval(timeout);
        return false;
    });
}

You can add variables in the parentheses just like a normal function and it works great. Also give you timeout a separate variable which you can globally.

calling var that is function


Nmake build failed

Question:
Tried to compile openSSl. Failed at nmake. I was able to enter "Perl Configure VC-WIN64A no-asm" I just can't compile openSSl. Any suggestions or any more information needed? I am using VS command prompt x64 Native tools.
Answer: Did you try:
<code>nmake clean
... A lot of output ...

nmake
</code>

Nmake build failed


Show that for all $u,v \in \mathbb{R}, u>v$ if and only if $u^3 > v^3$.

Question: Show that for all $u,v \in \mathbb{R}, u>v$ if and only if $u^3 > v^3$.
Hi, just wondering how everyone thinks best to prove this? I was thinking of using cases but not sure!
Thank you!
Comment: Possible duplicate of [$ x^3<y^3 \iff x<y $ proof issue.](https://math.stackexchange.com/questions/1672388/x3y3-iff-xy-proof-issue)
Answer: Hint: Use that $$a^3-b^3=(a-b) \left(a^2+a b+b^2\right)$$
It is $$a^2+b^2\geq 2|ab|$$ by AM.GM, so $$a^2+b^2+ab\geq 2|ab|+ab\geq 0$$ since $$2|ab|\geq -ab$$
Comment: Thank you, would it be wise to factories the quadratic further or am I missing something?
Comment: We have $$a^2+ab+b^2\geq 0$$ for all real $a,b$
Comment: I think you don't need cases, you need the factorization as i have written
Comment: How did you get the second line? I.E where is the 2 from
Comment: I have used the AM-GM inequality $$a+b\geq 2ab$$ for $$a,b\geq 0$$ and then i added $ab$ on both sides.
Comment: But how does this prove the claim that u>v?
Comment: If $$a>b$$ then we get $$a-b>0$$ and multiplying by $$a^2+ab+b^2>0$$ we get $$a^3-b^3>0$$
Comment: If $$a^3>b^3$$ then we have $$(a-b)(a^2+ab+b^2)=a^3-b^3>0$$ since it must be $$a>b$$


How to record device screen video using iOS sdk?

Question: I am doing a tutorial Application in which I have to take the iOS screen video.For view it is working fine but our requirement is to record the screen video when a video is running.I tried to play video using UIWebview and MPMoviePlayer.Until the player starts it is recording.But after starting the player I get only black screen.Any Suggestions.
I followed this link:
http://developer.apple.com/library/ios/#qa/qa1703/_index.html
 -(void) startRecording {

    // create the AVAssetWriter

    NSString *moviePath = [[self pathToDocumentsDirectory] stringByAppendingPathComponent:OUTPUT_FILE_NAME];

    if ([[NSFileManager defaultManager] fileExistsAtPath:moviePath]) {

    [[NSFileManager defaultManager] removeItemAtPath:moviePath error:nil];

    }

    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];

    NSError *movieError = nil;

    [assetWriter release];

    assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL

                                                fileType: AVFileTypeQuickTimeMovie

                                                   error: &movieError];

    NSDictionary *assetWriterInputSettings = [NSDictionary dictionaryWithObjectsAndKeys:

      AVVideoCodecH264, AVVideoCodecKey,

      [NSNumber numberWithInt:FRAME_WIDTH], AVVideoWidthKey,

      [NSNumber numberWithInt:FRAME_HEIGHT], AVVideoHeightKey,

      nil];

    assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeVideo

      outputSettings:assetWriterInputSettings];

    assetWriterInput.expectsMediaDataInRealTime = YES;

    [assetWriter addInput:assetWriterInput];

    [assetWriterPixelBufferAdaptor release];

    assetWriterPixelBufferAdaptor = [[AVAssetWriterInputPixelBufferAdaptor  alloc]

    initWithAssetWriterInput:assetWriterInput

    sourcePixelBufferAttributes:nil];

    [assetWriter startWriting];

    firstFrameWallClockTime = CFAbsoluteTimeGetCurrent();

    [assetWriter startSessionAtSourceTime: CMTimeMake(0, TIME_SCALE)];

    // start writing samples to it

    [assetWriterTimer release];

    assetWriterTimer = [NSTimer scheduledTimerWithTimeInterval:0.1

    target:self

      selector:@selector (writeSample:)

      userInfo:nil

      repeats:YES] ;

    }

    -(void) stopRecording {

    [assetWriterTimer invalidate];

    assetWriterTimer = nil;

    [assetWriter finishWriting];

    NSLog (@"finished writing");

    }

- (UIImage*)screenshot

{

    // Create a graphics context with the target size

    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration

    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext

    CGSize imageSize = [[UIScreen mainScreen] bounds].size;

CGFloat imageScale = imageSize.width / FRAME_WIDTH;

    if (NULL != UIGraphicsBeginImageContextWithOptions)

        UIGraphicsBeginImageContextWithOptions(imageSize, NO, imageScale);

    else

        UIGraphicsBeginImageContext(imageSize);

    CGContextRef context = UIGraphicsGetCurrentContext();

    // Iterate over every window from back to front

    for (UIWindow *window in [[UIApplication sharedApplication] windows])

    {

        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])

        {

            // -renderInContext: renders in the coordinate space of the layer,

            // so we must first apply the layer's geometry to the graphics context

            CGContextSaveGState(context);

            // Center the context around the window's anchor point

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            // Apply the window's transform about the anchor point

            CGContextConcatCTM(context, [window transform]);

            // Offset by the portion of the bounds left of and above the anchor point

            CGContextTranslateCTM(context,

                                  -[window bounds].size.width * [[window layer] anchorPoint].x,

                                  -[window bounds].size.height * [[window layer] anchorPoint].y);

            // Render the layer hierarchy to the current context

            [[window layer] renderInContext:context];

            // Restore the context

            CGContextRestoreGState(context);

        }

    }

    // Retrieve the screenshot image

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

-(void) writeSample: (NSTimer*) _timer {

if (assetWriterInput.readyForMoreMediaData) {

// CMSampleBufferRef sample = nil;

CVReturn cvErr = kCVReturnSuccess;

// get screenshot image!

CGImageRef image = (CGImageRef) [[self screenshot] CGImage];

NSLog (@"made screenshot");

// prepare the pixel buffer

CVPixelBufferRef pixelBuffer = NULL;

CFDataRef imageData= CGDataProviderCopyData(CGImageGetDataProvider(image));

NSLog (@"copied image data");

cvErr = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,

FRAME_WIDTH,

FRAME_HEIGHT,

kCVPixelFormatType_32BGRA,

(void*)CFDataGetBytePtr(imageData),

CGImageGetBytesPerRow(image),

NULL,

NULL,

NULL,

&pixelBuffer);

NSLog (@"CVPixelBufferCreateWithBytes returned %d", cvErr);

// calculate the time

CFAbsoluteTime thisFrameWallClockTime = CFAbsoluteTimeGetCurrent();

CFTimeInterval elapsedTime = thisFrameWallClockTime - firstFrameWallClockTime;

NSLog (@"elapsedTime: %f", elapsedTime);

CMTime presentationTime =  CMTimeMake (elapsedTime * TIME_SCALE, TIME_SCALE);

// write the sample

BOOL appended = [assetWriterPixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:presentationTime];

if (appended) {

NSLog (@"appended sample at time %lf", CMTimeGetSeconds(presentationTime));

} else {

NSLog (@"failed to append");

[self stopRecording];

self.startStopButton.selected = NO;

}

}

}

Where:
NSTimer *clockTimer;
NSTimer *assetWriterTimer;
AVMutableComposition *mutableComposition;
AVAssetWriter *assetWriter;
AVAssetWriterInput *assetWriterInput;
AVAssetWriterInputPixelBufferAdaptor *assetWriterPixelBufferAdaptor;
CFAbsoluteTime firstFrameWallClockTime;

Answer: I got a sample app from iOS Developer Library. AVSimpleEditor. Along with the video recording it can trim, rotate, crop and add music.
Description:
AVSimpleEditor is a simple AVFoundation based movie editing application which exercises the APIs of AVVideoComposition, AVAudioMix and demonstrates how they can be used for simple video editing tasks. It also demonstrates how they interact with playback (AVPlayerItem) and export (AVAssetExportSession). The application performs trim, rotate, crop, add music, add watermark and export.


Need to send a xml request from java and parse the xml response

Question: I need to send a xml request from a java standalone class. The xml request that I need to send is of the form -
http://url/query.do?
Request=<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Request initialTime="2011-03-11T16:40Z">
<Query>Java</Query></Request>

So i have put in
String xmlRequest = "url/query.do? Request=<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Request initialQueryTime="2011-03-11T16:40Z"> <Query>Java</Query></Request>"

and then
URL url = new URL(xmlRequest);
     URLConnection conn = (URLConnection)url.openConnection();
     //conn.connect();
     BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    conn.getInputStream()));

But I am getting a IOException - Server returned HTTP response code: 505 for URL at sun.net.www.protocol.http.HttpURLConnection.getInputStream.
This url when hit through a browser returns a xml response and I need to parse that XML using STAX.
Can anyone please provide some idea on how to achieve the above.
Can someone please provide some sample code or correct my code so that I am able to form the xml request and parse the xml response. Please help.
Thanks,
swati
Comment: The xml request is something http://url/query.do?
Request=
java
Comment: Please show a short but *complete* program. "Something like this" isn't terribly helpful when the problem may well be in what you're using as the URL. Putting XML in a *URL* seems very strange indeed... it would normally be in a request *body*.
Comment: Hi Jon, have edited my code part. see advise now.
Answer: Symbols '?', '&' and '=' are treated as argument and value separators in URL, so try to encode your XML first.
String xmlRequest = "url/query.do?Request=" + URLEncoder.encode("your xml", "UTF-8");
URL url = new URL(xmlRequest);
...

Browser performs URL encoding for every request. That's why it works.
Answer: This question is related to this one.
The error code 505 means the following:
The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client.
Answer: its advisable to use apache HTTP client library (it has many features which can be used in your case).
you can also use Apache Tika api.
consider the size of the URL being posted refer here..
using the apache HTTP client gets you the option to use the POST method instead of the GET method, this way you can post a fairly large file in the request.


Extracting data from a webpage where an unusual tag format is used

Question: Note:  has to be done in powershell.
I have searched and searched and have this one little problem that I can not seem to solve.
The page is in an unusual form of xml, and looks like this
<code><?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://foo.bar.moo.org/">WILBER</string>
</code>
This is the only thing on the page.  the only part that will ever change is WILBER might be something else.
I have tried:
<code>$site="http://lalaland.org/Getmoocow?input=$foo_name"
$data = (new-object System.Net.WebClient).DownloadString($site)
$foo = [regex]::Matches($data, '<string.*?>(.+)</string>') | % {$_.Captures[0].Groups[1].value}
</code>
and a few varients but no luck.  the only thing I need is is what is located between the string tags
Answer: So, given the string that you presented,
<code>[xml]$x = @"
>> <?xml version="1.0" encoding="utf-8" ?>
>> <string xmlns="http://foo.bar.moo.org/">WILBER</string>
>> "@
>>
$x.string.'#text'
WILBER
</code>
Comment: I have a feeling that this is not the entire string that you are getting back though.
Comment: yeah.  I tried your example worked great, however, when I actually tried it from the web page, it gave me  version="1.0" encoding="utf-8" as the string.  any idea how to get the wilber?
Comment: Not sure why it would do that. Updating the question with the string that you *actually* get from the page would help.
Comment: that was basically the same thing I was getting in IE, except I changed the http value. But I was able to get your example to work in my case by first downloading the page into a file then running it. after that it worked great.

My major issue is the little piece of information is from a database I do not have access to, so the person that does gave me a way to get it using the Get method.  I asked if there was a way to just get the value I needed, but he said no, that was the only way it was available....  yeah..  anyway thanks for your help.


Explain the error term in Euler method

Question: Task: I had to find out some estimates for M and L to make sure the proportional accucrazy is not above $10^{-4}$ in the Euler method with the problem below.
I am trying to understand the page 672 on this book here. The book provides the formula
$$\left|y(x_{n})-y_{n}\right|\leq \left(\frac{M}{2L}\right)\left(e^{L(x_{n}-x_{0})}-1\right)h$$
about the error where you can see the M and L (which looks like some use of Lambert function is needed or rough estimate for the upper bound, look at the $L$ term). There is also an example where it finds some upper bounds and claims some rough estimate. More precisely, I am trying to apply the method of deducing the error term on pages 673-674 for the problem 2 on page 676.
M
I cannot yet understand why the second derivative is used as an estimate for the $M$. On page 673, it just claims that assume that $|y''(x)|\leq M$ but cannot find any premise for it, the 2 in the above. This point about M on pages 673-674 is something black magic to me. Please, explain.
L
The L is apparently just length of the interval.
Answer:
Definitions
L
$L$ is not the length of the interval, but a Lipschitz constant: some
  number such that  $$|f(x,y_1) - f(x,y_2)| \le L|y_1 - y_2|$$
  satisfied for all $y_1,y_2,x$ (in some interval of interest).
M
Similarly, $M$ is any number such that the assumption $|y''(x)| \le M$
  is satisfied. The error analysis is also explained in this article
  here (reference taken from the Wikipedia article on the Euler
  method).

Example
Suppose the equation $y' = -\frac12 y$ with initial condition $y(0) = 1$ with the Euler method on the interval $x \in [0,1]$. We actually know the exact solution in this case, $y(x) = \exp(\frac12x)$.
Finding L
We note that $f(x,y) = \frac12 y$ in the example, so the equation
$$|f(x,y_1) - f(x,y_2)| \le L|y_1 - y_2|$$
becomes
$$|\frac12 y_1 - \frac12 y_2| \le L |y_1 - y_2|.$$
This equation is satisfied for $L = \frac12$, so this is the value of $L$ we will take (we can also have taken a bigger value for $L$, like $L=1$, in which case we'll get a result which is also valid but not as sharp).
Finding M
We need it to satisfy $|y''(x)| \le M$. Since we know the exact solution, $y(x) = \exp(\frac12x)$, we know that $y''(x) = \frac14\exp(\frac12x)$ and so $|y''(x)| \le \frac14$ on the interval $x \in [0,1]$. However, for most equations we do not know the exact solution, so let us pretend we do not. Then what we can do is the following: differentiate the differential equation $y'(x) = \frac12 y$ to get $y''(x) = \frac12 y'$, and then substitute the differential equation in it to get
$$y''(x) = \frac12 \cdot \frac12 y = \frac14y.$$
We do know that the numerical solution given by the Euler method is a decreasing sequence for this example, so $y\le1$ and thus $|y''(x)| \le \frac14$ (as we found before).
Conclusion
So, we can take $L = \frac12$ and $M = \frac14$ in the error bound.
Comment: ...the problem was such that we did not know the term $y$. In this case, my instructor showed me that one can from $\left|f(x,y_{1})-f(x,y_{2})\right|$ deduce some sort of upper bound for $L\left|y_{1}-y_{2}\right|$. Here, the separate-integration in the initial value problem will lead to $y$ where we get the upper bound. It is not crystal clear to me how we can make the Lipschnitz claim just by knowing the first derivative, there is something odd happening. Look we cannot get the function $y$ in the question but still we can get some sort of upper bound, some gap here.
Comment: Way late to the game, but I think it comes down to the fact that if $f$ and $\frac{\partial f}{\partial y}$ are continuous, it implies that $f$ satisfies the Lipschitz condition: That is, there exists an L such that  $|f(x,y_1) - f(x,y_2)| \le L|y_1 - y_2|$. The only thing that you are left to do is to determine what L is, as was done in the provided answer. Here is a proof: https://math.stackexchange.com/q/476075

Explain the error term in Euler method


Using change in rank to assess effectiveness of an intervention

Question: Is it possible to assess the effectiveness of a classroom intervention by:

Taking scores from an entrance exam administered before the intervention
Ranking these scores (i.e. 1st, 2nd, 3rd, ...)
Providing students with an optional learning app (the intervention)
Administering a final year exam
Ranking this final year exam
Using the directional change in rank (i.e. increased or decreased) to assess whether the learning app had a significant impact

If this is a valid experiment, what statistical methods should I use?
Answer: After considering this further, I feel that ranking items is a bad way to "normalize" the scores in these two tests for a number of reasons:

Ranking creates unwanted dependencies between participants. For example, imagine a scenario where you have 10 students undergoing this experiment. Then imagine that all 10 students performed equally well on the second test as they did on the first. This would result in all 10 students having the same rank on both tests (i.e. 1st -> 1st, 2nd -> 2nd etc.). However, if you imagine the same situation again, only now, with the person who was ranked 1st, ranking 10th on the second test (i.e. 1st -> 10th). What we'd see is 9 out of the 10 students increase their rankings (i.e. 2nd -> 1st, 3rd -> 2nd etc.) and only 1 decrease in ranking. This 1 person flunking would make it appear that 9/10 had improved while, in reality, they had only performed equally well.
Ties will almost certainly be different between tests which will also lead to the problem described above. For example, imagine there are no ties on the first test but then, in the second test, the person who was initially ranked 2nd gets the same score as the person who was initially ranked 1st. Even if all other students performed equally well on both tests, the "dense" ranking system would show that everyone ranked below 2nd had improved and increased in rank. Of course this specific example can be fixed by using a different ranking system, however, the other systems still introduce similar problems in different scenarios.
We lose information by ranking. For example, imagine the person who ranked 1st in the first test received a test score that was 50% higher than the person who was ranked 2nd. Then in the second test the person who was ranked 2nd performed extremely well and closed this 50% gap down to 5%. Looking at the rankings alone, we would miss this 45% improvement!

I've found that the best way to analyse this is to use the original scores without ranking. Essentially, group the students into two groups (students who took advantage of the optional intervention and those who didn't). We drew this line arbitrarily at 80% engagement rate (i.e. answering 80% of the optional questions).
We then take this information and run a t-test to check that we have a significant difference in means between these two groups. This gives us a general idea if there appears to be a significant difference.
In R this would look like:
my.t.test <- t.test(FINALEXAM ~ GROUP, data = my.data)
my.t.test # Show results of the t-test

Then to make things more robust you can use ANCOVA controlling for the entrance exam as "baseline academic ability".
Again, to do this in R you can simply use:
my.anova <- aov(FINALEXAM ~ PRETEST + GROUP, data = my.data)
summary(my.anova) # Show results of the ANOVA


CORS Error caused by JS files being requested by http in an https environment using Laravel Filament with Sail / Docker

Question: Environment: Laravel with Filament on Docker (Laravel Sail)
The request is made using https:// but there are 2 files (table.js and select.js) which seem to be being requested by http:// which is causing the following CORS error:
Access to script at 'http://test.docker.localhost/js/filament/forms/components/select.js?v=18.104.22.168' from origin 'https://test.docker.localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
async-alpine.js?v=18.104.22.168:1

GET http://test.docker.localhost/js/filament/forms/components/select.js?v=220.127.116.11 net::ERR_FAILED

Answer: This is caused due to reverse-proxying and the app thinking that it is being served by http when actually it's being served by https.
The following can be added to the bootstrap/app.php file in Laravel 11+ to resolve this:
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->trustProxies(at: [
            // proxy ips as array
        ]);
    })

Reference: https://laravel.com/docs/11.x/requests#configuring-trusted-proxies


Class inheriting from several Interfaces having same method signature

Question: 1) How to solve this problem in Java?
2) What if only the return types are different in the interfaces?
Comment: Related: http://stackoverflow.com/questions/2598009/method-name-collision-in-interface-implementation-java
Comment: If you have three methods which have incompatible signatures, they should have different names to describe what they do. There is no point calling all your methods `method`. you can try but is it going to help?
Answer:
1) How to solve this problem in Java?

Essentially, the different "versions" of the method in the respective interfaces all bind to the same implementation method.

If that's what you want, fine.
If you actually want a different version of the method for each interface then you are stuck.  You can't do that in Java.

2) What if only the return types are different in the interfaces?

If the return types are incompatible, you cannot write a class that implements all of the interfaces.  Compilation error.
So when are return types compatible?

Prior to Java 5.0, the return type of an overriding or implementing method had to be the same as the return of the overridden or implemented method.
In Java 5.0, the language was modified to allow you to override / implement a method with a return type that is a subclass of the return type of the overridden / implemented method.

So ... if you are using Java 5.0 or later ... you need to implement using a return type that is the same type or a subclass of all of the return types of all versions of the method.  If there is no such type, then the class is not implementable.  And obviously, this doesn't work for primitive return types, because no subclass relationship exists between primitive types.
(Note: in Java 5.0 +, we are talking about a subclass relationship between the declared return types ... not the runtime types of the returned objects.)
Answer: 1) This is not a real problem as an interface does not define an implementation. In the example all three cases are going to call the same implementation.
2) There is no problem if return types are compatible (see covariant return types).Simply, you can change the return type if the new one is extending the one defined in the interface:
<code>class A {
 ...
 List returnList();
}

class B extends A {
 ...
 ArrayList returnList(); // possible as an ArrayList is a List
}
</code>


regex (in gathering multiple sets of columns with tidyr)

Question: inspired by hadley's nifty gather approach in this answer I tried to use tidyr's gather() and spread() in combination with a regular expression, regex, but I seem to get it wrong on the regex.
I did study several regex questions; this one, this one, and also at regex101.com. I tried to circumvent the regex by using starts_with(), ends_with() and matches() inspired by this question, but with no luck.
I am asking here in the hope that someone can show where I get it wrong and I can solve it, preferably using, the select helpers from tidyselect.
I need to select 2 regex-groups one up to the last . and one consisting of what comes after the last ., I made this two example below, one where my code s working and one where I am stuck.
First the example that is working,
# install.packages(c("tidyverse"), dependencies = TRUE)
require(tidyverse)

The first data set, that work, looks like this,
myData1 <- tibble(
  id = 1:10,
  Wage.1997.1 = c(NA, 32:38, NA, NA),
  Wage.1997.2 = c(NA, 12:18, NA, NA),
  Wage.1998.1 = c(NA, 42:48, NA, NA),
  Wage.1998.2 = c(NA, 2:8, NA, NA),
  Wage.1998.3 =  c(NA, 42:48, NA, NA),
  Job.Type.1997.1 = NA,
  Job.Type.1997.2 = c(NA, rep(c('A', 'B'), 4), NA),
  Job.Type.1998.1 = c(NA, rep(c('A', 'B'), 4), NA),
  Job.Type.1998.2 = c(NA, rep(c('A', 'B'), 4), NA)
)

and this is how I gather() it,
myData1 %>% gather(key, value, -id) %>%
   extract(col = key, into = c("variable", "id.job"), regex = "(.*?\\..*?)\\.(.)$") %>%
   spread(variable, value)
#> # A tibble: 30 x 6
#>       id id.job Job.Type.1997 Job.Type.1998 Wage.1997 Wage.1998
#>    <int> <chr>  <chr>         <chr>         <chr>     <chr>
#>  1     1 1      <NA>          <NA>          <NA>      <NA>
#>  2     1 2      <NA>          <NA>          <NA>      <NA>
#>  3     1 3      <NA>          <NA>          <NA>      <NA>
#>  4     2 1      <NA>          A             32        42
#>  5     2 2      A             A             12        2
#>  6     2 3      <NA>          <NA>          <NA>      42
#>  7     3 1      <NA>          B             33        43
#>  8     3 2      B             B             13        3
#>  9     3 3      <NA>          <NA>          <NA>      43
#> 10     4 1      <NA>          A             34        44
#> # ... with 20 more rows

It works, I suspect I overdoing it with the regex, but it works. However, my real data can have either one or two digest at the end, i.e.
The second data, where I get stuck,
myData2 <- tibble(
  id = 1:10,
  Wage.1997.1 = c(NA, 32:38, NA, NA),
  Wage.1997.12 = c(NA, 12:18, NA, NA),
  Wage.1998.1 = c(NA, 42:48, NA, NA),
  Wage.1998.12 = c(NA, 2:8, NA, NA),
  Wage.1998.13 =  c(NA, 42:48, NA, NA),
  Job.Type.1997.1 = NA,
  Job.Type.1997.12 = c(NA, rep(c('A', 'B'), 4), NA),
  Job.Type.1998.1 = c(NA, rep(c('A', 'B'), 4), NA),
  Job.Type.1998.12 = c(NA, rep(c('A', 'B'), 4), NA)
)

Now, this is where I use (0[0-1]|1[0-9])$ for the second group, I also tried thing like \d{1}|\d{2}, but did that not work either.
myData2 %>% gather(key, value, -id) %>%
     extract(col = key, into = c("variable", "id.job"),
             regex = "(.*?\\..*?)\\.(0[0-1]|1[0-9])$") %>%
     spread(variable, value)

The expected output would be something like this,
#> # A tibble: 30 x 6
#>       id id.job Job.Type.1997 Job.Type.1998 Wage.1997 Wage.1998
#>    <int> <chr>  <chr>         <chr>         <chr>     <chr>
#>  1     1 1      <NA>          <NA>          <NA>      <NA>
#>  2     1 12     <NA>          <NA>          <NA>      <NA>
#>  3     1 13     <NA>          <NA>          <NA>      <NA>
#>  4     2 1      <NA>          A             32        42
#>  5     2 12     A             A             12        2
#>  6     2 13     <NA>          <NA>          <NA>      42
#>  7     3 1      <NA>          B             33        43
#>  8     3 12     B             B             13        3
#>  9     3 13     <NA>          <NA>          <NA>      43
#> 10     4 1      <NA>          A             34        44
#> # ... with 20 more rows

A simply solution à la t this question using select helpers like starts_with(), ends_with(), matches(), etc. would be appreciated.
Comment: @akrun, I added _expected output_. Thank you for your feedback!
Comment: so, simple! Thanks. I know. Thanks!
Comment: Can you show the expected output?  Are you looking for `myData2 %>% gather(key, value, -id)  %>% extract(col = key, into = c("variable", "id.job"), "^(.*)\\.([^.]+)$") %>% spread(variable, value)`
Answer: We can change the regex in extract to match characters and capture as group ((.*)) from the start (^) of the string followed by a dot (\\.) and one or more characters that are not a dot captured as a group (([^.]+)) till the end ($) of the string
myData2 %>%
    gather(key, value, -id)  %>%
    extract(col = key, into = c("variable", "id.job"), "^(.*)\\.([^.]+)$") %>%
    spread(variable, value)
# A tibble: 30 x 6
#      id id.job Job.Type.1997 Job.Type.1998 Wage.1997 Wage.1998
# * <int> <chr>  <chr>         <chr>         <chr>     <chr>
# 1     1 1      <NA>          <NA>          <NA>      <NA>
# 2     1 12     <NA>          <NA>          <NA>      <NA>
# 3     1 13     <NA>          <NA>          <NA>      <NA>
# 4     2 1      <NA>          A             32        42
# 5     2 12     A             A             12        2
# 6     2 13     <NA>          <NA>          <NA>      42
# 7     3 1      <NA>          B             33        43
# 8     3 12     B             B             13        3
# 9     3 13     <NA>          <NA>          <NA>      43
#10     4 1      <NA>          A             34        44
# ... with 20 more rows

Comment: @EricFail  Glad to know that it helped.  For regex learning, [this](https://www.regular-expressions.info/tutorial.html) seems to be good. In `R`, you may have to add escape for some expressions
Comment: Thanks a lot. That was super helpful. I realize it might seem mundane, but I spent way to long on this. I guess it's not possible to use _select helpers_ like `starts_with()`, `ends_with()`, `matches()` in this case. Can you possibly recommend any good `regex` tutorials for `R`-people?


How do I approach the following integral?

Question: Evaluate
$$\displaystyle \int_{-\infty}^{\infty} \frac{\cos x}{x^2+1}~dx$$
Comment: Tom: If you want to ask a new, different question, ask a new question, in a new thread. Please don't change the question that has already been answered to a different one.  It makes the answers below appear to not make sense, it is confusing for readers, and it won't help you get an answer.  I will edit back to the old version.  (Also, please consider sharing your thoughts on the problem while you are posting your new question if you choose to do so.)
Answer: Use Residue Theorem.
$$\int_{-\infty}^{\infty}\frac{\cos x}{x^2+1}dx=\Re\int_C\frac{e^{iz}}{z^2+1}dz=\Re 2\pi iRes|_{z=i}=\Re 2\pi i\frac{e^{-1}}{2i}=\frac{\pi}{e}.$$
Answer: Hints:
$$C_R:=[-R,R]\cup \Gamma_R:=\{z\in\Bbb C\;;\;z=Re^{it}\,,\;0\le t\le \pi\,\,,\,\,R>0\}$$
$$\left|\;\int\limits_{\Gamma_R}\frac{e^{iz}}{z^2+1}dz\;\right|\le \sup_{z\in\Gamma_R}\frac{e^{-R\sin t}}{R^2-1}R\pi\xrightarrow[R\to\infty]{}0\;,\;\;\text{since}\;\;R\sin t>0$$
$$\int\limits_{-R}^R\frac{e^{ix}}{x^2+1}dx\xrightarrow[R\to\infty]{}\int\limits_{-\infty}^\infty\frac{\cos t+i\sin t}{x^2+1}dx$$
$$\oint\limits_{C_R}f(z):=\frac{e^{iz}}{z^2+1}\,dz=2\pi iRes_{z=i}(f)=2\pi i\frac{e^{-1}}{2i}=\frac{\pi}{e}$$
Now put together the above, use Cauchy's Residue theorem and stuff.
Comment: +1 Nice sketch for the proof.
Answer: Since the simplest route has already been taken, I'll take another. The function $x\mapsto e^{-|x|}$ is integrable on $\mathbb{R}$, and it's Fourier transform is easily computed as
$$
\begin{align}
\int_{-\infty}^\infty e^{-|x|}e^{-itx}\,dx& = \int_0^\infty e^{-x(1+it)}\,dx + \int_{-\infty}^0 e^{x(1-it)}\,dx \\
& = \frac{1}{1+it} + \frac{1}{1-it} \\
& = \frac{2}{1+t^2}
\end{align}
$$
This Fourier transform is integrable. So by the Fourier inversion formula,
$$
\int_{-\infty}^\infty \frac{2}{1+t^2}e^{ixt}\,dt = 2\pi e^{-|x|}.
$$
Take $x = 1$ and divide both sides by $2$.
Comment: I guess I should note that this argument might be circular to a person who uses this Fourier transform to derive the inversion formula; I am not such a person, so it does not seem circular to me.
Comment: +1, but I think you mean "take $x=1$", not $x=0$.
Comment: Thanks Eric! I have edited accordingly.
Answer: Well that integral has poles at $z=i, -i$. You can integrate along a semicircle of radius $R>i$, use Cauchy's residue formula and let $R \rightarrow \infty$ and hope that the integral along the arc goes to $0$.
Comment: Either directly or using Jordan's Lemma, the integral on the semicircle goes to zero when $\,R\to\infty\,$
Comment: -1 It needs more than that.  The arc length goes as $\frac 1R$ so this would suggest the integral diverges logarithmically.  The oscillatory nature of cosine rescues this approach, but needs some justification.
Comment: Hmm, I might be wrong but here's what I got. The integral along the upper semicircle is given by $\int_{0}^{\pi} \frac{iRe^{it}cos(Re^{it})}{R^{2}e^{2it}+1} dt$, which should grow like $\frac{1}{R}$. Am I missing something?
Comment: The length of the semicircle grows as $\pi R$ which you have lost.  Multiplying by that it doesn't go to $0$ any more.  I should have said $R$ instead of $\frac 1R$ in my last comment.
Comment: Okay, I really think I'm missing something now because I have that term in my integrand. If we call OP's integrand $f$, then the path in question is $\gamma (t)= Re^{it}$, so $\int _{\gamma} f dz = \int _{0}^{\pi} f(\gamma(t)) \gamma'(t) dt$. Then we obtain the integrand I have, where the $iRe^{it}=\gamma ' (t)$ seems to be the arc length term you're talking about. I'm not sure where I'm going wrong, hopefully this helps clarify things.
Answer: $$f(x)=\frac1{1+x^2}\quad \quad \hat f(\xi)=\pi e^{-|\xi|}\\ \mathcal F[f(x)e^{inx}]=\hat f(\xi-n)$$
Note that $f\in L^1(\Bbb R)$, so $\hat f$ is continuous:
$$\int_{-\infty}^{+\infty}\frac{\cos x}{1+x^2}\,\mathrm dx = \frac12\int_{-\infty}^{+\infty}\lim_{\xi\to 0}\frac{e^{ix}}{1+x^2}e^{-ix\xi}\,\,\mathrm dx+\frac12\int_{-\infty}^{+\infty}\lim_{\xi\to 0}\frac{e^{-ix}}{1+x^2}e^{-ix\xi}\,\,\mathrm dx=\\ \frac{\pi}2\lim_{\xi\to0}(e^{-|\xi-1|}+e^{-|\xi+1|})=\frac{\pi}e$$


Presenting view controller over current context storyboard

Question: I have been trying to solve this for a while with a variety of people suggesting several different ways to achieve this and none of them working for me.
I am trying to display a view controller over the current context with a clear background. However each time I perform the segue the view controller underneath is removed from the view hierarchy.
Here is the presenting view controller.

And here is the current state when presenting the view modally.

As the segue is taking place the modal has the correct transparency effect however when the segue completes the background turns black indicating the view controller has been removed from the hierarchy.
Now many suggestions focus on setting up the modal in code however all these settings are available in the storyboard and I prefer to leave things like that in there. As suggested here I have setup my view controllers like this however I still have the above effect.
Here is my storyboard setup.
Presenting view controller settings

Segue settings

Modal view controller settings

Any help would be much appreciated.
Answer: you can make those view controllers child of the VC you want to present them on here, by making one view controller child of another, you can add view of child VC as a subview to the view of parent VC
you can then play with transparency/color of child VC view's
This can also be helpful tutorial
presenting view controller on top of the current one won't work for you, you will have add other view controller as child for the current one and then add it's view as subview to the current VC's view. then if you clear background color for child VC's view it will appear transparent and show you previous VC's view in background
Edit:
you can achieve the same effect using presentation controller here
Comment: Hi Usama, I was going to look at doing this with a container view and I know that it is possible with this. However what I am asking is possible using modal views. Others like the one I link to in the question have shown this technique to be working. However in my case it isn't for some reason.
Comment: i have vague idea that it can be done using presentation controllers which are introduced in iOS8>, have a look at them it might be helpful. i will post a link if find a way using presentation controllers
Comment: i have updated my answer, a tutorial is provided which shows how you can achieve the same effect using presentation controller. hope it helps
Comment: Thanks Usama. I had already seen this as an option however the storyboard methods should also work according to Apple's documentation. Writing custom transitioning delegates seems a little over the top for this simple effect but I have done this now and it works well. Thanks for your help.
Comment: First link in answer is dead (*Sorry, that page cannot be found.*).


Lifecycle of Jackson ObjectMapper in Spring

Question: Environment:
I use spring boot version 2.3.3.RELEASE

Problem
I register custom deserializers with @JsonComponent annotation.
In some modules and tests I @Autowire jacksons ObjectMapper.
Problem 1: I cannot @Autowire ObjectMapper in @JsonComponent or the @JsonComponent will be ignored completely (without error message)
Problem 2: I want to have the same instance of ObjectMapper in @JsonComponent (or at least OM with same configuration) that I can obtain by Autowire in other Components

Example
Since I don't want custom deserialization for some fields I use the ObjectMapper to use convertValue() in my custom deserializers.
I noticed, that I cannot @Autowire the ObjectMapper in any of my Deserializers or the Configuration will not be picked up for other ObjectMappers that are autowired in my Application (So the Deserializers are not registered correctly)
I'm obtaining the ObjectMapper in the Deserializer with (ObjectMapper) jsonParser.getCodec();
But this ObjectMapper is not configured correctly (meaning e.g. annotations on class/methods are ignored).
I want to deserialize my object as follows:
@Test
void testDeserializeFoo() throws IOException {
    ObjectMapper om = new ObjectMapper(); // this is obtained by jsonParser in deserializer but it behaves the same, since the ObjectMapper lacks the configuration
    InputStream is = getClass().getResourceAsStream("/json/foo.json");
    JsonNode fooNode = om.readTree(is);
    Foo foo =  om.convertValue(fooNode, Foo.class);
    log.info("Foo: " + foo);
}

The constructor of Foo is annotated with @JsonCreator.
The Problem is, that this annotation is ignored by the ObjectMapper I get from the parser in the custom Deserializer. This results in the following error message:

Invalid type definition for type
Foo:
Argument #0 has no property name, is not Injectable: can not use as
Creator [constructor for
Foo,
annotations: {interface
email@example.com(mode=DEFAULT)}]

Is it possible to have the same instance of ObjectMapper in my custom Deserializer that is used in other Components when Autowired?

Edit
Possible Solution / Test:
I was testing my deserializer like this:
private JsonParser getJsonParser(String resource) throws IOException {
        InputStream src = getInputStream(resource);
        return objectMapper.createParser(src);
}

@Test
void testDeserializeFoo() throws IOException {
    JsonParser parser = getJsonParser("/json/foo.json");
    Foo foo = deserializer.deserialize(parser, null);
    System.out.println(foo);
}

The problem was that the objectMapper in getParser() method was a new instance all the time. Now I use the autowired objectMapper. But how does this have any effect?

Conclusion:
I want to use the same instance of ObjectMapper in my JsonComponents (custom deserializers) as the Autowired ObjectMapper (which is provided by spring in other Components), or at least an ObjectMapper with the same configuration.
With configuration I mean: Enabled Jackson Features / Annotation Configurations on classes, methods, fields / registered modules and JsonComponents
Can someone please explain:

how and when ObjectMapper is configured in Spring (when are
Annotation configurations (JsonCreator, JsonProperty), Feature
configurations (like accepting upper case) in application.yml, Custom
JsonComponents etc registered on an ObjectMapper
what is the lifecycle of this objectMapper instance?
What is the lifecycle of a ContextConfiguration,
DeserializationConfiguration?
How does Spring and Jackson context relate to each other?

I looked for related topics, other answers related where:

Spring and Jackson context are not the same (but why, what does this mean?)
You need a HandlerInstantiator to Autowire (this is already default in my spring version I assume, also this does not explain why my custom deserializers are not picked up without any error messages when autowiring ObjectMapper in one of the deserializers)
Comment: I read your question about 3 times and still have no clue on what you are asking or trying to achieve. Looks like you want to register something with Jackson which will also use jackson aka a circulair dependency.
Comment: @ManuelWaltschek more clear, and more *focused* please. It looks like you're trying to ask several questions in one post.
Comment: Have you tried to create a bean which returns the instance of configured `ObjectMapper`?
Comment: Okay, I will try to make this more clear. I'll edit it later.

Although the questions on the bottom should be somehow clear, independently of the problem above.
Comment: @LHCHIN yes, as svr stated in the answer this still leads to unresolved circular dependencies / references.
Answer: In general you can use Jackson2ObjectMapperBuilder and build() to generate new object mapper instance with all the recent settings applied. The default ObjectMapper is provided by JackonsObjectMapperConfiguration in JackonAutoConfiguration. All jackson2 object mapper builder instances are created by JacksonObjectMapperBuilderConfiguration in JacksonAutoConfiguration. Details on configuring object mapper can be found here
You can further customize jackson2 object mapper builder using Jackson2ObjectMapperBuilderCustomizerConfiguration if you don't like the standard defaults in JacksonAutoConfiguration
Checkout this answer - it will answer your other questions
Coming to issue - Had the same issue when using jackson2objectbuilder/build or autowiring object mapper for ser/deser annotated with JsonComponent annotation. All these annotations are scanned by JsonComponentModule bean defined in JacksonAutoConfiguration and are registered with default object mapper and all the instances created by jackson2 object mapper builder. So it is not possible to use the not built object mapper and register the ser/deser at the same time. You are right the exception ( beancurrentlyincreationexception ) is suppressed by spring and json component module is not registered with message unresolvale circular reference for object mapper.
I didn't find any solution other than creating a new object mapper outside of spring managed.
Comment: Thank you, this was what I was looking for! So I can create a Bean in Configuration of Type Jackson2ObjectMapperBuilderCustomizerConfiguration to add additional configuration to the autoconfigured instances?
Comment: "I didn't find any solution other than creating a new object mapper outside of spring managed."

So how would I do this? Using Jackson2ObjectMapperBuilder and build() in the Deserializer, or can I do this in a singleton @Component (static instance)?
Comment: You are welcome - Creating your own Jackson2ObjectMapperBuilderCustomizerConfiguration bean will allow to further configure the jacksonObjectMapper unbuilt instance. You will still not be able to build instance as  JacksonAutoConfiguration will scan the JsonComponentModule - so you will end up with circular reference. I was able to create static class ObjectMapper variable without any customization for my need.