Why do I get a "Too Large or Too Small" error when calling Texture2D.GetData?

Question: I need to quickly save an image, and I am using Texture2D.GetData and SetData because simply saving and loading the image is way too slow. The image is 1024x1024.
RenderTarget2D Image = ChunkContainer.GetImg(x, y);
byte[] imageBuffer = new byte[1024 * 1024];
Image.GetData<byte>(imageBuffer);
b.Write(imageBuffer);

I get an ArgumentException error:
"The size of the data passed in is too large or too small for this resource."
So I can't save a 1024x1024 image? Is there a better way of doing this? Why isn't this working?
Answer: You are forgetting to add the Bit Depth, which is typically 4 bytes per pixel (1 byte for each: red, green, blue, alpha). Your array should be: 1024 x 1024 x BitDepth
Answer: What is the format of the image? How many bytes per pixel?
Per the documentation, you can see this error when the size of the array you are passing to GetData is too small to contain the render target's data. This seems to be the likely culprit here, since you are allocating 1024x1024 bytes. Unless you are using the Alpha8 format, each pixel in the render target is likely going to occupy at least two bytes of space. You need to figure out how many bytes are used per-pixel of your render target (by checking the Format property, for example). Once you know that, multiply your 1024 * 1024 calculation by that value.
For example, allocate an array of size 1024 * 1024 * 3 if you know your render target uses three bytes per pixel, et cetera.


Liferay integration options

Question: We have an existing large Java Web Application that is clustered across many servers.  We currently store our Word documents within our Oracle/BLOB and would like to move to a CMS solution like Liferay.    Ideally we would like to present our users a view of their directory/file within one of the pages of our existing application and implement some workflow on top of Liferay within our application.
I've been reading the Liferay documentation to get a good feel to how best integrate into an existing Liferay/CMS server and from what I can tell the only way is via Portlets and or IFrames.  So the integration happens in the GUI of the application.
We were hoping to integrate with Liferay within our Server calling SOAP/REST/JSON calls and then taking the results and displaying it within our application.
Could someone educate me on if this is feasible and if it is where I could get further information regarding this?
Answer: Yes, you can integrate just at "view side", but a good choice consists in usign Liferay ServiceBuilder.
It is a well documented Liferay's framework available for any custom portlet you want to write, allowing you to:
- automatically create a ready-to-use persistence layer (db DDL, ORM, cache configuration, transaction ecc...)
- expose local (in the same VM), remote (in the same VM, or by SOAP/REST/JS API/Mobile API) functionalities
You can surely combine both functionalities together, but you are free to use just one of them.
If it was a my choice, I would create a LR service wrapping the call to your external datasource.
In this way it will be able to partecipate in a distributed transaction (simply configuring a distributed transaction manager), to configure access to resource by using LR permissions framework, to be compliant with any kind of LR taglib (as SearchContainer: it should be very useful for showing a list of item)... and everything without the necessity to configure anything.
Several ways for achieving what I said are available... with a simple Google search I immediately fiund this guide.
Hope it helps.
Answer: Liferay allows you to write your own custom document store. You will need to implement few interfaces and configure LR to use it. That should do it. You can look at com.liferay.portlet.documentlibrary.store.BaseStore and com.liferay.portlet.documentlibrary.store.DBStore to understand how it can be done.
Thanks

Liferay integration options


Is there way to rearrange node on front page?

Question: I tried use weight module but it arrange node only on admin interface. Is there way set weight to node on front page?
Comment: Possible duplicate of [How can I recreate the default Views Frontpage?](http://drupal.stackexchange.com/questions/197176/how-can-i-recreate-the-default-views-frontpage)
Answer: You can create views with weight sorting nodes and set it as front page
Answer: Probably easiest if you create a view and list that on the homepage. I believe the listing of nodes on <code>/node</code> (the default homepage) are in reverse chronological by created date.
The checkbox "Sticky" under publish settings might be helpful, but a View would give you the most reliable results.


If a topological space is a path-connected, it is also connected. The converse fails. Can this be remedied?

Question: If a topological space is a path-connected, it is also connected. However, the converse of this theorem is false.
Can we generalize the notion of a path so that the converse also holds? I was thinking that maybe if the domain of a path was allowed to be an arbitrary connected totally ordered set, this might fix the problem.
EDIT. As Brian M. Scott explains in his answer, this doesn't fix the problem; so here's a last ditch-effort at salvaging the idea. Definition: A connected path in a topological space $X$ is a mapping $\gamma : T \rightarrow X,$ that preserves connectedness under direct images, where $T$ is a connected totally ordered set possessing both a least and a greatest element. Note in particular that $\gamma$ needn't be continuous.
Can anyone see whether this fixes the problem or not? We want to be able to prove that a topological space is path connected iff it is connected.
Anyway, here's the motivation.

The problem, as Brian explains, is that a connected linearly ordered space with endpoints is compact, so the continuous image of such a space is also compact and connected. This is a problem, because:

No compact, connected subset of the topologist's sine curve contains the origin and at least one other point of the curve, and
There exist countably infinite connected Hausdorff spaces, and there are no paths between distinct points in such a space; because if such a path existed, its image would be a compact countably infinite connected Hausdorff space with at least two points, and no such space exist.

So the problem seems to be the compactness of the image of the path, which is implied by the compactness of the domain, because the path is defined as a continuous function. Thus, weakening the requirement that paths need to be continuous might fix the problem.
Answer: Your suggestion would take care of the long line, since it is a connected linearly ordered space, but it wouldn't help with the topologist's sine curve for instance. A connected linearly ordered space with endpoints is compact, so the continuous image of such a space is also compact and connected, but no compact, connected subset of the topologist's sine curve contains the origin and at least one other point of the curve.
It also won't help with any of the various countably infinite connected Hausdorff spaces that have been constructed. A generalized path in such a space would be a countable, connected, compact Hausdorff space, and no such space exists.
Comment: @user18921: I really have no intuition about that. Once you get away from continuous maps, you're out of any purely topological setting.
Comment: @user18921: $T\cap([0,1]\times\Bbb R=T$ is not a closed subset of $\Bbb R^2$, so it's not compact. Its closure includes $\{0\}\times[0,1]$.
Comment: You write: "No compact, connected subset of the topologist's sine curve contains the origin and at least one other point of the curve." Are you sure about this? It seems to me that $T \cap [0,1]\times \mathbb{R}$ is both compact and connected. Which one fails?
Comment: Okay, good point. What if instead of requiring that a path be continuous, we merely require that it preserves connectedness? This allows that the image of a compact set can fail to be compact.
Answer: The following theorem might be the generalization you are looking for:

Theorem. A topological space $X$ is connected iff for every $x,y\in X$ and for every open cover $\mathcal U$ of $X$ there is a chain $U_1,\ldots,U_n\in\mathcal U$ that connects $x$ and $y$, more precisely: $x\in U_1$, $y\in U_n$ and $U_i\cap U_{i+1}\neq\emptyset$ for $i=1,2,\ldots,n-1$.

This is basically Theorem 8 on page 136 in Kuratowski - Topology, vol.2. (1968).
Comment: Thanks, that's a cool theorem.
Answer: Connected plus Locally Path Connected Implies Path Connected.
Here is the short proof if you are interested you may go through it.
Let $C$ be a connected set that is also locally path connected.  Pick any point $x$ in $C$, and let $U$ be the set of points in $C$ that are path connected to $x$.  Thus $U$ is a subset of $C$.
Let $y$ be a point in $U$.  Enclose $y$ in an open set $H$ in $C$, such that $y$ is path connected to all of $H$.  Since an arc can run from $x$ to $y$ to anything in $H$, $H$ is in $U$.  Therefore $U$ is the union of open sets and is open, relative to $C$.
Let $y$ be a point in $C$ that is a limit point of $U$.  Put an open set $H$ around $y$ such that $H$ is path connected.  Let $z$ be common to $H$ and $U$.  Now $x$ connects to $z$ connects to $y$, and $y$ is in $U$.
Since $U$ contains its limit points it is closed.  thus $U$ is both open and closed in $C$.  If $U$ is not all of $C$, separate $U$ and the rest of $C$ in open sets.  This contradicts the fact that $C$ is connected.  Therefore $U$ is all of $C$, and $C$ is path connected.


Issue with Pybamm Tutorial

Question: I am going through the PYbamm tutorial of setting parametres from the official site.
<code>parameter_values["Current function [A]"] = 10
parameter_values["Open-circuit voltage at 100% SOC [V]"]=3.4
parameter_values["Open-circuit voltage at 0% SOC [V]"]=3.0
</code>
when i run this part of the code i get an error whether it be locally or using the google colab
<code>'Open-circuit voltage at 100% SOC [V]' not found. Best matches are ['SEI open-circuit potential [V]', 'Outer SEI open-circuit potential [V]', 'Upper voltage cut-off [V]']"
</code>
When i check the parameter list provided on the site this exists however when i run the cod on either platform these parameters are not there
Answer: I came across a similar issue.
Name of these parameters are changed in PyBaMm version 23.5. These parameter names work fine with an older version.
You may try the following in PyBaMm 23.5:
<code> parameter_values["Current function [A]"] = 10
 parameter_values['Lower voltage cut-off [V]']= 3.0
 parameter_values['Upper voltage cut-off [V]']=3.4
</code>

Issue with Pybamm Tutorial


UIViewController not calling dealloc or calling it twice

Question: I have some problem with my singleton and UIViewController there;
Singleton.h
@property (nonatomic, retain) UIViewController *viewController;

Singleton.m
...

@synthesize viewController = _viewController;

- (void)load {
   self.viewController = [[[UIViewController alloc] initWithNibName:@"NibName" bundle: nil] autorelease];
}

- (void)unload {
   [_viewController release];
}

This viewController using by different part of the application via pushViewController:animated:. But sometimes I need to release viewController by calling method - (void)unload of Singleton class! If pushViewController:animated: never call for viewController everything is well and dealloc is calling, but if pushViewController(and viewController perform viewDidLoad), dealloc isn't work. If I do something like self.viewController = nil; dealloc calling twice... What I'm doing wrong???
Comment: structure of all viewController
UITabBarController - rootViewController
--UINavigationController
----UIViewController
------`viewController` - `pushViewController:animated:`
I'm trying to release rootViewController - all views are released only `viewController` has problems. Before releasing rootViewController I'm calling - (void)unload
Answer: Your unload function should only consist of:
- (void)unload {
   self.viewController = nil;
}

When you set a retained property to nil, it releases the instance variable AND nils it. You are simply leaving a dangling pointer on your property here.
Comment: It's not worked. Only if I'm using [_viewController release]; and self.viewController = nil; dealloc is calling, BUT twice. Maybe this helps: _viewController has MPMoviePlayerController which is playing...
Comment: @RostK. You have an extra retain then, because that code will release it twice.  Use instruments to track to retains and releases of this variable.
Answer: You need to set it to nil after releasing it:
[_viewController release];
_viewController = nil;

Otherwise the next person who comes along will try to do stuff with an invalid pointer.


Is a normalized version of an exponential family distribution still an exponential family distribution?

Question: Is a normalized version of an exponential family distribution still an exponential family distribution? Here "normalized" means making its mean zero and variance one.
According to the following definition of an exponential family distribution from Wikipedia, since both variance and mean are functions of the parameter $\theta$ alone, after normalization wrt variance we still have an exponential family distribution, but after normalization wrt mean $\mu(\theta)$,
$$
    f_{X'}(x|\theta) = h(x+\mu(\theta))\ \exp[\ \eta(\theta) \cdot T(x+\mu(\theta))\ -\ A(\theta)\ ],
$$
I am not sure.

A single-parameter exponential family is a set of probability distributions whose probability density function (or probability mass function, for the case of a discrete distribution) can be expressed in the form
  $$
    f_X(x|\theta) = h(x)\ \exp[\ \eta(\theta) \cdot T(x)\ -\ A(\theta)\ ]
$$
  where $T(x), h(x), η(θ)$, and $A(θ)$ are known functions.
An alternative, equivalent form often given is
  $$
    f_X(x|\theta) = h(x)\ g(\theta) \exp[\ \eta(\theta) \cdot T(x)\ ]\,
$$
  or equivalently
  $$
    f_X(x|\theta) = \exp[\ \eta(\theta) \cdot T(x)\ -\ A(\theta) + B(x)\ ]
$$
  The value $θ$ is called the parameter of the family.
Comment: I think it's definitely a curved exponential family, since you can add the sufficient statistics $x, x^2$ (if they're not already there), and then set their corresponding expectation parameters to $0, 1$.
Answer: The distributions for which this is possible are quite limited. There is a theorem of Dynkin, reported in Ferguson (1962) as Theorem 1, that states that the only one-dimensional exponential families with a location parameter have densities of the form
$$f(x)=\exp\left\{ \sum_{i=1}^m e^{\alpha_ix} p_i(x)\right\}$$
against the Lebesgue measure, where the $p_i$'s are polynomials. And there is another result of Lindley, reported in Ferguson (1962) as Theorem 2, that the only one-parameter exponential family with a location parameter is any rescaled log-Gamma distribution. And a third result of Dynkin in this paper of Ferguson (1962) is that the only location-scale exponential families with $k$ parameters are those for which $k$ is even and  the log density is a polynomial in $x$ of degree $k$.


Would a "switch hitting" golfer have an advantage in pga?

Question: Suppose someone could drive the ball well using a left or right handed driver?  Could this give them big advantage?  Downside is they would have to give up a club in order to carry 2 drivers.
Answer: TL;DR - Yes, it would be an advantage, but likely a very small advantage.
The biggest advantage of being able drive from both sides of the ball comes from shot shaping. I'm going to assume our standard golfer is right handed.
For a right handed golfer, a slice would be an extreme left to right movement off the tee, a fade would be a slight left to right, a draw would be a slight right to left, and a hook would be an extreme right to left.
Certain holes are considered "dog-leg" holes, and feature a very distinct change in direction. Off the tee, PGA players usually want to hit their shot in a shape that matches the direction of the hole. A dog-leg right would be played with a fade from our right handed golfer, ideally landing in the fairway, "around the turn" from the tee box.
A perfect golfer wold be equally capable of hitting fades and draws(slices and hooks almost always mean that a player made a mistake, and the ball was not ideally hit). However, no golfers are perfect, and most will be more successful at either hitting a fade or a draw. If a switch hitter was better at hitting a fade, they would hit right handed on a dog leg right and left handed on a dog leg left. If they were more adept at draws, they would do the opposite.
An assumption I'm making is that the player has the same exact swing from both sides. If they do not, they might be better at fades from one side of the ball and draws from the other, meaning the flight of the ball will the same from both sides, not mirrored, providing little if any advantage.
The versatility of having easier shot shaping off the tee is certainly an advantage for anyone who cannot already hit excellent draws and fades. How much of an advantage is another question.
Realistically, from the tee, a golfer would only hit the opposite hand drive ~5 times per round(Though this can vary by course/ conditions, for PGA golfers it may not even be that much). The advantage per shot is likely only a half shot on average. A ideal shot shape will not save you a shot over a straight ball shape every time. Being 30-40 yards closer to the hole on a par 4 or 5 will not always translate to a better score, but it often will.
So ~5 times per 18 holes, gain ~2-3 shot per 18. That sounds great! Except for in order to use another driver, you must lose a club as well. So where you gain ~2-3 strokes, you might lose a couple strokes as well; Which club to replace depends entirely on the golfer and course, but by replacing any club, you will be forced to play shots with a sub-optimal club. So where you make up on the drives, you will be forced to hit a 4 iron when you should hit a missing 3-wood, or a 9 iron when you should hit a pitching wedge. These drawbacks would likely outweigh the advantages, but that depends on the skill of the player and the course they are playing. A long course with lots of fairway bunkers may call for the extra driver, as shot shaping to avoid hazards would be very beneficial, where a short course with deep green side bunkers and small greens would mean that an extra wedge would come in handy more than a driver.
Overall, it is conceivable that it would be an advantage for a PGA pro, but most peoples time would be best spent practicing putting.
Comment: Good point about the opportunity cost of practice - an ambidextrous golfer will have to spend time practicing both their left-handed and right-handed shots, but a "unidextrous" golfer could spend that time improving the weaker of their draw/fade, so the difference between them will be even smaller. A more fair comparison might be between a golfer who hits equally well lefty/righty and one who hits equally well draw/fade, in which case there'd be little difference - otherwise the ambidextrous golfer is just more skilled than their counterpart, so they'd clearly have some (small) advantage.

Would a “switch hitting” golfer have an advantage in pga?


Qual problema que está ocorrendo no Axios com esta chamada HTTP?

Question: Estou tentando executar uma chamada HTTP, porém como sou iniciante não estou conseguindo encontrar o error.. Já testei no emulador e o error que é exibido o seguinte:
0, _loginService.autenticacao) is not a function. (In '(0, _loginService.autenticacao)(email,senha)','(0, _loginService.autenticacao)' is undefined)

api.js
import axios from "axios";

export const api = axios.create({
    baseURL: "http://localhost:8080/Proj_MedPag/api"
});

loginService.js
import { api } from "./api";

 export  const loginService = {
   autenticacao
 };

function autenticacao(email, senha) {

  let requestOptions = {
    headers: {
      "Content-Type": "JSON (application/json)"
    }
  };

  let data = { "email": email, "senha": senha };

  api.post("/autenticacao", JSON.stringify(data), requestOptions)
    .then(response => {
      //console.log(response.data);
      //return response.data;
      return response;
    })
    .catch(err => {
      throw err;
    });
}

index.js
import React, { Component } from "react";
import { StatusBar, View, TextInput, Alert } from "react-native";

import {autenticacao} from "../../services/loginService";

//import { Actions } from 'react-native-router-flux';

import login from "./login";
import Header from "../../components/HeaderLogin";
import Button from "../../components/Button";

class App extends Component {
  static navigationOptions = {
    header: null
  };

  constructor(props) {
    super(props);

    this.state = {
      email: "",
      senha: ""
    };
  }

  btnEntrar = () => {
    // Alert.alert('Aviso', this.state.email + " - " + this.state.senha);
    //Actions.home();
    //this.props.navigation.navigate("Home");
    const {email, senha} = this.state;
   const resultado = autenticacao(email, senha);
    Alert.alert('Aviso', resultado);
  };

  btnRecuperar = () => {
    this.props.navigation.navigate("Recuperar");
  };

  btnRegistro = () => {
    this.props.navigation.navigate("Registro");
  };

  render() {
    return (
      <View style={login.container}>
        <StatusBar
          barStyle="dark-content"
          backgroundColor={login.container.backgroundColor}
        />

        <View style={login.boxcampos}>
          <TextInput
            style={login.txtcampo}
            placeholder={"E-mail"}
            onChangeText={email => this.setState({ email })}
            value={this.state.email}
          />
        </View>

        <View style={login.boxcampos}>
          <TextInput
            style={login.txtcampo}
            placeholder={"Senha"}
            onChangeText={senha => this.setState({ senha })}
            value={this.state.senha}
            secureTextEntry={true}
          />
        </View>

        <Button style={login.btnRecuperar} type="recuperar"
          onPress={this.btnRecuperar}>
          Recuperar senha
        </Button>

        <Button onPress={this.btnEntrar}>Entrar</Button>

        <Button type="outline"
          onPress={this.btnRegistro}>
          Cadastre-se</Button>
      </View>
    );
  }
}

export default App;

Answer: Você não esta exportando a função autenticacao.
Use ...
export function autenticacao(email, senha) {

Comment: Olá.. eu fiz no arquivo loginService.js logo depois da importação da api
Comment: Seguindo um tutorial... estava assim
Comment: Realmente... do seu jeito funcionou... estranho que no tutorial funcionou do outro jeito.


Using Oracle 10g CLOB with Grails 2.0.1

Question: I'm working on a project using Oracle 10g and Grails v2.0.1.
I'm trying to use a CLOB data type for a text input field in my Domain class, and it doesn't seem to be working.  My first attempt was based on what I read here about GORM, where is says to use type: 'text', like this example:
class Address {
   String number
   String postCode
   static mapping = {
       postCode type: 'text'
   }
}

Grails mapped that to a LONG data type in my DB, which is not desirable
2nd attempt was to try type: 'clob'.  That WAS effective in getting my DB datatype to be CLOB, but resulted in a class cast error because the property itself was defined as a string, i.e. String postCode. (Note that I've never seen type:'clob' in documentation, but I could deduce from the dialect class that clob might be a valid input there)
I subsequently tried defining the property as a java.sql.Clob, i.e. Clob postCode;, and that didn't work at all.  No error messages, but nothing was getting persisted to the DB either.
I took a final step of keeping the Clob approach, but using a transient String property in which the getters/setters attempt to map the transient String value to the persistent Clob field.  But I cannot figure out how to get my string value into the Clob.  Grails doesn't throw an error, but the println() after my attempted assignment never prints.  I've tried using myClob.setString(1, theString) to make an assignment, but with no success.
So to make a long story short, I can't seem to use a Clob in my scenario, and I'm wondering if anyone else has seen this and been able to overcome it.  If so, can you tell me what I might be doing wrong?
OR... is there a way to override the datatype Grails chooses such that I could force it to map postCode type: 'text' to a CLOB?  I'm not proficient with Hibernate, so I'm not sure how to go about that if there's a way.
Side note: prior to our upgrade from Grails 1.3.7 to 2.0.1, I'm pretty sure the type: 'text' did, in fact, map to a CLOB in Oracle.  So this might be new to 2.0.1.
Comment: Well in the [2.0.x docs](http://grails.org/doc/2.0.x/ref/Database%20Mapping/type.html) actually is written that type in your case will be clob, but I didn't have to use this yet, so I cannot assure that this is working on 2.0.x
Answer: I think I found an answer tucked into the documentation on Custom Hibernate Types.

In that case, override the column's SQL type using the sqlType attribute

This appears to be working.
Looks like I'm able to use that to force my DB type to be CLOB while keeping the java type a String.  In other words, maybe type chooses both a DB type and a Java type for handling the field?  But sqlType gives a little more granularity to specify the DB type to use.
So the sample Domain class above should look like this in my case:
class Address {
    String number
    String postCode
    static mapping = {
        postCode sqlType: 'clob'
    }
}

I gleaned this from another StackOverflow question on the topic (the question itself clued me in, whereas the accepted answer misled me!):

How do I get Grails to map my String field to a Clob?

I spent a day trying to figure this all out, and it was incredibly frustrating.  So maybe my notes on the topic here will help someone else avoid that experience!

And while I'm keeping notes here... this post proved somewhat useful in terms of troubleshooting how to get more specific in my mappings:

http://omaha-seattle.blogspot.com/2010/02/grails-hibernate-custom-data-type.html

Interesting code from that is reproduced here:
//CONFIG.GROOVY (maps a custom SixDecimal type)
grails.gorm.default.mapping = {
    'user-type'( type: SixDecimalUserType, class: SixDecimal )
}

Comment: Awesome! It inserts and retrieves correctly strings > 4000 chars.
Answer: Probably too late but I have found a really simple solution to this problem:
class MyDomain{
  String myField
  ...
  static mapping = {
    myField type:'materialized_clob'
  }
}

Nothing else is required, writes and reads works like charm! :D
Hope it helps.
Ivan.
Answer: Ivan's answer works for me. MaterializedClob is the Hibernate JDBC type for a Java String.

Using Oracle 10g CLOB with Grails 2.0.1


Como persistir uma informação após recarregar a página? (ex: um background escolhido)

Question: Tenho um script de troca de background do site:
function bac(){
    document.body.background = "img/1.png";
}

O usuário pode escolher qual a imagem do plano de fundo do site, mas quando a página recarrega, o fundo volta a ser branco. Tem como salvar a opção que o usuário escolheu, até mesmo se ele reiniciar o pc?
Comment: Você pode usar cookies para persistir a url da imagem do background e quando recarregar a página, você verifica se existe valor no cookie e atribui ao background novamente. Segue esse [link](http://www.w3schools.com/js/js_cookies.asp) de como trabalhar com cookies em javascript.
Answer: Para guardar informação de um utilizador tem 3 opções:
Guardar na base de dados
Esse caso precisa de autentificação/login. Aí quando o utilizador clickar tem de enviar um AJAX para o servidor para poder guardar os dados e a referência do nome do utilizador.
Não creio que seja o que pretende mas tinha de o referir.
Guardar no Storage do HTML5
A API do HTML5 têm duas opções, dois tipos: sessionStorage e localStorage.
A sessionStorage é só para a sessão e perde-se quando a janela fechar. O que quer usar é o localStorage que permanece no computador mesmo que este seja reiniciado.
Esta API tem os métodos:

.setItem(<nome>, <dados>) Para escrever um novo registo
.getItem(<nome>) Para lêr um registo gravado

Um exemplo para o seu caso seria:
function bac(imagem) {
    imagem = imagem || "img/1.png";
    localStorage.setItem("corDeFundo", imagem);
    mudarFundo(imagem);
}

function mudarFundo(url) {
    document.body.background = "url(" + url + ");";
}
if (localStorage.background) mudarFundo(localStorage.getItem("corDeFundo"));

Guardar em Cookie
Já tinha dado esta resposta noutra pergunta sua.
Sugiro usar o código que está na página da MDN para criar e ler cookies. (Coloco tambem no fundo da resposta.)
E nesse caso a sintaxe será:

docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) - criar o cookie
docCookies.getItem(name) - ler o cookie
docCookies.removeItem(name[, path[, domain]]) - remover o cookie

Usando esse código como suporte, depois pode usar assim:
var fundo = docCookies.getItem('corDeFundo') || "#fff";
$('body').css('background-color', fundo);
$('button').on('click', function(){
    fundo = $(this).data('value');
    docCookies.setItem('corDeFundo', fundo);
    $('body').css('background-color', fundo);
});

Exemplo: http://jsfiddle.net/wpnk5ep8/
(Teste fazer refresh ao exemplo depois de ter mudado a cor e vai ver que o Cookie guarda a unformaçõ.

Código na página da MDN:
var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Comment: Tem alguns que deram respostas, vc deu uma aula e dicas valiosas para que o projeto seja cross-browser, infelizmente as vezes usuários só querem o simples e não se aprofundam em dicas valiosas como as suas. Parabéns +1
Answer: Há a opção de utilizar Local Storage presente no HTML5.
Exemplo:
// Sempre que carregar a página verifica se existe um background pré-definido
if (localStorage.background)
    document.body.background = localStorage.getItem("background");

// Guarda o background escolhido
function bac(){
    localStorage.setItem("background", "img/1.png");
    document.body.background = "img/1.png";
}

Comment: Funcionou mesmo! Muito obrigado! Vlw!


Algebra clock problem

Question: An absent-minded watch repairman connected the hour hand to the minute hand pinion and the minute hand to the hour hand pinion and set the clock at 6AM which was the correct time then. How soon after 6AM (at what time) will this clock give the correct time again?
Comment: @Vikram: How did you come up with that answer?
Comment: I don't see how it could be 06:33 and the pinion does matter as it will change the speed of the hand.
Comment: It does not matter which hand is connected to which pinion, so it will be 6:33 AM
Comment: Sorry friends , my answer is wrong
Comment: I think the obvious (and possibly wrong) answer is 12 hrs. later at 6PM when both hands have made a circuit.
Comment: Of course, if he connected the hands wrong, the clock will not be showing a valid time, even at the initial time of 6:00. The reason is that if the hands were switched, the time would ostensibly be 12:30 -- but at 12:30, the hands are not on the "12" and the "6" because the hour hand would have advanced halfway between the "12" and the "1".
Comment: But it is showing a valid time at 06:00 because he sets it to the correct time (even though the hands move at the wrong speeds)
Comment: @oliveeuler: You're right after 12 hours it will display a correct time. But our professor, who gave this problem, said that there will be a time between those 12 hours when the clock will display a correct time.
Comment: I thought as much
(I get the feeling that modular arithmetic could help but I'm quite inexperienced with it)
Comment: Hint: use angular speed of pinions of the skewed watch, and the reference one. When the two minutes and/or hours (interesting to see the result for both - straightforward, remains to be seen) match, you have your time...
Answer: Hint: Try writing out formulae for the positions of the hands on a correct clock and one the wrong clock in terms of time.
Correct clock:
the long hand is at $(\text{time in mins})\times (6^{\circ}), \mod 360^{\circ}$, since it starts straight up and moves by 360 degrees each hour;
the short hand is at $180^{\circ} +(\text{time in mins})\times \frac{1}{2}^{\circ}, \mod 360^{\circ}$, since it starts straight down and moves by 360 degrees every 12 hours.
Now write similar equations for the wrong clock, and look for values of time from which the long-hand equations give the same angle and so do the short hand equations.
Answer: correct answer is 7:06 AM, in 1 hour and 6 minutes the  minute hand will rotate 360+30 plus degrees and just cross 7 o'clock and the hour hand will rotate 30 degrees and come to 6 minutes (right next to 1 o'clock)
Comment: In $1:06$ the minute hand travels $360+36=396$ degrees, while the hour hand travels $\frac {1.1}{12}\cdot 360=33$ degrees.
Comment: mark position of both the hands in false clock after 1 hour and 6 minutes and see if you get the correct time.
Comment: @RossMillikan, dosen't it coincide with 7:06 AM?
Comment: No, the minutes hand at $7:06AM$ is $39$ degrees from vertical, while on this clock the hour hand will be $33$ degrees from vertical.  Similarly the "hour" hand will be off by $6$ degrees the other way.
Comment: @RossMillikan, minute hand rotates 360 degrees in 60 min, so in 1 minute it rotates 360/60=6 degrees, so in 6 min it rotates 36 degrees, so difference of 3 degrees between this clock and normal one, Diff of 6 degrees changes the minute(6 to 7, 7 to 8 etc).
Answer: Imagine a phantom hour hand that starts at $6$ (just like the actual hour hand)
but is connected to the correct pinion so that it moves at the speed an hour hand is supposed to move.
The clock cannot be showing the correct time unless the actual hour hand is where it is supposed to be, namely, where the phantom hour hand is.
So we have two "hands" that start at one position on the clock (pointing to $6$);
one hand rotates at a rate of one revolution per hour, the other at a rate of
one revolution every $12$ hours. They are next at the same position when
$\frac{12}{11}$ hours have passed, the same amount of time as it takes between noon and when the hands meet again on a normal clock.
So far, we know only that the hour hand is in the correct position at $\frac{1}{11}$ hour after $7$ AM. But what about the minute hand?
If the minute hand does not end up where it is supposed to be at $\frac{1}{11}$ hour after $7$ AM, you will have to look for a later time when the clock is correct.
So the next step is to find out whether or not the minute hand will be where it should be at that time.
There are various ways of doing this, including direct computation (since you know exactly when to look at the hand's position); I leave that step "as an exercise."

Algebra clock problem


How can i edit this navigation bar? MAGENTO

Question: So i am new to magento and web development and i am in the middle of putting together my own site which is here theshirt.org i am trying to change the look of this vertical navigation menu which i made following the instructions on this wiki
Creating a vertical navigation
I am trying to change a few things on this navigation but i just have no clue where to start.

As i have changed the size of my main and left sidebar, the nav menu is too big so will i will need to change the size of the nav menu to 150px
the nav menu only appears on the home page. I need it to appear of every page
When i hover over the navigation categories i would like the menu items to change colour.

now how would i go about doing this?
Thanks again guys for your help. I would not have been able todo any of my store without the help of this site!
Jon
Answer: 1°) Look at http://theshirt.org/skin/frontend/default/footprint/css/widgets.css and edit width:200px to width:130px around line 155
#nav_vert li {
background-color: #F6F6F6;
border-bottom: thin solid #CCCCCC;
list-style: none outside none;
position: relative;
text-align: left;
width: 130px;
}

2°) You must have missed the first step of your tutorial :
<reference name="left">
        <block type="catalog/navigation" name="catalog.leftnav" after="currency" template="catalog/navigation/left.phtml"/>
    </reference>

move this in the <default> section
it will show the menu in all page with a left column.
3°) Just do some CSS here to look at the :hover pseudo-element
Basically in the same css than for 1°) (widget.css) look at line 202 and replace #nav_vert a:hover by #nav_vert span:hover to have your text grey on mouse over. Then you can play with color, or background-color or whatever you want ;)
Edit.:
To transform a page to a 2 columns with left bar, edit your xml layout files to change the template of the <reference name="head"> on page you want.
For CMS page you can set this directly through a menu when creating the page.
Comment: i am having trouble displaying the navigation on all pages :( I moved the code shown above to the default section in layout/catalog.xml
Comment: i have just "inspected element" on my website using google chrome and i cant see the div class "col-left sidebar". I can see the div for the right side. is this the cause?
Comment: If the page is displayed with 1 column or 2 columns with right bar it won't work.
For right bar you need `` instead of "left"
Comment: well i want all my pages to be 2 columns with left sidebar and i want the vertical navigation to be on every single page i make. even if its a contact us page
Comment: do you have an email address? i have tried to contact you via your website but the contact button doesnt work yet. i would like a quote? you can email me email@example.com


Mikrotik: Forward local ip to another local ip on specific port

Question: I'm running a Docker container on a machine on port 8090. Let's say the IP address of that machine is 192.168.0.3. I want to forward 192.168.0.4:80 to 192.168.0.3:8090. The machine is and may only be reachable from within the local network.
What I've tried:
/ip firewall nat export
add action=dst-nat chain=srcnat dst-address=192.168.0.4 dst-port=80 \
    src-address=192.168.0.0/24 to-address=192.168.0.3 to-port=8090 \
    protocol=tcp
add action=masquerade chain=srcnat dst-address=192.168.0.4 dst-port=80 \
    src-address=192.168.0.0/24 protocol=tcp

This doesn't work.
Am I forgetting something? I've got the feeling I'm overlooking something simple but haven't been able to figure out what.
Edit:
The ip address 192.168.0.4 does not resolve to anything in my network. I just want to "assign" and forward it to 192.168.0.3:8090. The reason for this is that I want to setup a local domain name that resolves to the Docker container without having to specify a port.
Comment: is `192.168.0.4` pingable? if so, does the firewall know about this ip address on one of its interfaces? if so, is the ARP entry for `192.168.0.4` the MAC address of your firewall or is it per chance flapping? try last question on a system in the same subnet with `arping -I eth0 192.168.0.4` (replace eth0 with the correct interface name if necessary)
Comment: Traffic on the same layer-3 network is delivered directly by layer-2, not layer-3, so you can't NAT (redirect) at layer-3. ARP will try to find the layer-2 address for the layer-3 address, and the resulting frames are delivered by layer-2. If ARP can't resolve the addressing, then the packet gets dropped because no frame can be built.
Comment: apart from that: using port forwarding on `192.168.0.3` looks way easier and more transparent to me.
Comment: The address is not pingable. Running the `arping` command will surely result in a timeout as well. I will update my question with some additional information.
Answer: Your computers in the local network try to reach IP addresses within their own subnet directly. Therefore a computer ("Workstation") with the IP address 192.168.0.105 will ignore the default gateway when trying to reach 192.168.0.4 and tries to send tcp packages directly.
This will fail if no other computer is answering Workstations call ("arp request") for the MAC address belonging to 192.168.0.4 - and none will answer, as this IP address is not in use within your local network.
You do have various choices on how to solve it:

add 192.168.0.4 to an interface on your firewall and use your firewall to re-route those packages
add 192.168.0.4 to an interface on your docker-host and redirect traffic on the docker-host itself
add the redirection of traffic on the docker-host and use 192.168.0.3 directly instead of 192.168.0.4

other options may exist.
Comment: I would go with option 3, but thats my personal opinion on keeping things simple.


Error when wrapping text in a div

Question: Can you tell me why there's a break after varun09 in the picture below? It's kind of weird because it only happens whenever the statement is bigger than the actual width of the
, and I'd like to know how to wrap the text? I want the vertical scroll option, but not the horizontal scrolling bar.
I am populating the
 with Mysql data through Php.
The code is:
while ($row = mysql_fetch_assoc($query_run)) {
    echo '
'.$row['user_name'].' '.$row['chat_body'].'

 ';
}

Comment: You don't need a `br` when wrapping it inside `` tag.. Also add a class to `<p class="user_comments"` and set the style for that property.
Comment: `word-wrap: break-word;` will do the job
Comment: it's wrapping now but why is it still breaking the line ??
Answer: jsBin demo
use for your element the CSS property word-wrap:
word-wrap: break-word;

Answer: You can use word-wrap property:
selector {
    word-wrap: break-word;
}

Answer: You need to set the white-space in order for it to wrap for you, but the space after varun09 will cause the next one to go to the next line. Try this combination:
jsFiddle Demo
p { word-wrap: break-word; white-space:pre; }

Info on white-space here
Comment: Thanx  but any idea on  why  it's still breaking the line  after varun09 ?
Comment: white-space:pre(which fixes the line break) and white-space:normal (which wraps the text) are working  but i can't use  them  together, and word-wrap: break-word;  is not working ....
Comment: Unfortunately it'll only work on newer browsers, which one are you using?
Comment: yes you are right it's  working on chrome  not  working on mozilla and ie
any suggestion on making it work on old browsers too ?

Error when wrapping text in a div


Is there any official/semi-official standard for music symbol visual appearance?

Question: Is there any official or at least widely recognized source that documents the visual parameters of music symbols? Something that says things like: "The note head shall be an ellipse with the proportion of the larger radius to the smaller radius of 51:35". Etc.
Comment: @ToddWilcox - I understand. Thank you for answering it! In my defense, asking about every possible little thing would explode in hundreds of questions, which would quickly become burdensome for everyone. And also, I didn't ask for just any resource. I asked for The One And Only resource to rule them all; blessed by ISO, ECMA, IETF, the Catholic Church and the Nine Muses. To which a fair answer would be "No, sorry, there isn't one". And then, if you're feeling generous, also a little asterisk: "* But everyone uses this book over there which is the next best thing". :)
Comment: @Vilx- is there a standard distance for the dot on top of an "i", and is the standard dot a circle or an ellipse? Obviously there's no absolute answer: notation (similarly to text) follows the rules of *typography*, which has no standard sizes or ratios. A *good* font is not just "beautiful", but has *readability* requirements which, for notation, are even more important: a good text font ensures fast reading "flow", but if "decoding" a bad text font is not a big issue, for notation it is, because when you read music your focus should be on how to play a note, not understand what note that is.
Comment: Check out this youtube video which talks about music font design:  https://www.youtube.com/watch?v=XGo4PJd1lng
Comment: @guidot - Funny enough, I'm not any of them. I just wanted to draw a few separate notes for a little computer program I'm making and have them be pretty and proper. :) I tried searching the web but could not find all the things I needed, so resolved to create my own. Thus this question was born. But, yes, in general I agree. The audience for this question is pretty narrow. Then again... I'm sure there are other questions here with similarly narrow audiences, like for some more exotic instruments or obscure theory points etc. Still, if you feel the need to close-vote - go for it!
Comment: I think this question is a bit borderline in terms of the rules of the site. I believe it is an important and valuable question, and at the same time it is a "resource request", which are generally frowned upon. You could see if there are any votes to close before making any changes, or you could proactively re-word it. One way to reword it would be to specifically ask about notehead size and also say that you would like citations from an authoritative source. Then my answer could stand as it is and your question would definitely be on-topic.
Comment: @musicamante - good point! I hadn't thought about that. :)
Comment: While I find the question interesting, the auditory benefitting from an answer seems restricted to music font creators (the boundary line of a hollow note has never constant thickness), notation program developers and possibly those, which use a standard drawing program to create a score - my understanding for the last group is limited.
Answer: Yes. One of the most widely respected and utilized sources (at least in American universities and professional circles) for the precise parameters of standard notation is the book Behind Bars by Elaine Gould.
Many universities in the US have that book in their music libraries and several professional organizations, such as ASMAC, refer to that book as one of the standard texts on notation.
In the book, Gould does go into detail about the shapes and relative and absolute sizes for all of the most common musical symbols. It is a comprehensive text.

Excerpts related to your example:

The size of every notational symbol is measured in proportion to the stave size.

page 5
Table 2 on page 483 lists the traditional "rastral sizes" for staves for various uses. The sizes are the distance from the top line of a single stave to the bottom line. For piano music that is not for education (which is often printed larger), recommended staff size is between 6mm and 7.4mm. Note that piano parts written into a full orchestral score will usually use a staff size smaller than 6mm.
Noteheads:

These are oval-shaped and placed on the stave with a diagonal slant away from the stem.

page 9

The height of the stave-space determines the size of all noteheads, which is crucial to ease of reading.
...
The notehead fills the space, touching the stave-line on each side of it, but without extending beyond either line.

page 10
Interestingly, Gould does not seem to detail the proportions of the "oval" for noteheads, so the specific example you asked about is not answered the book. It is clarified that the shape of a semibreve (whole note) is a wider oval than that of the minim (half note), which is in turn slightly wider than the black noteheads.
Comment: "Many universities in the US have that book as required reading"— for what programs?
Comment: @ElizaWilson I came across it originally in reading lists for more than one composition program but now I can't find those sources. I've edited the answer since I can't support my prior understanding.
Comment: Huh, I don't think I'd ever noticed the difference in width between note-heads, but on a quick spot-check of some of my books, it does appear to be true most of the time.  Mostly only noticeable between whole/half notes and black note-heads.  Only difference I noticed between whole and half note-heads is that half notes are slanted like black note-heads, while whole notes are pretty much straight, and the line thickness variation is flipped around - half notes are thicker on top-left/bottom-right, while whole notes are thicker on top-right/bottom-left.  Consistent across multiple publishers.
Answer: The Music Publishers Association published a style guide: "Standard Music Notation Practice". It does not address notehead size, but it does address other visual parameters. For example

Placement of note heads and accidentals: (a) Many musical symbols slant up from left to right at a uniform angle.

It also addresses issues such as stem lengths; beam thickness, placement, and angle; duration-based horizontal spacing; and relative placement of symbols like lyrics, dynamic markings, and other instructions.
Comment: This is a good reference to a more digestible summary of notation conventions - the Gould book is over 1000 pages!


Why is the presheaf of holomorphic functions that admit a square root not a sheaf?

Question:
Prove that the presheaf of holomorphic functions that admit a square root does not form a sheaf.

Why is this? I can guess that this is because the square root of such a function contains two branches. However, I don't understand how this will lead to a contradiction (presumably in the "identity" axiom).
Answer: The problem is the "gluing axiom": Let $U^{-}$ and $U^{+}$ denote the complements of the non-negative and non-positive real axis, respectively. The function $f(z) = z$ admits a square root in each of $U^{\pm}$, but does not admit a square root on their union.


"invalid_grant" for Google SSO with Symfony4 and knpuniversity OauthBundle

Question: When I choose my email acount to log with google API, I have systematically a "invalid_grant" error.
After debugging the GuardAuthenticator, everything's fine until retrieving user (it retrieves !) but when I return the user, I fall in onAuthenticationFailure with "invalid _grant" error.
I'm working with Symfony 4.1 and Doctrine ODM :
Here my code :
knpu_oauth2_client.yaml :
knpu_oauth2_client:
  clients:
    google:
      # must be "google" - it activates that type!
      type: google
      # add and configure client_id and client_secret in parameters.yml
      client_id: "%env(GOOGLE_CLIENT_ID)%"
      client_secret: "%env(GOOGLE_CLIENT_SECRET)%"
      # a route name you'll create
      redirect_route: connect_google_check
      redirect_params: {}
      # Optional value for sending access_type parameter. More detail: https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
      # access_type: ''
      # Optional value for sending hd parameter. More detail: https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
      # hosted_domain: ''
      # Optional value for additional fields to be requested from the user profile. If set, these values will be included with the defaults. More details: https://developers.google.com/+/web/api/rest/latest/people
      # user_fields: {}
      # Optional value if you don't want or need to enable Google+ API access.
      # use_oidc_mode: false
      # whether to check OAuth2 "state": defaults to true
      # use_state: true

security.yaml :
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt
    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/(?!(api|connect))
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            anonymous: ~
            logout:
                path: /logout
                target: /login
            remember_me:
                secret: '%env(APP_SECRET)%'
            guard:
                authenticators:
                    - App\Security\GuardAuthenticator\GoogleAuthenticator
                    - App\Security\GuardAuthenticator\LoginFormAuthenticator
                    - lexik_jwt_authentication.jwt_token_authenticator
                entry_point: App\Security\GuardAuthenticator\GoogleAuthenticator
        social:
            pattern: ^/connect/
            stateless: true
            anonymous: ~
            guard:
                authenticators:
                    - App\Security\GuardAuthenticator\GoogleAuthenticator

    access_control:
         - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api/doc, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api/token/refresh, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/connect/google, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/, roles: ROLE_USER }
         - { path: ^/api, roles: ROLE_USER }

GoogleAuthenticator :
<?php
declare(strict_types=1);

namespace App\Security\GuardAuthenticator;

use App\Document\User;
use Doctrine\ODM\MongoDB\DocumentManager;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
use League\OAuth2\Client\Provider\GoogleUser;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Router;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use KnpU\OAuth2ClientBundle\Client\Provider\GoogleClient;

class GoogleAuthenticator extends SocialAuthenticator
{
    /**
     * @var ClientRegistry
     */
    protected $client;
    /**
     * @var DocumentManager
     */
    protected $documentManager;
    /**
     * @var Router
     */
    protected $router;

    public function __construct(
        ClientRegistry $client,
        DocumentManager $documentManager,
        RouterInterface $router
    ) {
        $this->client = $client;
        $this->documentManager = $documentManager;
        $this->router = $router;
    }

    /**
     * @param Request $request The request that resulted in an AuthenticationException
     * @param AuthenticationException $authException The exception that started the authentication process
     *
     * @return Response
     */
    public function start(
        Request $request,
        AuthenticationException $authException = null
    ) {
        return new JsonResponse(['message' => $authException->getMessage()], JsonResponse::HTTP_UNAUTHORIZED);
    }

    /**
     * @param Request $request
     *
     * @return bool
     */
    public function supports(Request $request): bool
    {
        return $request->attributes->get('_route') === 'connect_google_check';
    }

    /**
     * @param Request $request
     *
     * @return mixed Any non-null value
     *
     * @throws \UnexpectedValueException If null is returned
     */
    public function getCredentials(Request $request)
    {
        return $this->fetchAccessToken($this->getGoogleClient());
    }

    /**
     * @param mixed $credentials
     * @param UserProviderInterface $userProvider
     *
     * @throws AuthenticationException
     *
     * @return UserInterface|null
     */
    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        /** @var GoogleUser $googleUser */
        $googleUser = $this->getGoogleClient()->fetchUserFromToken($credentials);
        $userEmail = $googleUser->getEmail();

        $user = $this->documentManager
            ->getRepository(User::class)
            ->findOneBy(['email' => $userEmail]);

        if ($user) {
            return $user;
        }

        return null;
    }

    /**
     * @param Request $request
     * @param AuthenticationException $exception
     *
     * @return JsonResponse
     */
    public function onAuthenticationFailure(
        Request $request,
        AuthenticationException $exception
    ): JsonResponse {
        return new JsonResponse(
            [
                'message' => strtr(
                    $exception->getMessageKey(),
                    $exception->getMessageData())
            ],
            JsonResponse::HTTP_FORBIDDEN
        );
    }

    /**
     * @param Request $request
     * @param TokenInterface $token
     * @param string $providerKey The provider (i.e. firewall) key
     *
     * @return Response|null
     */
    public function onAuthenticationSuccess(
        Request $request,
        TokenInterface $token,
        $providerKey
    ) {
        $user = $token->getUser();
        $googleApiToken = $this->fetchAccessToken($this->getGoogleClient());

        $user->setApiToken($googleApiToken);
        $this->documentManager->persist($user);
        $this->documentManager->flush();

        return null;
    }

    /**
     * @return GoogleClient
     */
    private function getGoogleClient(): GoogleClient
    {
        return $this->client->getClient('google');
    }
}

GoogleController.php :
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Document\User;
use App\Logger\PlanningLogger;
use Doctrine\ODM\MongoDB\DocumentManager;
use FOS\RestBundle\Controller\Annotations as Rest;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class GoogleController extends AbstractController
{
    /**
     * @var ClientRegistry
     */
    protected $clientRegistry;

    public function __construct(
        DocumentManager $documentManager,
        LoggerInterface $logger,
        ClientRegistry $clientRegistry
    ) {
        parent::__construct($documentManager, $logger);
        $this->clientRegistry = $clientRegistry;
    }

    /**
     * @Rest\Get("/connect/google", name="connect_google")
     *
     * @return RedirectResponse
     */
    public function connect()
    {
        return $this->clientRegistry->getClient('google')->redirect();
    }

    /**
     * @Rest\Get("/connect/google_check", name="connect_google_check")
     *
     * @param Request $request
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
     */
    public function connectCheckAction(Request $request) {}
}

I followed the documentation oauth2-client-bundle but I was not able to solve it.
Someone could help me to solve this issue please ?
Thanks !
Answer: You need to set the access_type field in your knpu_oauth2_client.yaml
knpu_oauth2_client:
  clients:
    google:
      .....

      access_type: 'offline'
      ...

Comment: Sorry thought I answered ...
You made my day dude, thanks again :)


cardinality of collection of chains in the collection of infinite subsets of $\mathbb{N}$ with inclusion partial order

Question: Let's confer inclusion partial order in the collection of infinite subsets of $\mathbb{N}$.
Is the cardinality of the collection of chains in that poset countable or uncountable?
Comment: What do you think? What do you know about the chains in that partial order?
Comment: What i know is... collection of infinite subsets of natural numbers itself is uncountable, of course.. and.....
 It is impossible to construct uncountable disjoint collection of subsets of natural numbers..

 It seems that collection of chains will, in some sense, saturate the whole $P(\mathbb{N})$ in countable steps.. but it is just my crude feeling..
Comment: @BCLC: I'd be happy to hear what makes this [set-theory] in your eyes.
Answer: Uncountable as the collection of infinite subsets of $\mathbb N$ is already uncountable.
Comment: You can actually say much more than just that.
Answer: First, recall that in general, a subset of a chain is a chain.
Second, recall (or prove) that there is an uncountable chain in $\mathcal P(\Bbb N)$ when ordered by inclusion (HINT: Find such chain in $\mathcal P(\Bbb Q)$ first), in fact you can find a chain whose cardinality is that of $\Bbb R$. In fact such chain can be order-isomorphic to $\Bbb R$.
Finally, calculate how many chains you can find in $\mathcal P(\Bbb N)$.
Comment: I've managed to check that there exists an uncountable chain in $\mathcal{P} (\mathbb{Q})$ which is order-isomorphic to $\mathbb{R}$ ..


Há alguma alternativa para PRIORITY_MAX que esta obsoleto?

Question: Estou usando a classe NotificationCompat.Builder para criar uma notificação no qual ela tem que ficar no topo com a prioridade máxima.
Eu defino a prioridade da notificação da seguinte forma:
notification.setPriority(Notification.PRIORITY_MAX);

No entanto, o Android Studio diz que o campo PRIORITY_MAX esta deprecated.
Pergunta
Sendo assim, eu gostaria de saber se há alguma alternativa para PRIORITY_MAX e que não esteja deprecated ou obsoleto?
Answer: O método setPriority ficou obsoleto a partir da API 26 e na documentação recomenda-se utilizar método setImportance
Você pode usar IMPORTANCE_HIGH no lugar de PRIORITY_MAX.
Abaixo os valores que pode ser informado como parâmetro, esses valores estão disponíveis a partir da API 24.

IMPORTANCE_UNSPECIFIED
IMPORTANCE_NONE
IMPORTANCE_MIN
IMPORTANCE_LOW
IMPORTANCE_DEFAULT
IMPORTANCE_HIGH


Would Django be appropriate for this project?

Question: I'm a CS student interning at a company that needs a web app made to make looking at data much easier for the end user. I'm very new to web dev. I have experimented a little bit with HTML and CSS but I have never touched Javascript.
Anyway, my company has a web API that I have access to that returns a bunch of data points in JSON format. Upon doing some research online it seems that utilizing something like Django, Node.js, or Rails would be the best option to parse these JSON strings and return the data that I am interested in. Django seems like the best alternative because the documentation seems very good, and I know Python relatively well so the learning curve will not be too bad.
Do you guys think I have roughly the right idea so far? Would using Django to parse hundreds of JSON format strings be a good idea, and then export the data I have to HTML in some way and construct the web app?
Thank you!
Answer: I <3 Django.
But in my opinion, Django is best suited to making objects out of data in a database. It does this using and MVC-ish structure and an Object Relational Model (ORM). I'll make some assumptions from your question:

your data isn't in a DB, but is a bunch of JSON strings
you're more interested in displaying, rather than manipulating this data

If those are true, I would think you would want front-end focused system using Javascript. That's the best at handling JSON, after all. Django or Rails would be overkill for parsing strings.
Look at Angular or Ember, et. al.
Comment: What about something like Node.js?
Answer: Node.js is great for requesting remote JSON data and real-time streaming. Pair it with socket.io and real-time data just get more fun.
Take a look at D3.js, which use SVG to generate stunning, customized data visualizations or for simple visualizations, Google Charts API is really simple to begin with.


Delta Lake: File Not Found Exception

Question: I am using Delta Lake to perform merge operation, for which I am trying to convert my Parquet files to delta format which are partitioned over time:
val source = spark.read.parquet("s3a://data-lake/source/")
       source
      .write
      .option("maxRecordsPerFile",20000)
      .mode("overwrite")
      .partitionBy("time")
      //.option("fs.s3a.committer.name", "partitioned") (I even tried using s3a committers)
      .format("delta")
      .save("s3a://data-lake/target/")

The data is over around 250G and my spark configs are:
spark.cores.max 420
spark.default.parallelism   10000
spark.delta.logStore.class  org.apache.spark.sql.delta.storage.S3SingleDriverLogStore
spark.driver.extraJavaOptions   -Xms20g
spark.driver.memory 28g
spark.executor.cores    2
spark.executor.memory 28G

In the logs it shows File Not Found Error and eventually kills executors after running for some time:
20/05/16 11:51:02 WARN TaskSetManager: Lost task 208.0 in stage 2.0 (TID 3294, 172.16.145.25, executor 14): org.apache.spark.SparkException: Task failed while writing rows.
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:257)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:170)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:169)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException: No such file or directory: s3a://data-lake/target/time=20190101/part-00208-2c9b5ddd-f2c1-4b8c-9d77-eacb0055ff82.c000.snappy.parquet

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1889)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1877)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1876)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:167)
    ... 53 more
Caused by: org.apache.spark.SparkException: Task failed while writing rows.
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:257)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:170)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:169)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I tried saving it as parquet format, it does work as expected. But it takes significantly more time to process.
Comment: Try not setting spark.delta.logStor and max records per file
Comment: I am having the same issue. I don't think it is to do with the settings. It may be the same cause as here - https://github.com/delta-io/delta/issues/341.
Answer: If it's already in parquet, you can copy the folder in s3 to the target place without spark, and initialize it as a delta table with the following line:
import io.delta.DeltaTable
DeltaTable.forPath("s3a://data-lake/target/"))

More info here.

Delta Lake: File Not Found Exception


Problem with creation of model with many-to-many field in serializer

Question: I have Course, TeacherProfile and StudentProfile models with following relations:
class Course(models.Model):
    students = models.ManyToManyField(
        StudentProfile,
        blank=True,
        related_name='students'
    )
    teachers = models.ManyToManyField(
        TeacherProfile,
        blank=True,
        related_name='teachers'
    )
    name = models.CharField(max_length=30, blank=False)

class TeacherProfile(models.Model):
    user = models.OneToOneField('CoursesUser', on_delete=models.CASCADE)

class StudentProfile(models.Model):
    user = models.OneToOneField('CoursesUser', on_delete=models.CASCADE)

When I'm trying to create new course via POST request with body:
{
  "name": "Course",
  "students": [],
  "teachers": []
}

I want to add request.user to teachers filed
This is my view for Course
class CourseList(generics.ListAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def post(self, request, format=None):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(creator=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

And serializer for Course model:
class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ['id', 'name', 'students', 'teachers']

    def create(self, validated_data):
        creator_profile_id = TeacherProfile.objects.filter(
            user__id=validated_data['creator'].id
        )[0].id
        validated_data['teachers'].append(creator_profile_id)

        return Course(**validated_data)

But have

Direct assignment to the forward side of a many-to-many set is prohibited. Use students.set() instead.

I don't understand how to use ```set()`` in my case
Answer: The right approach is to save new model and then add ManyToMany fields.
In CourseSerializer.create():
def create(self, validated_data):
    creator_profile_id = TeacherProfile.objects.filter(
            user__id=validated_data['creator'].id
        )[0].id
    name = validated_data['name']
    course = Course(name=name)
    course.save()
    course.teachers.add(creator_profile_id)

    return course


ReactJS - Custom hook return function doesn't store actual data from internal state

Question: I have a custom hook useNotifications for Notification widget. This hook returns an array with the next elements (it's similar to ant.design message api):

add: function to add a new notification
remove: function which gets a notification id and removes the notification
contextHandler: JSX which is passed into component's render

When user calls add they get an id which can be used to remove the notification
The problem is dedicated to remove function particularly. Since I call this function right after I add new notification, the function receives a copy of old list so there's no new element and it throws an error. How can I fix it so there's same API for the Component uses that?
useNotification hook
How I use it
Codesandbox (for test I did setTimeout which calls remove() in 3 seconds): https://codesandbox.io/s/goofy-smoke-5q7dw3?file=/src/App.js:405-440
Answer: You can make your remove function use the state updater function which has access to the most up-to-date state value. This allows you to access the new list state before your component has rerendered within remove().
Note: You're currently mutating your original state by setting the nested object's isMounted property to false. Even though you make a copy of your array, you should also make a copy of the object you're updating to avoid rerendering issues.
Below are some modifications on how you can access the most up-to-date value of your state and avoid state mutations:
const add = useCallback((params) => {
  const id = v4();
  const element = {...params, id, isMounted: true};
  setList(list => [...list, element]); // Add your new element while also making a copy of the current state (`list`)
  return id;
}, []);

const remove = useCallback((elementId) => {
  setList((list) =>
    list.map((elem) => elem.id === elementId
      ? { ...elem, isMounted: false }
      : elem
    )
  );
  setTimeout(() => {
    setList((list) => list.filter((elem) => elem.id !== elementId));
  }, 500);
}, []);

See example below:


Listview divider margin

Question: I'm trying to set a margin to a listview divider.
The divider is a dashed line:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line" >
    <stroke
        android:dashGap="1dp"
        android:dashWidth="1.5dp"
        android:width="1dp"
        android:color="#FF404040" />

    <size android:height="3dp" />

</shape>

and a listview where i set the divider
<ListView
    android:id="@+id/lv_news_feed_list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:divider="@drawable/ch_dashed_line_divider"
    />

but I want a divider margin left and right.
I also tried to set a padding to the shape, but the listview is ignoring the padding.
    <padding
        android:bottom="15dp"
        android:left="15dp"
        android:right="15dp"
        android:top="15dp" />

Is there any possibility to set a margin to the listview divider  - except in the getView() of the Adapter?
Answer: Inset is the way to go
<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="15dp"
    android:insetRight="15dp" >

    <shape
        android:shape="line" >
        <stroke
            android:dashGap="1dp"
            android:dashWidth="1.5dp"
            android:width="1dp"
            android:color="#FF404040" />

            <size android:height="3dp" />

    </shape>

</inset>

Comment: If we just want a line, use

 and set the property "android:dividerHeight" in the ListView
Comment: Easily the best answer here. This is what the inset xml structure is for.
Answer: Use 'inset'.....
(list_divider.xml)
<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="50dp"
    android:insetRight="50dp" >

 <shape>
    <solid android:color="@color/orange" />
    <corners android:radius="2.0dip" />
</shape>

</inset>

and in your list view add like this...
<ListView
    android:dividerHeight="2dp"
    android:divider="@drawable/list_divider"
    ...
/>

you can set the inset value as desired...
Comment: You can place the `` element directly into the `shape` to avoid repeating the height for every listview.
Answer: You can use the following idea:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/table_background"/>
    </shape>
</item>
<item android:left="2dp" android:right="2dp">
    ... your shape here ...
</item> </layer-list>

It works for me. Hope it will help.
Answer: U can use Gradient to get Right and Left margin instead of stroke.. Try this sample it starts and ends with black, in centre u'll get White.. It appears like u've given margin
 <gradient android:startColor="#000000" android:centerColor="#ffffff"
    android:endColor="#000000" />

Comment: This is a good solution, but i need the stroke for the dashed line in the divider, so i can't use a gradient.
Answer: I don't believe it is possible :/ Although if you add your own drawable at the bottom of each list item and remove the ListViews divider you can customize it however you want :)
Create the folder res/drawable and create a new xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#666666"></solid>

</shape>

..Then use that drawable in you list item.
Or a really quick and dirty way would ofc to create a thin LinearLayout (or some other layout) with colored background at the bottom of the list item to fake a customizable ListView divider..
Not a proper sollution, just some fixit ideas ;)
Comment: This was my first idea to. Attach it yourself in the Adapter but i don't know if this is peformant.
Comment: Try it out and see ;) Or make your own custom ListView, though i doubt it would be worth the trouble.

Listview divider margin


How do I avoid an overbooked GCE zone?

Question: Apparently if too many people use a zone, you won't be able to start instances back up.

Starting VM instance Error: The zone does not have enough resources
  available to fulfill the request

As I'll need to move the instance to a new zone, how do I know which zones are  at high capacity so that I may avoid those?
I'm thinking of moving it from us-east1-b to us-west1-b, as the latter has been busy for over 3 hours
Answer: The information you are looking for is not publicly-available. However, if you know what your needs will be in the longer-term, you can utilize committed use discounts, which will guarantee capacity for you in your zone of choice.
I'll also mention that due to the highly transient nature of many public cloud deployments, instances of resource contention may be very brief, lasting for only minutes perhaps. A corollary of this is that even if you could know which zone is least loaded at one moment, that information has a useful half-life measured in seconds.
Comment: commitments are for CPU's only, afaik. But it's really the GPU that never seems to be available. Is there a way to gaurentee capacity for a GPU ?
Comment: It's kind of a shame that to keep datacenters profitable, they have to buy servers close to max capacity... with few purgeable slots. You would hope that datacenters/zones are only at 70% capacity so that you can book 10 servers at will... but that wouldn't be profitable/efficient they buy hardware linearly as the demand grows. Which means it takes them days to increase capacity if possible. Still I wish there was a way for them to warn me that "capacity is at it's max and will not soon increase due to space limitations."

How do I avoid an overbooked GCE zone?


como mostrar um aviso na tela quando o jogador perde o jogo? feito em javascript

Question: <code>function novoElemento(tagName, className) {
    const elem = document.createElement(tagName)
    elem.className = className
    return elem

}

function Barreira(reversa = false) {
    this.elemento = novoElemento('div', 'barreira')
    const borda = novoElemento('div', 'borda')
    const corpo = novoElemento('div', 'corpo')
    this.elemento.appendChild(reversa ? corpo : borda)
    this.elemento.appendChild(reversa ? borda : corpo)

    this.setAltura = altura => corpo.style.height = `${altura}px`
}

function parDeBarreiras(altura, abertura, x) {
    this.elemento = novoElemento('div', 'par-de-barreiras')
    this.superior = new Barreira(true)
    this.inferior = new Barreira(false)

    this.elemento.appendChild(this.superior.elemento)
    this.elemento.appendChild(this.inferior.elemento)

    this.sortearAbertura = () => {
        const alturaSuperior = Math.random() * (altura - abertura)
        const alturaInferior = altura - abertura - alturaSuperior
        this.superior.setAltura(alturaSuperior)
        this.inferior.setAltura(alturaInferior)
    }

    this.getX = () => parseInt(this.elemento.style.left.split('px')[0])
    this.setX = x => this.elemento.style.left = `${x}px`
    this.getLargura = () => this.elemento.clientWidth

    this.sortearAbertura()
    this.setX(x)

}

function Barreiras(altura, largura, abertura, espaco, notificaPonto) {
    this.pares = [
        new parDeBarreiras(altura, abertura, largura),
        new parDeBarreiras(altura, abertura, largura + espaco),
        new parDeBarreiras(altura, abertura, largura + espaco * 2),
        new parDeBarreiras(altura, abertura, largura + espaco * 3)

    ]
    const deslocamento = 3
    this.animar = () => {
        this.pares.forEach(par => {
            par.setX(par.getX() - deslocamento)

            // quando a barreira sair da area do jogo
            if(par.getX() < -par.getLargura()){
                par.setX(par.getX() + espaco * this.pares.length)
                par.sortearAbertura()

            }
            const meio = largura / 2
            const cruzouOMeio = par.getX() + deslocamento >= meio
            && par.getX() < meio
            if(cruzouOMeio) notificaPonto()
        })
    }
}
// setando o passaro
function Passaro(alturaJogo) {
    let voando = false

    this.elemento = novoElemento('img', 'passaro')
    this.elemento.src = 'imgs/passaro.png'
    // posicao do passaro  e movimento
    this.getY = () => parseInt(this.elemento.style.bottom.split('px')[0])
    this.setY = y => this.elemento.style.bottom = `${y}px`
    window.onkeydown = e => voando = true
    window.onkeyup = e => voando = false

    this.animar = () => {
        const novoY = this.getY() + (voando ?  8 : -5)
        const alturaMaxima = alturaJogo - this.elemento.clientHeight
        //condiçao da altura do passaro
        if(novoY <= 0) {
            this.setY(0)
        } else if (novoY >= alturaMaxima) {
            this.setY(alturaMaxima)

        } else {
            this.setY(novoY)
        }
    }

    this.setY(alturaJogo / 2)

}
//fazendo a pontuaçao
function Progresso() {
    this.elemento = novoElemento('span', 'progresso')
    this.atualizarPontos = pontos => {
        this.elemento.innerHTML = pontos
    }
    this.atualizarPontos(0)

}

function estaoSobrepostos(elementoA, elementoB) {
    const a = elementoA.getBoundingClientRect()
    const b = elementoB.getBoundingClientRect()

    const horizontal = a.left + a.width >= b.left
     && b.left + b.width >= a.left

    const vertical = a.top + a.height >= b.top
      && b.top + b.height >= a.top
   return horizontal && vertical

}

function colidiu(passaro, barreiras) {
    let colidiu = false
    barreiras.pares.forEach(parDeBarreiras => {
        if (!colidiu) {
            const superior = parDeBarreiras.superior.elemento
            const inferior = parDeBarreiras.inferior.elemento
            colidiu = estaoSobrepostos(passaro.elemento, superior)
            || estaoSobrepostos(passaro.elemento, inferior)

        }
    })
    return colidiu
}

function FlappyBird() {
    let pontos = 0

    const areaDoJogo = document.querySelector('[wm-flappy]')
    const altura = areaDoJogo.clientHeight
    const largura = areaDoJogo.clientWidth

    const progresso = new Progresso()
    const barreiras = new Barreiras(altura, largura, 200, 400,
        () => progresso.atualizarPontos(++pontos))
    const passaro = new Passaro(altura)

    areaDoJogo.appendChild(progresso.elemento)
    areaDoJogo.appendChild(passaro.elemento)
    barreiras.pares.forEach(par => areaDoJogo.appendChild(par.elemento))

    this.start = () => {
        // loop do jogo
        const temporizador = setInterval(() => {
            barreiras.animar()
            passaro.animar()

            if (colidiu(passaro, barreiras,)) {
                clearInterval(temporizador)
            }
        }, 20)
    }
}

new FlappyBird().start()
</code>
Answer: Recomendo deixar mais explicito oque você deseja fazer, maaas... você pode simplesmente na função colidir validar, caso não caia no early return que criou crie um alert citando que o user perdeu, pode também abrir um modal com bootstrap e jquery function abreModal() {
$("#myModal").modal({
show: true
});
}
setTimeout(abreModal, 1000); por exemplo. não sei se é isso oque quer fazer.


R Forward and backward Selection

Question: I have a data set with large number of attributes some are not relevant and some are relevant for the regression model. My approach was to do forward and backward selection to identify a starting point, such as which attributes I should drop from the analysis.
I did a forward and backward without any log transformation for the attributes and issue is that the best model provided by forward selection and best model provided by backward selection are different. I am confuse on what I should pick to go forward with.
In addition when you have large number of attributes what is the best way to identify predictors for regression model.
Answer: In brief, forward and backward selection are unfortunately rather poor tools for feature selection.  Frank Harrell is likely the most opinionated (and informed) opponent of the method.  See some of his main comments here:  (And buy his great regression strategy book!):
http://www.stata.com/support/faqs/statistics/stepwise-regression-problems/
I believe LASSO/Elastic Net would be a much safer option if you still want to be constrained to a linear based model without interactions.  The glmnet package in R is a very mature implementation that also has nice cross-validation functions to help you determine the "best/most useful" number of features.

R Forward and backward Selection


Wait Until Data is Fetched from MongoDB React JS

Question: I'm creating a Quiz App. This is the Quiz Page Code. Quiz DB Document contains a QuizQuestions Array which has question ids. Then I fetch specific question from MCQ/Question DB. Fetching MCQ takes time and when I console.log fetched data. First and second time data in undefined then its viewable. Due to this I'm unable to display it as it cause TypeError: Cannot read properties of undefined mcqOptions How can I fix this?
`
import React, { useEffect, useState } from "react";
import shuffleMcq from "../components/shuffleMcq";

const QuizTakePage = ({ match }) => {
  const reqUrl = match.params.path; //Getting Quiz ID From URL
  const [quizInfo, setQuizInfo] = useState({
    "q_title":"",
    "q_seo_description":"",
    "q_questions":[],
    "q_tags":[],
    "m_subject":"", })
  //const fetchQuizData = fetch();
  useEffect(() => {
    const fetchQuizData = async () => {
        const reqApiUrl = '/quiz/api/qid/'+reqUrl;
        const fetchedApiResult = await fetch(reqApiUrl);
        const resultJson = await fetchedApiResult.json();
        setQuizInfo(resultJson);
    }
    fetchQuizData();  }, []);
// Quiz Data START
const quizTitle = quizInfo.q_title;
const quizDesc = quizInfo.q_seo_description;
const quizQuestions = quizInfo.q_questions;
// Quiz Data END
// MCQ Data START
const [currentQuestion, setCurrentQuestion] = useState(0);
const requestedQuestion = quizQuestions[currentQuestion];
const [mcqInfo, setMcqInfo] = useState({
  "m_title":"",
  "m_question":"",
  "m_alternatives":[],
  "m_language":"",  })
useEffect(() => {
  const fetchApiResponse = async () => {
  const reqApiUrl = '/mcq/api/mid/'+requestedQuestion;
  const fetchedApiResult = await fetch(reqApiUrl);
  const resultJson = await fetchedApiResult.json();
  setMcqInfo(resultJson);
  }
  fetchApiResponse(); }, [requestedQuestion]);
  //const mcqLanguage = mcqInfo.m_language;
  const mcqQuestion = mcqInfo.m_question;
  const mcqOptions = mcqInfo.m_alternatives;
  console.log(mcqOptions);
  return (
    <>

{quizTitle}

{quizDesc}

    </>
  );

};
export default QuizTakePage;

Answer: The reason you're getting undefined for the first and second time is due to the fact that useEffect would've not been executed by then. useEffect runs when the component is rendered and mounted for the first time, and then subsequent executions are made when there is a change in dependency array (If there are any dependencies).
You could get rid of the error by rendering the dynamic content conditionally, i.e, displaying it when the data has been fetched.
return (
    <>

{quizTitle.length>0 ? quizTitle : "Loading Question"}

{quizDesc.length>0 ? quizDesc: "Loading Description"}

      {mcqOptions && mcqOptions.length>0 && mcqOptions.map(option=>{
        return(
{option}
) //Using Math.random() for key to ensure all the mapped items have an unique key
      }
      }

    </>
  );

Alternatively, if your mcqOptions is an array of objects you can map it accordingly, for instance, something like this,

      {mcqOptions && mcqOptions.length>0 && mcqOptions.map(mcqOption=>{
        return(
{mcqOption.text}
) //Use the properties accordingly, this is an example only.
      }
      }

Comment: `mcqOptions` which is an array is the one that causing problem. How can I render array conditionally?
Comment: Is it an array of strings or objects?
Comment: Strings but I can turn them in objects if it solves the problem
Comment: I've updated the answer, kindly check.
Comment: Your answer is correct at all, but in this case, a simple mistake causes the `undefiend` error on getting variables.


Memory for crash kernel (0x0 to 0x0) not within permissable range

Question: When booting Centos 5.5 on a  vmbox  running on windows XP I get the following message.
Memory for  crash kernel (0x0 to 0x0) not within permissable range
Answer: By reading http://wiki.centos.org/Manuals/ReleaseNotes/CentOS5.1

During the boot process you may see the message "Memory for crash
  kernel (0x0 to 0x0) notwithin
  permissible range" appear. This
  message comes from the new kdump
  infrastructure. It is a harmless
  message and can be safely ignored.

This is for CentOS 5.1, you can assume it's valid for 5.5 too
Answer: Does the system boot into a useful state? or does the system hang there?
If it boots into a useful state, you can either ignore the message (like I do), or you can allocate some RAM for kdump via system-config-kdump.
If the system doesn't boot, it's rather more interesting.
Comment: The system boots ok.


broken UTF8 characters in MySQL using PHP

Question: I have noticed when dealing with some names that are not of normal spelling ie standard alphabet UK/US are getting lost from my inserting of a record to what actually shows up in the database. I have done quiet a bit of reading regarding the Collation type, which is what I thought was causing the issue, but not sure if this is the case or I'm still doing it wrong as my problem is still persisting.
Below is an example of a record I am creating as well as my database structure, and as you can also see the last_name field has "ö", when I lookup the record I actually see the last_name "Körner"
CREATE TABLE `data` (
  `id` bigint(20) NOT NULL,
  `profile_id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

ALTER TABLE `data`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `profile_id` (`profile_id`);

ALTER TABLE `data`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;

INSERT IGNORE INTO data (profile_id, first_name, last_name) VALUES (1, 'Brent', 'Körner');

The field collation on the last_name is set to 'utf8_general_ci' which that I understand or should I say thought would sort this issue out.
This seems to be something I am doing wrong / missing with PHP, as when I execute the INSERT query within PhpMyAdmin it saves fine.
Comment: Ive just done the Insert Query within the PhpMyAdmin tools and it actually saves fine, which seems to prove the issue is somewhere with PHP
Comment: How are you determining that information is getting lost?  Do you run a select?
Comment: i am using phpMyAdmin to look at the record, and thats when i can see the name has them different characters in, "Körner" instead of "Körner", and when i click on the filed and change it manually it saves with the correct one. Which is leading me to beleive if i can do it manually with phpMyAdmin maybe i am doing something wrong.
Comment: If you set the encoding for your MySQL table to UTF-8, then maybe the problem is on the PHP side of things.
Comment: How are you obtaining the name and inserting it into the db ?
Comment: im collecting it from a JSON payload from a curl request i am making, and then writing that to the db using PHP, i have cut out the middle man just now by defining the values in a php script and no longer making a curl request, and the issue is still happening.
Comment: See "Mojibake" in https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored
Answer: it seems the issue was down to PHP in the end, and i wasn't setting the charset.
For mysql
mysql_set_charset('utf8');

For mysqli
mysqli_set_charset('utf8');

ref https://akrabat.com/utf8-php-and-mysql/
Comment: Be cautious about links that have not been updated in nearly a decade.  That particular link fails to mention `utf8mb4`, refers to antique version of PHP, mentions the `mysql_*` interface in PHP, which should _not_ be used, etc.
Comment: And it links to an older blog that is riddled with a higher percentage of misinformation.


Space leak with wrapper around Data.ByteString.Builder

Question: I have a wrapper type around Data.ByteString.Builder that allows me to track the length of the ByteString being built (cf. my previous question):
import Data.Monoid
import qualified Data.ByteString.Builder as B
import System.IO (stdout)

data LBuilder = LBuilder { toBuilder :: !B.Builder
                         , lbLength  :: !Int }

instance Monoid LBuilder where
    mempty = LBuilder mempty 0
    (LBuilder x1 l1) `mappend` (LBuilder x2 l2) =
        LBuilder (x1 <> x2) (l1 + l2)

char c = LBuilder (B.char7 c) 1
hPutLBuilder h = B.hPutBuilder h . toBuilder

As far as I understand it, this should be roughly as efficient as using Builder directly. But trying the following test case seems to reveal a space leak:
parts = replicate 10000000 $ char 'x'
main = hPutLBuilder stdout $ mconcat parts

Running this code takes a few seconds and consumes around 250MB of memory. Doing the same task with Builder is far faster and needs only 40KB. The memory profile shows that all the extra space is taken up by instances of BuildStep and Builder, which does not happen when using Builder directly.
What makes this code so inefficient? Why does it not happen when using Builder?
Edit:
Michael's answer below, led me to look at how parts is actually evaluated.
After playing around some more, I rewrote the test code in the following way:
makeStuff !acc 0 = acc
makeStuff !acc i = makeStuff (acc <> char 'x') (i - 1)
stuff = makeStuff mempty 10000000
-- stuffOld = mconcat $ replicate 10000000 $ char 'x'
main = hPutLBuilder stdout stuff

Using this definition the performance and memory usage for Builder and LBuilder is exactly the same (i.e. horrible :-). So it looks like the original version is so fast when using Builder because the compiler can somehow rewrite mconcat $ replicate n $ char c into something like B.lazyByteString $ L.replicate n (toAscii c) at compile time, instead of composing 10000000 functions at runtime on the heap. I tried to confirm this by looking at the generated core. I could tell that:

The definition for stuffOld is a call to a relatively short function that does something with types in Data.ByteString.Builder.Internal.
The definition for stuff is a call to makeStuff.
Said core was not meant to be understood by mere mortals.

So I guess this is just the benchmark being a pathological case, and the actual performance problem in my application lies somewhere else.
Answer: One issue is that forcing evaluation of the mconcat parts expression forces evaluation of its lbLength, which in turn will force evaluation of all the individual char 'x' values, which is where the space leak seems to come from. However, the only way I've found to get performance of your code to be the same as the original Builder is to use a newtype around B.Builder. Even just data LBuilder = LBuilder !B.Builder introduces significant overhead.
Comment: Hm. Does `char 'x'` really have to be evaluated more than once? In other words, are there really individual `char 'x'` values, or is there just a single one which is referenced many times?
Comment: That's not an easily answered question, it has to do with GHC's sharing rules. Lifting out `char 'x'` to a top-level definition will likely force the value to be shared.