How to get the 4 coordinates of a rectangle from 3 coordinates?

Question: I want to create a function that allows user to draw rectangle from 3 points (blue points):

The first two points will form an edge (width).
The third point will determine the height.

I need this custom draw function in leaflet, however leaflet's default rectangle is created with 2 diagonal points: https://leafletjs.com/reference-1.5.0.html#rectangle.
I need to calculate one of the green points but my small brain can't seem to figure it out :P
PS/EDIT: The rectangle might be angled, this is what makes it challenging
Answer:
Leaflet's default rectangle is created with 2 diagonal points
[...]
The rectangle might be angled, this is what makes it challenging

Be aware that Leaflet's L.Rectangle is created from a L.LatLngBounds, a bounding box in which the edges are implicitly aligned to the coordinate grid. Don't use bounding boxes, and rely on L.Polygon instead, providing all four points.

Let A and B be the points of the base of the rectangle, and C be the point on the top. Assuming all points are Javascript structures of the form {x: Number, y: Number}, and assuming that you're working in an euclidean plane (i.e. not on the surface of a geoid),
First, calculate the distance from a point to a line defined by the other two points, i.e. the distance from C to the line defined by AB. Let that be distance (note that it's equal to "height" in your diagram):
var distance = Math.abs(
    (A.y - B.y) * C.x  -  (A.x - B-x) * C.y  +  B.x * A.y  -  B.y * A.x )
  ) / Math.sqrt(
    Math.pow(B.y - A.y, 2) + Math.pow(B.x - A.x, 2)
  );

Then, let AB be the vector from A to B
var AB = {  x: B.x - A.x,   y: B.y - A.y };

(Note that the length of AB is equal to "width" in your diagram)
Calculate a unit vector perpendicular to AB:
var perpendicular = {x: -AB.y, y: AB.x}
var perpendicularSize = Math.sqrt(AB.x * AB.x + AB.y * AB.y);
var unit = {x: perpendicular.x / perpendicularSize, y: perpendicular.y / perpendicularSize};

Multiply that unit vector by the distance from C to AB to get the vectors for the "sides" of your rectangle:
var sideVector = { x: unit.x * distance, y: unit.y * distance };

...and create new points D and E by offsetting A and B by the vector for the sides of the rectangle:
var D = { x: A.x + sideVector.x, y: A.y + sideVector.y };
var E = { x: B.x + sideVector.x, y: B.y + sideVector.y };

...And your rectangle is now defined by the points ABDE. Note that C is in the line defined by points DE.
Comment: Awesome! Thanks so much, now that I read your answer, I vaguely remember doing this in school long ago hahaha. I have further question if you don't mind. Since I eventually want to draw the rectangle on leaflet map, would the projection affect the shape? I need the final shape to be a rectangle with 4 right angles. My use case is to draw an angled rectangle; initially I went with a 2 steps method, draw rectangle then rotate, but the rotate plugins that I could find distorts the rectangle due to the projection. Which is why I wanted to use the bounds, what do you suggest?
Comment: Yes, projections can screw your calculations. That's why I added the "assuming that you're working in an euclidean plane" bit. Geometry on the surface of a geoid (or on the surface of a sphere, for that matter) is very different from euclidean geometry, e.g. the angles of a triangle can add up to more than 180° (think triangle with vertices at north pole, equator at prime meridian, equator at 90° meridian), so you cannot ever have a rectangle with four 90° angles.
Comment: In practical terms, you should either redefine your problem in terms of geodesic geometry, or project the data onto a known [CRS](https://en.wikipedia.org/wiki/Spatial_reference_system) (preferably one based on a [conformal projection](https://en.wikipedia.org/wiki/Map_projection#Projections_by_preservation_of_a_metric_property) adequate for your data) and work on that CRS as if it was an euclidean plane.
Comment: I see. I understand now. Thank you so much for explaining! It's interesting and enlightening.
Answer: For Python:
#Given three points fit a rectangle

import math
a,b,c=[1,4],[3,4],[3,10] #Sample numbers

#Distance from dot C to line AB (https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points)
distance= abs((b[1]-a[1])*c[0] - (b[0]-a[0])*c[1] + b[0]*a[1] - b[1]*a[0] ) / math.sqrt((b[1]-a[1])**2 + (b[0]-a[0])**2)
print(distance)
#let AB be the vector from A to B
ab=[b[0]-a[0],b[1]-a[1]]

#unit vector perpendicular to AB (https://en.wikipedia.org/wiki/Unit_vector)
perpendicularSize = math.sqrt(ab[0]**2+ab[1]**2)
unit = [-ab[1]/perpendicularSize ,ab[0]/perpendicularSize]

#Multiply that unit vector by the distance from C to AB to get the vectors for the "sides" of your rectangle
sideVector = [unit[0]*distance,unit[1]*distance]

#create new points D and E by offsetting A and B by the vector for the sides of the rectangle
d=[a[0]+sideVector[0],a[1]+sideVector[1]]
e=[b[0]+sideVector[0],b[1]+sideVector[1]]

print(e,d)  #[3.0, 10.0] [1.0, 10.0]

Answer: Assuming coordinates of those 3 dots are provided,
- 2, 5 (first point)
- 5, 5 (second point)
- x, 8 (third point)
the first green will take x from one of the first two point let's say from the first one => 2, and y from the third point => 8
so the first green point is at 2,8
the second will take x from the second point => 5, and y from the third point => 8
so the second green point is at 5,8
I'm not sure if I understand the answer correctly tho.
Comment: Hi thanks for answering. Yes, this is the base case but it will only work if the rectangle is not at an angle (the edge formed by point 1 and point 2 is parallel to x-axis). However, the rectangle might be angled. So it will be a little more complex.
Comment: Ahh I see, that's a lot more complicated. Now I wanna know the answer too.
Answer: assuming edge1 = [x1,y1]
   , edge2 = [x2,y2]
def calculate_edges (edge1,edge2,height)
    edge3 [0] = edge1[0]          //x3
    edge3 [1] = edge1[1] + height //y3
    edge4 [0] = edge2[0]          //x4
    edge4 [1] = edge2[1] + height //y4
return edge3,edge4

Comment: Hi thanks for answering. Yes, this is the base case but it will only work if the rectangle is not at an angle (the edge formed by point 1 and point 2 is parallel to x-axis). However, the rectangle might be angled. So it will be a little more complex
Comment: here you have to make a landmark transformation (1-assume edge1 is your new landmark, 2 - calculate the coordinates of the other edges using the algo i implemented, 3 - calculate the matrix of transformation (from the new  landmark to the original) and '-finally find coordinates of the different edges in the original landmark )[https://imgur.com/a/WNwIMJB]


Guardar valores e fazer uma comparação

Question: Estou com dificuldade em realizar uma logica para fazer comparação ou algo melhor que vocês possam me indicar.
Estou desenvolvendo um app que contém vários botões em formato de jogo da mega sena.
Preciso fazer com que caso uma bola ja esteja selecionada a cor mude para verde e caso receba um novo clique volte para a cor branca (Já estou conseguindo fazer isso ), porém preciso que caso ja tenha uma bola selecionada não deve ter a possibilidade dele selecionar uma nova.

Meu codigo:
public void buttonClick(View button){
    String tag = (String)button.getTag();
    int numeroInteiro = Integer.parseInt(tag);

    switch (numeroInteiro){
        default:
            if (ballsColor()){
                button.setBackgroundResource(R.mipmap.ball_verde);
            }else {
                button.setBackgroundResource(R.mipmap.ball);
            }
            break;
    }
}

private boolean ballsColor(){
    if (count == 0){
        count++;
        return true;
    } else {
        count--;
        return false;
    }
}

Tem algum jeito de guardar um valor e nao ser sobrescrito em uma nova ação do botão?
Answer: O que você pode fazer é adicionar uma tag para cada botão, criar uma variável selectedTag para armazenar a tag do botão selecionado e usar isso para fazer a lógica que precisa. Observe o código a seguir.
private String selectedTag = null;

public void buttonClick(View button){
    String tag = (String) button.getTag();

    if(this.selectedTag == null){
        button.setBackgroundResource(R.mipmap.ball_verde);
        selectedTag = tag;
    }else if(this.selectedTag.equals(tag)){
        button.setBackgroundResource(R.mipmap.ball);
        selectedTag = null;
    }
}

Estou considerando que o método buttonClick será usado para tratar o evento de click de todos os botões.

Espero ter ajudado.
Comment: Deu certinho, muito obrigado!!

Guardar valores e fazer uma comparação


Nginx forwarding presenting wrong certificate

Question: I have a little problem with nginx. We have two subdomains we own, let's call them domain1.com and domain2.com. For domain2 we don't have further subdomains, for domain1 we have several. If someone enters www.domain2.com I would like nginx to forward the person to https://domain2.com, otherwise just forward them to https://. I achieve this with these two blocks at the end of the config of domain2 in sites-available:
server {
       listen 80;
       server_name domain2.com;
       return 301 https://$http_host$request_uri;
}
server {
       listen 80;
       server_name www.domain2.com;
       return 301 https://domain2.com$request_uri;
}

Also I have HSTS enabled for all subdomains with add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;
Now when navigating to www.domain2.com, browsers throw errors, because nginx presents them with the certificate of a_subdomain.domain1.com. This doesn't happen when directly accessing domain2.com, then nginx presents the correct certificate. And no, reverse proxying the subdomains of domain1 sadly is no option, nginx seems to have trouble with this in combination with PHP.
How do I make nginx to do this right?
Interestingly enough, I also have a config forwarding from a domain we used to host (different from domain1 and domain2) to the new domain on other servers, these forwardings don't have this issue, but the new page probably doesn't use HSTS, so that might be the reason.
Answer: The HSTS policy causes an internal redirect in the browser from HTTP to HTTPS; the browser never sees the redirect configured in Nginx. From the developer tools in the browser (Network tab):

Request URL:
http://www.isdm.rwth-aachen.de/

 Request Method:
GET

Status Code:
307 Internal Redirect

Referrer Policy:
strict-origin-when-cross-origin

The https://www.isdm.rwth-aachen.de/ answers with a certificate from the default server{} block for HTTPS:
$ curl "https://www.isdm.rwth-aachen.de/" -v

* Server certificate:
*  subject: C=DE; ST=Nordrhein-Westfalen; O=RWTH Aachen University; CN=carl.fsmuw.rwth-aachen.de
*  start date: Apr 13 00:00:00 2023 GMT
*  expire date: Apr 12 23:59:59 2024 GMT
*  subjectAltName does not match www.isdm.rwth-aachen.de
* SSL: no alternative certificate subject name matches target host name 'www.isdm.rwth-aachen.de'

To match with this behaviour caused by HSTS, you should configure your Nginx to first redirect to HTTPS and only then between subdomains and apex. All HTTPS subdomains in use should have a valid certificate, which should not be a deal-breaker in the Let's Encrypt era.

As the default (first) server, this already covers the first phase:
server {
    listen 80;
    server_name isdm.rwth-aachen.de;
    return 301 https://$http_host$request_uri;
}

You could alter the second server{} block to perform the second phase, having a valid certificate for the hostname.
server {
    listen 443 ssl;
    server_name www.isdm.rwth-aachen.de;
    ssl_certificate /etc/letsencrypt/live/www.isdm.rwth-aachen.de/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.isdm.rwth-aachen.de/privkey.pem;
    return 301 https://isdm.rwth-aachen.de$request_uri;
}

Comment: Or abandon the `www.isdm.rwth-aachen.de` altogether by removing it from the DNS, as `isdm.rwth-aachen.de` is already a subdomain.
Comment: Thanks for the detailed explanation. Is there a way to not have www.isdm.rwth-aachen.de use encryption? We do not rely on letsencrypt, in fact it's not possible for letsencrypt to create certificates for our domains and the process for us to request new server certificates is still quite manual, even though at least we don't have to hand in the requests by hand anymore. And I'm not sure if SANs can be used for this. So not needing yet another certificate would be helpful. Also, deleting the additional DNS entry for www would effectively defeat the whole purpose of the forwarding.
Comment: The `strict-transport-security: max-age=15768000; includeSubDomains; preload` is cached by the browser for half a year. (As the `preload` not at the domain level `rwth-aachen.de` but at the subdomain `isdm.rwth-aachen.de` it is not preloaded.) Unless you are a time traveler, for not having encryption for the subdomain you would have to remove the `includeSubDomains` from the parent level(s) and wait for six months.
Comment: At least if you don't tell your browser to drop the HSTS policy. Thanks.
Answer: This is mostly comment - but its a bit long....

If someone enters www.domain2.com I would like nginx to forward the person to https://domain2.com

Well, that's a bit silly to start with; you can only have a sungle A record at domain2.com but you can have multiple A or CNAME records at www.domain2.com.

server_name isdm.rwth-aachen.de;

I thought we were talking about [www.]domain[1,2].com

browsers throw errors, because nginx presents them with the certificate of a_subdomain.domain1.com

But you have only shown us a fragment of your config, excluding anything over https and no details of your certificates.


Error trying to obtain metadata from JSON nominatim, Blocked from Nominatim?

Question: I have a big problem with OSM with nominatim. I'm getting the error when i try to obtain metadata from JSON from nominatim url on openstreetmap (shown in the image) .
However, when I make the same request from a different PC everything its OK. Maybe I got blocked?
this is the error:

What could I do to fix it?
Thanks so much
Comment: *from a different PC everything its OK*, do you mean IP address?
Comment: Yes, it works fine form another pc or people (using the same code). They can access to json data and i cant
Comment: it works for me too, its very odd a public api would block ya without reason, maybe you should [contact them](https://nominatim.org/imprint/), give them your public IP and ask if you're blocked for some reason.
Comment: Yes, i sent a email to this contact. Now im.waiting an answer. Thanks ;)
Comment: Did it worked before? Then you got blocked by not adhering to the nominatim usage policy.
Answer: The API block your IP, so use VPN to change it.
It's working
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.


Showing group managers a list of pending users

Question: We're using Drupal Commons 3.3 and our group managers have been asking for a single view of all pending users. Email is becoming too cumbersome and unmanageable. Is there a View or Pane that I can add showing our Group Managers which users should become members?
Answer: First, in the View Commons Contributors - Group (User), I cloned the Display group homepage

In this new content pane, I then added a footer with a link below. This will take the user to the Administer Group/People page.
Manage memberships

Caveat: On Panels (via /admin/structure/types/manage/group/panelizer/page_manager/content), I set view permission to: Logged in User has "Approve or Deny permission for this group"


Creating a file of the desired memory size

Question:
Possible Duplicate:
Create file with given size in Java

Say, I want to create a file of size 1KB, will this approach work?
I create a java array like
char[] s = new char[1024]; //1KByte

and write it to a newly created *.txt file using a writer, will the size of the file be 1Kb precisely? If not, how should i create a file of the desired size?
Comment: http://stackoverflow.com/questions/245251/create-file-with-given-size-in-java this might help!
Answer: The Java char type is 16-bits long and OutputStreamWriter objects are string-oriented, not byte-oriented. Depending on the output encoding of the writer, you could get e.g. a 2 KB file, or even something unpredictable on character sets with a variable number of bytes per character.
You would be better off using an OutputStream directly, either with a byte[] or using write(int) in a loop. That would guarantee that you get what you are asking for.


How to check for instantiation of a python class during unit-tests

Question: I for the life of me can not remember how to test for the instination of a python class.
It was something like:
try:
  m = MyModel()
except:
  ...

I can't remember the exception to call or the assert to use.
Answer: There is no common exception to use for failed instantiation.  The constructor (both __init__ and __new__) can raise any exception it wants.  The except statement you have without an explicit exception will catch every type of exception, which may be what you want.
Comment: Yeah the except statement is currently `except Exception:` to achieve the same as without naming the exception with `assert(False, "Object didn't initialize")`, but still not 100% sold on this. I'll work with it, thanks.   I don't want to override `__init__` or `__new__` in this case because it's for a django Model (which uses lots of voodoo underneath to achieve it's goals).  Thanks.
Answer: I'm not exactly sure what you are asking, however here is a list of all built in exceptions for Python (2.7):
http://docs.python.org/library/exceptions.html
Hope this helps.


Como iniciar no CakePHP3.x

Question: Estou começando agr com o cakephp, segui o tutorial do bookmarker, mas existe algum material com uma didática simples, explicando os conceitos, que são usados no cake?
vejo youtuber usando o AuthComponent, mas não dizem o que é pra que serve, quais os principais métodos/funções/actions, qual a diferença do find pro get, o que é a Entity e a Table presentes na pasta Model e etc... ou só lendo e relendo a documentação oficial mesmo?
Até porque se usa muitos jargões, e pra quem tá iniciando fica mais difícil ainda.
Desde já, grato!
Answer: O melhor material mesmo é o manual do CakePHP. Esse material é bem completo e muito alto explicativo
Algo que complica é que quando você vai mais fundo no Framework muito dessa documentação esta disponível apenas em inglês.
Aconselho a inicialmente usar os tutorias do cookbook
AuthComponent - É um componente do cakephp para gerenciamento de sessões e permissões do usuário, fornecendo funções para login, controle de acesso por perfil de usuário.Conytrola identificação e autorização.
find pro get, o que é a Entity e a Table
Entity e table são os componentes do model
Na table você define métodos e propriedades para o modelo de tabela, validação de dados e de criação de objetos.
Na entity você modela como a entidade da tabela será em si tratada
por exemplo podemos definir na entity quais propriedades do objeto serão enviadosa view, são possíveis de ser editados e quais não
get e find depende da definição da classe
mas aqui entendi que se refere aos métodos fornecidos Pela ORM do cake para busca em banco.
 O get faz a busca unicamente por ID. ou seja sempre retorna um objeto especifico da do modelo.
O find permite a implementação de um método de pesquisa, podendo fazer busca por outras propriedades do objeto que não o id.
Espero ter ajudado

Como iniciar no CakePHP3.x


Find an expression for the posterior distribution of the change-point for this model

Question: The simple change-point problem can be described as follows. Here it is assumed that both $p_1(y)$ and $p_2(y)$ are known completely.

$y_1,...,y_\tau|\tau $ are iid with distribution $p_1(y)$ and $y_{\tau + 1},...,y_n|\tau$ are iid as $p_2(y)$ and $\tau$ takes the values $1,...,n-1$
If $\tau = 0$ it is assumed that $y_1,...,y_n|\tau = 0$, are iid $p_2(y)$
If $\tau = n$ it is assumed that $y_1,...,y_n|\tau = n$, are iid $p_1(y)$

The case $\tau = n$ corresponds to 'No change' and $\tau < n$ to 'change'.
I need to find an expression for the posterior distribution of change-point for this model. Assuming the values $\tau = 0,1,2,...,n$ are allowed.

I know the following: $$\text{posterior} \propto \text{likelihood} \cdot \text{prior}$$
So for this example it might look like: $$p(\tau | y) \propto p(\tau|y)p(\tau)$$
For this case I think it is sufficient to leave the prior as $p(\tau)$ as we are given no additional information about the distributions of $p_1(y)$ and $p_2(y)$. The issue is the likelihood. Any help appreciated.
Answer: Likelihood: $$p(y|\tau) = \bigg[\prod_{n=1}^{\tau} p_1(y) \cdot \prod_{\tau + 1}^{n} p_2(y)\bigg]$$
Prior: $$p(\tau)$$
Therefore the posterior is given by:
$$p(\tau|y) \propto \bigg[\prod_{n=1}^{\tau} p_1(y) \cdot \prod_{\tau + 1}^{n} p_2(y)\bigg] \cdot p(\tau)$$


"styles":[...] in angular.json not working

Question: I have been trying to implement Angular Material in my project and I imported a prebuilt theme in styles.scss. But that didn't work. So I tried to add it to angular.json file but seems that that didn't work out either. Then I finally figured out that whatever added in the "styles":[] in angular.json didn't work in my project(even styles.scss is not working). Does anyone know what might be the issue?
My angular.json file
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "unified-product-assessment": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "ngx-build-plus:browser",
          "options": {
            "outputPath": "dist/unified-product-assessment",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets/"
            ],
            "styles": [
              {
                "input":"node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
              },
              "src/styles.scss"
            ],
            "scripts": [],
            "extraWebpackConfig": "webpack.config.js",
            "commonChunk": false
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "7kb",
                  "maximumError": "10kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all",
              "extraWebpackConfig": "webpack.prod.config.js"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "ngx-build-plus:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "unified-product-assessment:build:production",
              "extraWebpackConfig": "webpack.prod.config.js"
            },
            "development": {
              "browserTarget": "unified-product-assessment:build:development"
            }
          },
          "defaultConfiguration": "development",
          "options": {
            "port": 5000,
            "publicHost": "http://localhost:5000",
            "extraWebpackConfig": "webpack.config.js"
          }
        },
        "extract-i18n": {
          "builder": "ngx-build-plus:extract-i18n",
          "options": {
            "browserTarget": "unified-product-assessment:build",
            "extraWebpackConfig": "webpack.config.js"
          }
        },
        "test": {
          "builder": "ngx-build-plus:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-eslint/builder:lint",
          "options": {
            "lintFilePatterns": [
              "src/**/*.ts",
              "src/**/*.html"
            ]
          }
        }
      }
    }
  },
  "cli": {
    "analytics": "85c84fd2-00e2-4930-b2a7-4da897f60d34",
    "schematicCollections": [
      "@angular-eslint/schematics"
    ]
  }
}

Answer: Try using this format:
"styles": [
          "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
          "src/styles.scss"
         ],

Also do not forget to restart the application with ng serve for changes to apply.
Comment: Thanks for the answer. The problem I was facing was since I was using Microfrontends to implement my application I had to add the .scss file in the angular.json file of the shell.


Mixture and Alligation:::

Question:
A solution contains alcohol and water in the ratio 3:1, 16 litres of
  the Mixture is drawn off and 12 litres of water is added.11 litres of
  Mixture is replaced by 11 litres of water.The alcohol and water ratio
  is 9:13.Find the Intial amount of solution?

How to solve this sum and please guide the steps? I am unable to proceed sum further?
Answer: Say initial solution is $4x \, \mathrm{L}$.
Then quantity of alcohol $=3x \,  \mathrm{L}$
And quantity of water $=x \,  \mathrm{L}$.
Now out of the $16 \,  \mathrm{L}$ of mixture taken away, alcohol $=12 \,  \mathrm{L}$ and water $=4 \,  \mathrm{L}$.
And again $12 \,  \mathrm{L}$ of water is added.
So, now quantity of alcohol $=(3x-12) \,  \mathrm{L}$
And quantity of water $=(x-4+12) \,  \mathrm{L}$.
Again, $11 \,  \mathrm{L}$ of mixture is replaced by $11 \,  \mathrm{L}$ of water.
So, now quantity of alcohol $=(3x-12-\frac{33}{4}) \,  \mathrm{L}$
And quantity of water $=(x-4+12-\frac{11}{4}+11) \,  \mathrm{L}$.
By the problem, $$\frac{3x-12-\frac{33}{4}}{x-4+12-\frac{11}{4}+11}=\frac{9}{13}$$
Solve for $x$ and your answer will be $4x$.
Hope this helps you.
Comment: @Learninguser You are welcome. However you should refrain from asking for upvotes. If your question is good enough then automatically people will give your question upvotes. Merely asking for upvotes makes one look pathetic.
Comment: Thank you for replying this Question.please upvote my question @SchrodingersCat
Comment: @ SchrodingersCat  could you please explain these steps:Again, 11L of mixture is replaced by 11L

of water.

So, now quantity of alcohol =(3x−12−334)L

And quantity of water =(x−4+12−114+11)L. how you done?
Comment: @Learninguser Read the answer carefully. Everything is explained.
Comment: how it becomes 33/4 and 11/4 please explain @SchrodingersCat
Comment: @Learninguser They are respectively the quantity of alcohol and the quantity of water present in 11 litres of the mixture which was replaced by 11 litres of water.
Comment: after replacing 11 litres of mixture , how you are subtracting from the equation 33/4 and 11/4
Comment: @Learninguser I am taking away that much amount of mixture. So I must subtract those parts from the equation.
Comment: How you are getting  33/4 and 11/4  @SchrodingersCat Total 3x-12+x-4+12 = 4x-4,for alcohol 3x-12/4x-4 *11 but i am not getting 33/4
Comment: 1. The answer is quite clear and self explanatory. 2. Read the chapter from which you got this problem; you may be having trouble in understanding ratio and proportions. If latter is the case, then unless you go thoroughly through some proper text, I will not be able to help.
Comment: ok I got it Thank you so Much@ SchrodingersCat Nice Explanation Well Done
Comment: http://math.stackexchange.com/questions/2192480/mixture-and-allegation-problems please guide me this

Mixture and Alligation:::


Inference in Time Series: Prophet vs. ARIMA

Question: I read through Prophet's white paper and they mention that their algorithm,

"gives up some important inferential advantages of a generative model such as an ARIMA." (page 7)

So now I'm curious, what advantages does an ARIMA have for inference?
In my opinion, the parameters/posterior from Prophet's Pystan implementation are relatively clear - are there any bold assumptions that Prophet's algorithm is making that may bias inference that I should be aware of?
Answer: ARIMA and similar models assume some sort of causal relationship between past values and past errors and future values of the time series: $$Y_{t+h}=f(Y_{t},Y_{t-1},Y_{t-2},....,\epsilon_{t},\epsilon_{t-1},\epsilon_{t-2},...)$$ e.g. the volatility of a stock today is causally driven by the volatility of that stock yesterday and two days ago, the population of a species this year is a direct function of the population of that same species last year, etc...
Facebook Prophet doesn't look for any such causal relationships between past and future. Instead, it simply tries to find the best curve to fit to the data, using a linear or logistic curve, and Fourier coefficients for the seasonal components. There is also a regression component, but that is for external regressors, not for the time series itself (The Prophet model is a special case of GAM - Generalized Additive Model).
Theoretically speaking, the assumptions underlying Prophet are indeed simplistic and weak - just fit the best curve to your historical data. Since fitting a curve to a limited data set over a specific time period doesn't impose any constraints on how the curve behaves outside of your historical data set, it is entirely possible that the best fitting curve will "go off the rails" outside of the historical time interval. For example, I have often noticed that Prophet can go negative in the future, even if the historical data set has only positive values, because the simplistic assumptions mean that it will naively perpetuate a downward trend forever.
This why prophet is recommended only for time series where the only informative signals are (relatively stable) trend and seasonality, and the residuals are just noise.
In theory, a more rigorous causal or structural approach is more likely to capture signals that will extrapolate into the future. More importantly, if the residuals are not just noise, then an ARIMA model or a Neural Network might be able to capture those relationships...in theory.
In practice, outside of the examples I mentioned above and a few others, the chances of finding a business time series where the underlying data generating process involves a causal relationship of the type $Y_{t+h}=f(Y_{t},Y_{t-1},Y_{t-2},...)$ are very slim. Think about it: why would sales for a grocery or fashion item ever be driven by a process of the form $Y_t = a_1Y_{t-1}+...a_nY_{t-n}+c+\sigma(t)$?
What causal mechanism would there be that says your sales of butter this week should be a linear combination of your butter sales last week and your butter sales from two weeks ago? Or that your web traffic today should be a linear combination of  your web traffic from yesterday, two days ago, three days ago, and last week?
So at the end of the day, the assumptions of ARIMA and similar models end up being so strong and implausible that, for all of their mathematical rigor, they are just as add-hoc in practice as Prophet or Holt-Winters.
So the simplicity of Prophet's approach in practice makes sense for a lot of business time series. Moreover, the authors acknowledge this in their paper.
Answer: I played with Prophet a bit. They promise big. As I understood their claim was for the framework for massive forecasting. If you have 10,000 series to forecast, there's no way to do it manually. So, let's just run the thing on all of them automatically, and maybe we'll get a decent set of forecast on average.
In finance we also forecast massive numbers of series, e.g. loan loss forecasting may involve millions of loans in the portfolio. In this case we manually strat the portfolio, and manually build models for each strat then run the same model on all loans. Prophet would not need this, because it would estimate a separate model, potentially with its own variables for each loan.
However, I tried Prophet on a different problem. I had just a few series, and looked at the quality of the forecast. The problem that I saw was the "change point" detection. In essence, if I understood right what it's doing then Prophet adjusts the slope if it think it encountered a change point. That was a problem for me because we sometimes have temporary deviations from the mean, could be a different regime, then things get back to old way. In other words mean reversion is quite prevalent. Prophet would not be able to say what is a true change point. However, this is not a criticism of a framework. It's just difficult generally to detect a change point automatically or manually.
Comment: Interesting insight about the forecasting of massive numbers of series, it is the same in retail demand forecasting, where millions of series (#products * #stores) are forecast on a weekly or daily basis. I'm curious though: Why do you see Prophet as providing an advantage in this case? In my field, highly scalable demand forecasting tools (SAP, Oracle, JDA, Manhattan Asscociates, etc...) predate Prophet by almost 2 decades. They are full fledged ERPs, built around sophisticated forecasting and model selection engines, not just elegant APIs that you would build custom code around....
Comment: (...continued) I always assumed Finance would have similar tools, but your answer (if I interpret it correctly) seems to imply that there are no such tools and FB Prophet is finally providing a solution to this. Is that indeed what you are implying? Or such tools in Finance do indeed exist? Do you mind sharing some names and links if that is the case?
Comment: @SkanderH., no I'm not saying Prophet is such a tool. In finance, the products are quite common, e.g. Prime conforming 1st lien 15y mortgage etc. There are a lot of variations, of course. So a COTS solution would be to buy a model that covers many products you have, then you use that model. The models are hand tuned in many cases. You can build your own model any way you want, but practitioners tend to follow a similar approach by building strat models. That's why I'm saying building a model for an individual loan ground up would be an interesting approach if it was automated


SQL Server 2012 - login por autenticação do SQL Server

Question: Na instalação eu coloquei uma senha e a anotei. Quando vou fazer o login por autenticação do SQL server o campo login está em branco, só anotei a senha não sei o login. Tentei o mesmo que do autenticação do Windows, mas não deu certo. Como faço para ver qual é o login? Outra pergunta: tem como alterar o login e senha?
Answer: Encontrei a solução aqui: http://pt.wikihow.com/Redefinir-a-Senha-de-Administrador-do-Sistema-no-SQL-Server
No meu caso, entrei com a autenticação do Windows, depois fui na pasta "segurança - logins" e criei um novo; também vi que meu login era "sa".


Server 2012: change desktop background color

Question: On a Windows Server 2012 Remote Desktop Session Host with the Desktop Experience feature enabled and the desktop wallpaper disabled, users wish to configure own color schemes and define an own desktop background color. However, I seem unable to find an easy way to change the desktop color via the GUI.
I would expect the settings to reside under Appearance settings -> Colors -> Advanced Appearance Settings but those are unavailable in Windows 8 and Server 2012. Is there a replacement GUI dialog for this or do I have the ability to allow users to create their own design schemes containing the appropriate desktop background color?
Answer: Users can still change the desktop background color in Windows Server 2012. Note that you need to have Desktop Experience installed. You also have to allow users to change their colors and desktop background in Group Policy.
The way I did this was:
Open Control Panel. Under Appearance and Personalization, choose Change desktop background.

Choose the drop-down next to Picture location (which is confusing) and change it to Solid colors.

You can select some existing colors.

Or, click More at the bottom left, and you can select a custom color.

Voila! Now my desktop is UGLY, just the way I like it!

Or you can select some other folder with Browse if you want to select a background image from somewhere as a wallpaper.

However, this doesn't complete the picture. As you can see, when I set a solid background color, the taskbar changed but my window borders didn't change. I suspect this is a bug.
To actually override the color of the window decorations (and taskbar) do this:
Open Control Panel. Under Appearance and Personalization, choose Change the theme.

Near the bottom center, choose Color to change the color.

The first tile is Automatic and Windows will derive the colors from the desktop background wallpaper. (Assuming all the bugs are fixed.) Selecting any other tile will allow customization.

I think these are about the only real options users are going to have.
Comment: You *can* do this over RDP connections, but you have to make sure that a) no policy is dictating that wallpapers are disabled for remote desktop users *and* b) the client's connection settings have the "Desktop background" option enabled in the "Performance" tab.
Comment: Ah, I see. I got stuck where I tried to change the desktop background wallpaper and have been greeted with *"Desktop background is turned off during remote connections"* with no available options presented. Apparently, I have to allow wallpapers on the server *and* the clients to be able to access the setting at all. Very annoying, especially since I aim to *not* use wallpapers, but there seems to be no way around it so far.
Comment: Funny, I did that all over an RDP connection!


What is the difference in an app using FFmpeg directly VS using Ffmpeg commandline?

Question: Is there any difference between using FFmpeg directly VS using Ffmpeg command line in an application?
Answer: There isn't: FFmpeg command line is just an app that use the FFmpeg API. Of course when using the app you are limited to what has been implemented (which is surprisingly much, but it isn't as extensive as the API).


Is taking the Euclidean norm of multiple Euclidean norms equivalent to taking the Frobenius norm?

Question: I'm just a programmer venturing into the world of norms (is that even a thing?) here, and am wondering if two formulas are equivalent. Please forgive my ignorance!
Suppose we have a $10\times3$ matrix $\boldsymbol{X}$ ($10$ rows, $3$ columns).
Formula 1: The Euclidean norm of the Euclidean norms of the rows of $\boldsymbol{X}$
$$e = \sqrt{\sum_{i=1}^{10}{\|\boldsymbol{X_i}\|^2}}$$
Procedural description: take the Euclidean norm of all the rows of $\boldsymbol{X}$ and construct a new $10\times1$ matrix (so actually a $10$-element vector) containing the norms and call it $\boldsymbol{e^\prime}$. Then, take the Euclidean norm of $\boldsymbol{e^\prime}$ and call the final result $e$.
Formula 2: The Frobenius norm of $\boldsymbol{X}$
$$f = \|\boldsymbol{X}\|_F$$
Procedural description: Simply take the Frobenius norm of $\boldsymbol{X}$ and call the outcome $f$.

According to a number of simulations I've done on my machine, $e$ is consistently equal to $f$. Am I just getting 'lucky' or are the two actually equivalent?
Comment: The standard spelling is "Euclidean" and I changed it.  (And the etymology will tell you why it makes sense to spell it that way even though we write things like "Kantian", etc.)
Answer: Good observation skills!
Let's chase definitions and then be happy :)
Let me write $n = 10, m = 3$ and let your matrix be denoted $A$.
Then we calculate!
$$
\begin{align}
f &= \|A\|_F \;\; \text{ your defn}
\\ & = \sqrt{\sum_{i=1}^n\sum_{j=1}^m |A_{ij}|^2}\;\; \text{ defn of Frobenius norm}
\\ & = \sqrt{\sum_{i=1}^n\sqrt{\sum_{j=1}^m |A_{ij}|^2}^2} \;\; \text{ maths: $\sqrt{x}^2=x$ if $x \geq 0$}
\\ & = \sqrt{\sum_{i=1}^n \|A_i\|^2} \;\;\text{ defn of Euclidean norm of row $i$}
\\ & = e \;\; \text{ your defn }
\end{align}
$$
Yay :)
Hope that helps!
(See http://en.wikipedia.org/wiki/Matrix_norm)
Comment: Funny how it was only a single step. Thank you!


Centralizar menu na página

Question: Estou tentando alinhar o menu que tenho de forma centralizada, mas as tentativas que fiz foram frustradas e meu conhecimento em css é pouco, o tentei foi fazer alterar isso aqui:

#topNav ul.nav>li.mega-menu {
    position: unset;
}

O código do css é esse:

/** Menu
 **************************************************************** **/
#topBar {
    display:block;
    position:relative;
    background-color:#fff;
    min-height:30px;
    z-index:11;
}
body.boxed #topBar {
    -webkit-border-bottom-left-radius: 0;
    -webkit-border-bottom-right-radius: 0;
    -moz-border-radius-bottomleft: 0;
    -moz-border-radius-bottomright: 0;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}
#topNav a.logo {
    padding:30px 0;
    display:block;
    text-align:center;
    border-bottom: 1px solid #eee;
    z-index:10;
}
#topNav a.logo.onepage {
    display:inline-block;
    height:50px;
    overflow:hidden;
    margin-top:3px;
}
#topBar a.social {
    width:24px; height:24px;
    line-height:26px;
    font-size:16px;
}

#topNav {
    display:block; left:0; right:0; top:0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    background:#fff;
    position:relative;
    z-index:10;

    -webkit-box-shadow: 0 4px 0 rgba(0, 0, 0, 0.04);
       -moz-box-shadow: 0 4px 0 rgba(0, 0, 0, 0.04);
         -o-box-shadow: 0 4px 0 rgba(0, 0, 0, 0.04);
            box-shadow: 0 4px 0 rgba(0, 0, 0, 0.04);
}

#topNav .nav-pills>li>a,
#topNav .nav-pills>li>a:hover,
#topNav .nav-pills>li>a:focus,
#topNav .nav-pills>li.active>a,
#topNav .nav-pills>li.active>a:hover,
#topNav .nav-pills>li.active>a:focus {
    background-color:transparent;
}
#topNav div.navbar-collapse {
    padding:0;
}
#topNav ul.nav>li {
    color:#666;
    border-left:#eee 1px solid;
    text-align:center;
    position:relative;
    margin:0;
}
#topNav ul.nav>li:last-child {
    border-right:#eee 1px solid;
}
#topNav ul.nav>li:hover>a:before,
#topNav ul.nav>li.active>a:before {
    content:' ';
    background-color: #EF4539;
    height: 2px; width: 100%;
    left: 0; top: -3px;
    position: absolute;
}

#topNav ul.nav {
    border-right:#eee 1px solid;
}
#topNav ul.nav>li a {
    color:#000000;
    padding: 15px 25px;
    position: relative;
    text-decoration: none;
    font-size:14px;
    line-height:14px;
    display:block;
    font-weight:300;

    -webkit-transition: all 0.2s;
       -moz-transition: all 0.2s;
         -o-transition: all 0.2s;
            transition: all 0.2s;
}
#topNav ul.nav>li>a>span {
    display:block;
    font-size:12px;
    color:#ccc;

    -webkit-transition: all 0.2s;
       -moz-transition: all 0.2s;
         -o-transition: all 0.2s;
            transition: all 0.2s;
}

#topNav ul.nav>li:hover a {
    color:#333;
}
#topNav ul.nav>li:hover a>span {
    color:#888;
}

/* submenu */
#topNav ul.dropdown-menu li.divider {
    margin:-1px 0 0 0;
    padding:0; border:0;
    border-bottom:rgba(0,0,0,0.2) 1px solid;
}
#topNav .nav li:hover>ul.dropdown-menu {
    padding:0;
    display:block;
    z-index:100;
}

#topNav ul.dropdown-menu {
    text-align:left;
    margin-top:0;
    box-shadow:none;
    border:#eee 1px solid;
    border-top:0;
    list-style:none;
    background-color:#fff;
    box-shadow:rgba(0,0,0,0.2) 0 6px 12px;
    min-width:200px;

    -webkit-border-radius: 0;
       -moz-border-radius: 0;
            border-radius: 0;
}
#topNav ul.dropdown-menu li {
    position:relative;
}
#topNav ul.dropdown-menu>li a {
    margin:0;
    padding:10px 15px;
    font-weight:400;

    color:#555;
    font-size:13px;
    border-bottom:rgba(0,0,0,0.1) 1px solid;
}
#topNav ul.dropdown-menu>li a i.fa {
    margin-right:4px;
}
#topNav ul.dropdown-menu a.dropdown-toggle:after {
    content: "\f105";
    font-family: FontAwesome;
    position: absolute;
    font-size: 15px;
    right: 10px;
    top: 9px;
    color:#999;
}

#topNav .dropdown-submenu > a:after {
    display: block;
    content: " ";
    float: right;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
    border-width: 5px 0 5px 5px;
    border-left-color: #eaeaea;
    margin-top: 5px;
    margin-right: -10px;
}
#topNav .dropdown-submenu li:hover> a:after {
    color:#fff !important;
}
#topNav ul.dropdown-menu li:last-child>a {
    border-bottom:0;
    border-bottom:0;
}
.dropdown-menu>li:hover>a,
.dropdown-menu>li:focus>a {
    color:#fff !important;
    background-color:#333;
}

/* sub-submenu */
#topNav ul.dropdown-menu>li:hover > ul.dropdown-menu {
    display:block;
    position:absolute;
    left:100%; top:0;
    padding:0; margin:0;
    border-top:0 !important;
    border-bottom:0 !important;
    border-right:0 !important;

    border:#eaeaea 1px solid;

    -webkit-border-radius: 0;
       -moz-border-radius: 0;
            border-radius: 0;
}

/* search */
#topNav form.search {
    float:right;
    max-width:180px;
    margin:12px 8px 0 0;
    padding:0;
}
#topNav form.search {
    position:relative;
}
#topNav form.search input {
    padding:6px 26px 6px 6px;
    height:auto; width:100%;
    font-size:13px;
    position:relative;
    z-index:0;

    -webkit-border-radius: 0;
       -moz-border-radius: 0;
            border-radius: 0;
}
#topNav form.search button {
    position:absolute;
    top:10px; right:10px;
    color:#ccc;
    z-index:1;
}

/* mobile */
#topNav button.btn-mobile {
    display:none;
}
    #topNav button.btn-mobile {
        color:#fff;
        display: none;
        background:#333;
        padding:6px 10px;
        margin-top:10px;
        margin-bottom:3px;

        -webkit-border-radius: 0;
           -moz-border-radius: 0;
                border-radius: 0;
    }
    #topNav button.btn-mobile i {
        padding:0; margin:0;
        font-size:21px;
    }

/** Mega Menu
 **************************************************************** **/
#topNav ul.nav>li.mega-menu {
    position:inherit;
}
#topNav ul.nav>li.mega-menu p {
    margin:0; padding:10px 10px 0 10px;
    font-size:13px;
}

#topNav ul.nav>li.mega-menu div.row {
    width:100%;
}

#topNav ul.nav>li.mega-menu div {
    display:table;
}
#topNav ul.nav>li.mega-menu div div {
    border-left:#eee 1px solid;
    margin-left:-1px;
    display: table-cell;
    vertical-align:top;
    float:none;
}
#topNav ul.nav>li.mega-menu div div:first-child {
    border-left:0;
}

#topNav ul.nav>li.mega-menu>ul {
    width:100%;
    background-color:transparent;
    border:none;
    box-shadow:none;
}
#topNav ul.nav>li.mega-menu>ul.dropdown-menu>li {
    margin:0 15px; padding:15px;
    background-color:#fff;
    border: #eee 1px solid;
    box-shadow: rgba(0,0,0,0.2) 0 6px 12px;
}
#topNav ul.nav>li.mega-menu>ul ul {
    margin:0 !important;
    padding:0 !important;
    list-style:none;
}

#topNav ul.nav>li.mega-menu h3 {
    font-size:18px;
    line-height:18px;
    margin:10px 10px 20px 10px; padding:0;
}
#topNav ul.nav>li.mega-menu>ul li>a {
    border-bottom:0;
    padding: 6px 10px;
}
#topNav ul.nav>li.mega-menu>ul li.active>a,
#topNav ul.nav>li.mega-menu>ul li:hover>a {
    color:#fff;
    background-color:#333;
}
#topNav ul.nav>li.mega-menu>ul li.divider {
    border:0;
    border:rgba(0,0,0,0.01) 1px solid;
    margin:10px 0;
}

/** Secondary Main Menu
    Top Bar / Shop Cart
 **************************************************************** **/
#barMain {
    float:right;
    margin-top:6px;
    font-size:12px;
}

#barMain .nav>li>a {
    padding:5px 10px;
}
#barMain .nav>li>a:hover,
#barMain .nav>li>a:focus {
    background-color:rgba(0,0,0,0.03);
}

/* cart */
#barMain .nav>li.quick-cart {
    background-color:#F8F8F8;
    margin-left:10px;
}
#topBar.styleBackgroundColor .nav>li.quick-cart {
    background-color:rgba(0,0,0,0.1) !important;
}
#topBar.styleBackgroundColor .nav>li.quick-cart.open>a {
    color:#000;
}
#topBar.styleBackgroundColor .nav>li.quick-cart p {
    color:#000;
}
#barMain .nav>li.quick-cart>.dropdown-menu {
    border:0; margin:0;
    background-color:#F0F0F0;
    width:185px;
}
#barMain .nav>li.quick-cart .quick-cart-content {
    padding:10px 10px 0 10px;
}
#barMain .nav>li.quick-cart p {
    margin:0; padding:10px 10px 0 10px;
    font-size:13px;
}
#barMain .nav>li.quick-cart a.quick-cart-item {
    clear: both;
    display: block;
    padding: 10px 8px;
    font-size: 13px;
    line-height: 16px;
    min-height: 60px;
    text-decoration: none;
    border-bottom: rgba(0,0,0,0.1) 1px solid;
    background: rgba(0,0,0,0.05);
}
#barMain .nav>li.quick-cart a.quick-cart-item,
#barMain .nav>li.quick-cart a.quick-cart-item a {
    color:#999 !important;
}
#barMain .nav>li.quick-cart a.quick-cart-item:hover {
    background: rgba(0,0,0,0.08);
}
#barMain .nav>li.quick-cart .cart-footer {
    margin-top:10px;
}

/** Responsive Top Nav
 **************************************************************** **/
@media only screen and (max-width: 990px) {
    .navbar-collapse {
        max-height:100%;
    }
    #topNav .container {
        padding:0;
        margin:0;
    }

    #topNav button.btn-mobile {
        display:block;
        float:right;
        margin-right:15px;
    }

    #topNav form.search {
        float:left;
        margin-top:6px;
        margin-left:15px;
    }

    #topNav nav.nav-main {
        background-color:#fff;
    }
    #topNav div.nav-main-collapse,
    #topNav div.nav-main-collapse.in {
        width: 100%;
        margin:50px 0 0 0;
    }
    #topNav div.nav-main-collapse {
        float: none;
        overflow-x:hidden;
    }
    #topNav div.nav-main-collapse.collapse {
        display: none !important;
    }
    #topNav div.nav-main-collapse.in {
        display: block !important;
    }
    #topNav div.nav-main-collapse {
        position: relative;
    }

    #topMain>li>a>span {
        display:none !important;
    }
    #topMain li {
        display:block !important;
        float:none;
        text-align:left;

        -webkit-border-radius: 0;
           -moz-border-radius: 0;
                border-radius: 0;
    }
    #topMain>li>a {
        text-align:left;
        border:0;
        border-bottom:rgba(0,0,0,0.1) 1px solid;

        -webkit-border-radius: 0;
           -moz-border-radius: 0;
                border-radius: 0;
    }
    #topMain>li:hover,
    #topMain>li:hover>a {
        border-top:0 !important;
    }

    #topNav ul.nav>li>a:after {
        content: "\f107";
        font-family: FontAwesome;
        position: absolute;
        font-size: 14px;
        right: 20px;
        top: 15px;
        color:#999;
    }

    /* submenu */
    #topMain ul.dropdown-menu {
        position: static;
        clear: both;
        float: none;
        display: none !important;
        border-left:0 !important;

        -webkit-box-shadow: none;
           -moz-box-shadow: none;
                box-shadow: none;
    }

    #topNav nav.nav-main li.resp-active > ul.dropdown-menu {
        display: block !important;
        margin-left:30px;
        margin-right:30px;
        padding:20px 0;
        border-right:0;
    }
    #topNav nav.nav-main li.resp-active > ul.dropdown-menu li {
        border-left:0;
    }

    #topNav ul.nav>li:hover>a:before,
    #topNav ul.nav>li.active>a:before {
        background-color:transparent;
    }

    #topNav ul.dropdown-menu>li:hover > ul.dropdown-menu {
        position:static;
    }

    /* mega menu */
    #topNav ul.nav>li.mega-menu>ul.dropdown-menu>li {
        padding:0; margin:0 30px 0 0;
        border:0;

        -webkit-box-shadow: none;
           -moz-box-shadow: none;
                box-shadow: none;
    }
    #topNav ul.nav>li.mega-menu h3 {
        margin-left:8px;
    }
    #topNav ul.nav>li.mega-menu>ul li>a {
        border-bottom: rgba(0,0,0,0.1) 1px solid;
    }
    #topNav ul.nav>li.mega-menu div,
    #topNav ul.nav>li.mega-menu div div {
        border:0; margin-bottom:30px;
        display:block;
        width:100%;
    }
    #topNav ul.nav>li.mega-menu div div:last-child {
        margin-bottom:0;
    }
}

@media only screen and (max-width: 479px) {

    #topNav form.search {
        margin-left:4px;
    }
    #topNav button.btn-mobile {
        margin-right:4px;
    }

    #topBar a.logo {
        display:block;
        text-align:center;
        margin:6px 0;
        float:none;
    }

    .hide_mobile {
        display:none;
    }
}

A página com o menu pode ser vista aqui:
Projeto
Comment: Adicione um `width` em `#topNav ul.nav`, acredito que deve resover.
Comment: Adiciono com algum valor específico @RubensBarbosa?
Answer: Isso resolveu o problema aqui no Chrome. Com float:left vc não ia conseguir alinha no centro...
#topNav ul.nav>li {
    color: #666;
    border-left: #eee 1px solid;
    text-align: center;
    position: relative;
    margin: 0;
    display: inline-block;
}

.nav-pills>li {
    /* float: left; */
}

Comment: Acabei de fazer isso, valeu pela dica.
Comment: Muito bom, resolveu meu problema @hugocls, grato.
Comment: @adventistapr que bom que resolveu. Mas.... Depois que vc ajustar sem o float etc , vai ficar faltando um pedaço do border da nav, pq vc só usou border-right, vc vai ter que corrigir isso por estática apenas... ou então retira a borda da direita tb...
Answer: #topNav ul
{
   display: block;
   width: 600px;
   margin: 0px auto;
}

Comment: quebra o menu em duas linhas (contato vai pra linha debaixo)
Comment: @LeoCaracciolo só aumentar o tamanho do menu width: 650px;
Comment: blz, dá certo, mas como sabes que deve ser 650px?
Comment: @LeoCaracciolo Só testando pelo tamanho dos itens do menu. Se o menu for dinâmico essa pode não ser uma boa opção.
Comment: Na verdade o menu já está centralizado, só que ao lado do item `CONTATOS` parece ter um item vazio, talvez a largura da div ou ul, sei lá
Answer: Vou deixar algumas dicas para centralizar elementos HTML
Usando  display flex no elemento pai:
.container {
  display: flex;
  justify-content: center;
}

.elemento-centralizado {
  /* Estilos adicionais para o elemento */
}

Usando margin auto no left e right:
.elemento-centralizado {
  margin: 0 auto;
}

Usando position absolute:
.elemento-centralizado {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Centralizar menu na página


Can I pass arguments to a gulp task?

Question: I'm using gulp in Visual Studio, as a client-side build tool only.
I have lots of tasks which are common across various projects, so I moved them to separate files, and reference them in a project's gulpfile.js as follows:
require("../path/to/task/files/fooCommon.js");  // has a task called "fooCommon"

And then in the gulpfile.js I wrap it in a task:
gulp.task("foo", ["fooCommon"], function () { });

This works nicely, and I can reuse common tasks across projects.
BUT, some tasks require configurations which are only accessible in gulpfile.js - how can I pass them as arguments to a task?
Comment: Is there any reason the common logic needs to actually register the tasks? Why not export something like `module.exports = function(gulp, config){` and have that register the tasks like `require("../path/to/task/files/fooCommon.js")(gulp, {...})`
Comment: @loganfsmyth Unsure what you mean. Though if I'm understanding you correctly, the gulpfile.js won't know about those tasks as they weren't registered. And also, only the gulpfile has access to the config for the project, those external task files have no knowledge of anything other than a single task.
Answer: Two things come to mind. The first would be that instead of fooCommon.js creating tasks, it could create something usable as a gulp plugin, so then to use it, you just pass your config arguments to the plugin. If that doesn't fit well in this case, then you can move your task logic into a wrapper function, e.g.
fooCommon.js
module.exports = function(gulp, config){
    gulp.task("fooCommon", function () {
        // Use the config here
    });
};

Gulpfile
// Define whatever config you need
var gulp = require('gulp');

var config = {...}

var taskCreator = require('../path/to/task/files/fooCommon.js');

// Call the function in 'fooCommon.js', which will be passed the config, and
// will create all the tasks you have in common.
taskCreator(gulp, config);

// Register a task depending on the task created by the exported function.
gulp.task("foo", ["fooCommon"], function () { });

Comment: @hbob Cool. You are right about the last line, I just misunderstood your example, I thought you were saying you also had a body in the `foo` task. When defining a task, you can leave the function off entirely, e.g. `gulp.task("foo", ["fooCommon"]);`
Comment: This works well. Not sure you even need the last line, depending on your setup.
Comment: Thank you, this is a great way to reuse a task so you could use the same tasks at the command line with app 'X' as app 'Y', just passing in an additional parameter at the command line.
Comment: However, this solution would run into problems if you were trying to build multiple apps at once with the same asynchronous tasks.  If the tasks are asynchronous, you'll have a hard time figuring out whether task Foo for app X is completed before you need to load in the config for App Y.  I have a hard time figuring out how to create a truly dynamic, reusable gulp task without the ability to take parameters.

Can I pass arguments to a gulp task?


Use office 365 login/credentials as Single Sign On

Question: Can I use office 365 login/credentials as Single Sign On? Actually I need to sign in my web application using office 365 login details.
Further I want to use following url credentials for Single Sign On in my web application.
https://portal.office.com
Answer: Indeed. Office365 identities are backed by Azure Active Directory, and you can build WebApps, WebAPIs and mobile apps secured using Azure Active Directory, so that customers of Offic365 can SSO to your applications.
The various auth scenarios supported by Azure AD are here: http://msdn.microsoft.com/en-us/library/azure/dn499820.aspx. Code samples are here: http://msdn.microsoft.com/en-us/library/azure/dn646737.aspx.
Hope that helps.


If $X$ and $Y$ are Hausdorff, $X$ is compact, and $f:X\to Y$ is continuous and surjective, then $f$ is open.

Question: I was given the following assertion:

If $X$ and $Y$ are Hausdorff, $X$ is compact, and $f:X\to Y$ is
  continuous and surjective, then $f$ is open.

However, I believe that I have a counterexample:
Define $f:[0,3]\to[0,2]$ by
$$
x\mapsto\begin{cases}
x&0\leq x\leq1,\\
1&1<x<2,\\
x-1&2\leq x\leq3.
\end{cases}
$$
Then $[0,3]$ and $[0,2]$ are Hausdorff, $[0,3]$ is compact, and $f$ is continuous and surjective. However, $[0,3/2)$ is open in $[0,3]$ but $f([0,3/2))=[0,1]$ is not open in $[0,2]$.
Does this look correct? If so, then is there a similar theorem?
Comment: $[0,3/2)$ is open **in $X$**.  The counterexample is correct, and the assertion is wrong.
Comment: @астонвіллаолофмэллбэрг, perhaps whoever told me this meant to say that $f$ is bijective.
Comment: I think $[0,\frac32)$ is not open
Comment: @AlessandroBlasetti, why not?
Comment: @Raptor Can you find an open ball around zero, that is entirely contained in $[0,\frac{3}{2})$?
Comment: @астонвіллаолофмэллбэрг, $B_{3/2}(0)=\{x\in[0,3]:|x|<3/2\}$ does it.
Comment: @RobertIsrael I don't understand how $[0,\frac{3}{2})$ is open in $[0,3]$? The subspace topology on $[0,3]$ says that $[0,\frac{3}{2})$ must be the intersection of an open set in $\mathbb{R}$ with $[0,3]$ in order to be an open set (in the ordinary topology), right? But then that's not true? Or is it?
Comment: @астонвіллаолофмэллбэрг, $[0,3/2)=(-3/2,3/2)\cap[0,3]$.
Comment: It is open in the relative topology which is what is being used here, we are looking at $X$ as it inherits its subspace topology from $\mathbb{R}$. Since for example $(-1,3/2)\cap X= [0,3/2)$ this proves the set is  open ( in the subspace topology)
Comment: @Raptor Oh, I see. I get it. But then there is a very similar statement that is true, something like: "A continuous bijection from a compact space to a Hausdorff space is a homeomorphism". But then your function is not a bijection, so I see where the counterexample is coming from. Right, thank you for this question, and $+1$.
Comment: @Raptor I think so, I really do, because the proof of that fact is a standard (and nice) topological exercise.
Comment: @RobertIsrael you are right! Damn, how fool I have been!
Answer: There are some more or less similar theorems:

If $X$ is compact and $Y$ is Hausdorff, then $f\colon X\to Y$ is closed.
If $f$ is in addtion bijective then $f(U^C)=f(U)^C$ and thus $f$ is open
In functional analysis there is the open mapping theorem. For continuous lineare operators the statement is true, there are open if and only if they are surjective.


Swap 2D Double Arrays in c++

Question: I have the following method to swap two double arrays (double**) in c++.  Profiling the code, the method is accounting for 7% of the runtime...  I was thinking that this should be a low cost operation, any suggestions?  I am new with c++, but i was hoping to just swap the references to the arrays.
 62 void Solver::Swap(double** &v1, double** &v2)
 63 {
 64         double** vswap = NULL;
 65         vswap = v2;
 66         v2 = v1;
 67         v1 = vswap;
 68 }

Comment: What is wrong with the inbuilt swap() function?
Comment: I wasn't aware of it... I'm new to c++.  The two perform the same.
Answer: 1) Make sure your function is inlined.
2) You can inplace swap, using a XOR for instance
3) Try to force the compiler to pass arguments using register instead of the stack (even though there's lot of register stress on x86, it's worth trying) - you can use the standard register keyword or play with fastcall on MS' compiler.
typedef double** TwoDimArray;

class Solver
{
  inline void Swap( register TwoDimArray& a, register TwoDimArray& b )
  {
    a ^= b ^= a ^= b;
  }
};

4) Don't bother giving default values for temporaries like vswap.
Comment: Something is fishy with your compile settings if this changes make it faster; are you sure you are using a high optimisation level? Typically, inline and register is simply ignored by the compiler, and the XOR swap _shouldn't_ be significantly faster than a register-register copy ;)
Comment: A member function defined inside its class' definition is implicitly inlined.
Comment: Nice solution, but identifiers in C++ don't start with a number "2DArray".
Comment: My mistake, i wrote it too fast :) it's corrected.
Concerning the implicit inlining of inside-class methods, that's a matter of style, i like to emphasis inline and virtual keywords.
Comment: Not sure I follow, where are a and b coming from?
Comment: They are just the identifiers passed as arguments
Comment: Thank you, using 'register' and 'inline' swap no longer shows up in the profile.  Before I call it a done deal, is it possible that inline is preventing the profiler from seeing the method calls all together?  Note I have some errors trying the binary operators "invalid operands of types 'double**' and 'double**' to binary 'operator^'"
Comment: I suppose the improvement you see comes from `inline`. (I'd be surprised if a modern compiler would actually pay much attention to `register` and on that XORing swap trick I'm with Anteru.)
Comment: I think I've read analysis that the xor-swap should be *slower* than normal swap, in addition to just breaking under certain conditions (swap something with itself), and I don't think it should even work for pointers. May-be just inlining did it?
Comment: IMHO it's a common myth nowadays that compilers are sooo smart compared to programmer. And all these specifiers are just ignored. Truly, i don't think so. Optimization is just a matter of finding tricky specifiers, build, and retry until the assembly looks like what you want.
There is no way to know if you a XOR will be fast than a copy on specific platform. Even on very close CPUs this may change. You have to test each possibility.
Comment: Also see http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice
Comment: Thank you for the great feedback, this post with comments definitely helped me out.
Answer: The code looks fine. Its is just a pointer assignment. It depends on how many times the method was got called.
Comment: It's being called once every iteration to swap the new and old arrays.  The array itself is 2x20000.  Could the size of the array be an issue?
Answer: I guess your profiler is getting confused here a bit, as this method really only swaps two pointers, which is very cheap. Unless this method is called a lot, it shouldn't show up in a profile. Does your profiler tell you how often this method gets called?
One issue you have to be aware of with swapping is that one array might be in the cache and the other not (especially if they are large), so constantly swapping pointers might trash the cache, but this would show up as a general slow-down.
Comment: The arrays are both large and swapped a lot.   It's being used in an RK4 method I am working on.  What is bugging me is that the Swap is costing more than the derivative evaluation.  The derivative is being calculated some 24M times, while the swap just 502, however Swap is accounting for 21% and the derivative just 13%.  Note the derivative is rather simple atm... (t^3) but all the same.
Comment: It could be also due to your swap getting inlined (your running with optimisation on, aren't you) and this could skew the numbers.
Answer: Are you sure you profiled fully optimized code?
You should inlinethis function.
Other than that the only thing I see is that you first assign NULL to vswap and immediately afterwards some other value - but this should be taken care of by the optimizer.
 inline void Solver::Swap(double** &v1, double** &v2)
 {
   double** vswap = v2;
   v2 = v1;
   v1 = vswap;
 }

However, why don't you use std::swap()?
Comment: I actually didn't know of std::swap... (oops)  On the plus, the two perform at the same speed. Ty for pointing me to std::swap
Answer: Don't assume that the 7% means this operation is slow - it depends on what else is going on.
You can have an operation that only takes 1 nanosecond, and make it take nearly 100% of the time, by doing nothing else.

Swap 2D Double Arrays in c++


How client will automatically detect a new leader when the primary one goes down in Kafka?

Question: Consider the below scenario:

I have a Kakfa broker cluster(localhost:9002,localhost:9003,localhost:9004,localhost:9005).
Let's say localhost:9002 is my primary(leader) for the cluster.
Now my producer is producing data and sending it to the broker(localhost:9002).
If my primary broker(localhost:9002) goes down, with the help of Zookeeper or some other consensus algorithm new leader will be elected(consider localhost:9003 is now the new leader).

So, in the above scenario can someone please explain to me how the Kafka client(producer) will get notified about the new broker configuration(localhost:9003) and how it will connect to the new leaders and start producing data again.
Answer: Kafka clients are receiving the necessary meta information from the cluster automatically on each request when reading from or writing to a topic in case of a leadership change.
In general, the client sends a (read/write) request to one of the bootstrap server, listed in the configuration bootstrap.servers. This initial request (hence called bootstrap) returns the details on which broker the topic partition leader is located so that the client can communicate directly with that broker. Each individual broker contains all meta information for the entire cluster, meaning also having the knowledge on the partition leader of other brokers.
Now, if one of your broker goes down and the leadership of a topic partition switches, your producer will get notified about it through that mechanism.
There is a KafkaProducer configuration called metadata.max.age.ms which you can modify to update metadata on your producer even if there is no leadership change happening:

"Controls how long the producer will cache metadata for a topic that's idle. If the elapsed time since a topic was last produced to exceeds the metadata idle duration, then the topic's metadata is forgotten and the next access to it will force a metadata fetch request."

Just a few notes on your question:

The term "Kafka broker cluster" does not really exists. You have a Kafka cluster containing one or multiple Kafka brokers.

You do not have a broker as a "primary(leader) for the cluster" but you have for each TopicPartition a leader. Maybe you mean the Controller which is located on one of the brokers within your cluster.
Comment: Thanks for the explanation. Actually, I am new to Kafka and I am implementing a small prototype of Kafka using Netty and in my application whenever I am closing the primary broker and trying to connect the next leader I am getting an error:

`java.io.IOException: Connection reset by peer
 at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
 at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)`

I know the error is occurring because I am abruptly aborted the connection in midst of a transaction, but I just want to understand how Kafka handles this.


SQL Order by using the values from two different columns

Question: Suppose I have a table NAME with the columns PART_TYPE and VALUE. Each type can have multiple types like FAMILY, GIVEN, PREFIX, etc.
What I would like to do is write SQL to get all the names but have them first ordered by a specific type then have them ordered alphabetically within that type.
I have something like this:
SELECT *
FROM name
ORDER BY (
  CASE
    WHEN PART_TYPE = 'GIV'
    THEN VALUE
  END)

But I'm not sure how to include the other types as a primary order while keeping the VALUE as the secondary order. Adding another case statement will then just make VALUE the primary order.
I would like to keep this database independent but if need be, I would be willing to make it Oracle specific.
How can I do this? Also, a way of doing this with Hibernate Criteria would also be greatly appreciated.
Edit: I need the PART_TYPE to be ordered by a specific order as defined by me. In particular, it needs to be GIVEN then FAMILY.
So it should look like this:
GIVEN  A
GIVEN  B
GIVEN  C
FAMILY A
FAMILY B

The natural order by would have FAMILY first, not GIVEN.
Comment: `ORDER BY TYPE, VALUE` ?
Comment: @zerkms How to ensure the type is ordered by GIVEN then FAMILY?
Comment: This is a similar issue to this question: http://stackoverflow.com/questions/10350330/oracle-sql-modifying-data-in-order-by/10350445#10350445
Comment: Thanks for the answers. I am holding out to see if anyone has a Hibernate Criteria version of this. If one does not appear in a few hours, I'll still accept an answer.
Comment: `ORDER BY part_type DESC, value`?
Comment: @Dems There's more part types than that. The answers below solved this.
Comment: @AHungerArtist - Your comment on GarethD's answer states specifically `Fortunately there's only two types I have to worry about and it should be pretty consistent.`  But yes, if you have to re-order *multiple* entities, a table with a sort_order field is the way to go :)
Comment: @Dems I mean there's only two types I have to sort. There's more than two total types (as alluded to by the mention of PREFIX in the opening  sentence) but I only care about sorting on those two. Those other types come alphabetically before and after GIVEN AND FAMILY, so that why's that wouldn't work.
Answer: The most manageable way of resolving this is probably to have a table containing all your Types, and then a sort column within that. So you might have a table like:
TypeID      Name      SortOrder
1           FAMILY    2
2           GIVEN     1
3           PREFIX    3

Then you Can join this on to your query and use:
ORDER BY SortOrder, Value

You could just resolve this with a CASE expression
ORDER BY CASE Type
            WHEN 'GIVEN' THEN 1
            WHEN 'FAMILY' THEN 2
            WHEN 'PREFIX' THEN 3
            END,
            Value

But the more types you have the less manageable the case expression becomes.
Comment: Fortunately there's only two types I have to worry about and it should be pretty consistent.
Answer: SELECT *
FROM name
ORDER BY
  CASE
        WHEN TYPE = 'GIVEN' THEN 1
        WHEN TYPE = 'FAMILY' THEN 2
        ELSE 3
     END,
  VALUE

This will order the result by a custom order on TYPE and VALUE as the secondary order.
Comment: But I need the type to be in a specific order, not by whatever order by defaults to. So, I need it to first sort by GIVEN, then FAMILy.
Answer: ORDER BY CASE TYPE
             WHEN 'GIVEN' THEN 0
             WHEN 'FAMILY' THEN 1
             ELSE 2
         END,
         VALUE

Answer: Feels a bit 'hacky' but it works
SELECT part_type,name
FROM (
SELECT
CASE
WHEN part_type = 'Given' THEN 'A'
WHEN part_type = 'Family' THEN 'B'
END AS Sorthack,
part_type,
name
FROM NAME
) Sort

ORDER BY sorthack,name


Infinite Series: $\sum_{n=1}^\infty \frac{1}{2^nn}$

Question: Just encountered a problem in my BC Calculus sequences and series unit that I just can't figure out.
I don't know the latex, but the problem was to find compute
$$
\sum_{n=1}^\infty \frac{1}{2^nn}
$$
The handout was just on convergence, so it was easy to see that by ratio test, it does converge, but I think I'm missing some ideas to be able to calculate the sum.
We have done Taylor series, I just don't quite know how to go backwards, although my guess is that you find a way to write the partial sums and find it's value as the limit approaches infinity.
How would you go about solving this?
Thanks!
Comment: Hint: what if you differentiated $\sum x^n/n$? What series do you get?
Comment: Ahh, got it. It's the sum of x^(n-1), which can easily be computed, so just integrate 1/(1-x) and make x=1/2. That makes a lot of sense, thank you so much!
Comment: Hint: What function has a Taylor series resembling $\sum x^n/n$?
Comment: e^x is close to that with $\sum x^n/n!$.
Comment: sum x^(n-1) right?
Comment: No, I left out the factorial. No factorials.
Answer: $\sum_{n=0}^\infty x^n = \frac{1}{1-x}, $ for $|x|<1$. Geometric series.
Integrate both sides to get
$\sum_{n=1}^\infty \frac{x^n}{n} = C-\ln (1-x), $ for $|x|<1$.
For $x=0$ you see that $C=0$. Then substitute $x=1/2$ to get $\ln 2$
The integration is valid for any closed interval $[-a,a]$ for $a \in [0,1)$
Comment: That makes a lot of sense thank you so much. As a follow up, the sum of 1/(2^n*n!) was also asked on this handout. What would be your approach? Integrals seem pretty tricky with factorials.
Comment: In this case the series is $e^{1/2}$. You have to know the Taylor series for some basic functions.
Comment: Also, substituting x=1/2 means the sum = -ln(1/2), which according to WolframAlpha should be ln(2). Thoughts?
Comment: I wrote the same.
Comment: How did you get ln(2)?
Comment: $-\ln(1-\frac{1}{2})=-\ln (\frac{1}{2})=-\ln (2^{-1})=-(-1)\ln (2) = \ln (2).$


Is setting a FILE* equal to stdout portable?

Question: I've got a function that needs to be able to write to either stdout, or to a file, depending on what the user wants. It defaults to standard out though. To accomplish this, I'm doing the following (minus error checking etc):
FILE* out;
if (writeToFile) { /*Code to open file*/; }

else
    out = stdout;

// ...rest of the function goes here

if (out != stdout)
    fclose(out);

This certainly does the trick, but I have no idea how portable it is. And if it's not, and/or there's another problem with it, how should I go about this?
Answer: Yes, it's portable and it's fine, provided you don't also mess with the low-level implementation of *stdout (e.g. by calling close(fileno(stdout)) on Posix or using dup).
Answer: It should be fine. You might have trouble if you pass the pointer back and forth across the boundary of a DLL (ie, C code outside DLL passes pointer to stdout to C code inside DLL), but apart from that it should be portable.


8 - Register form automatically fills in input fields

Question: I am using the core user-register-form to let users register to my site. When I first want to register a new account the form is displayed as followed:

Now, when I enter credentials and submit the form, the user is created. I can login and out with the created user.
However, if I want to register ANOTHER new account the form automatically fills in the e-mail and username of the user I just created.

I have tried several things that did not solve the problem:

Clear Drupal cache
Close browser and re-open
Kill browser and re-open
Open incognito browser
Clear browser cache
Disabled browser auto-fill

I also tried clearing the inputs using jQuery val(''); but then the form doesn't submit properly.
I assume this has something to do with drupal core? Please advice!
Answer: I found a solution thanks to the Drupal Community
Apparently this is defined in the core of Drupal: core/modules/user/src/RegisterForm.php
The following should be set to FALSE
// For non-admin users, populate the form fields using data from the browser.
    if (!$admin) {
      $form['#attributes']['data-user-info-from-browser'] = TRUE;
    }

However it would be better to not mess with the core values and write a form_hook_alter instead in your theme file:
function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
    $form['#attributes']['data-user-info-from-browser'] = FALSE;
  }
}

This solved the problem.


Which of these situations is a new shift?

Question: In the NHL, when tracking the relevant statistics (ice time, number of shifts, time per shift, etc) for player a on team A, while team A is playing team B, does a shift officially end in the following situations? I cannot find any official rules for this, so if possible please point me to the correct reference!
In each of the following situations, does it count as a new shift or a continuation of the previous shift?

Player a is on the ice, a stoppage of play occurs causing the clock to be stopped, and player a chooses to remain on the ice for the ensuing faceoff.
Player a is on the ice, either team scores, and player a chooses to remain on the ice for the ensuing faceoff.
Player a is on the ice, either team commits a penalty causing a stoppage of play, and player a chooses to remain on the ice for the ensuing faceoff.
Player a is on the ice, player a commits a penalty and goes to the penalty box, and then player a comes back on the ice after serving the penalty time.
Player a is on the ice, player a commits a penalty and goes to the penalty box, and then player a comes back on the ice, before serving all of the penalty time because team B scores, for the ensuing faceoff.
Player a is on the ice, the period ends, and player a starts on the ice for the next period.
Comment: Interesting question, fellow Joe, and if you happened to find out the answer in the last year, please update us!  I suspect I know the answer to these, but I'm definitely not sure - and it doesn't seem like it's readily available, just not as much meta-analysis about ice hockey as there is about baseball or football unfortunately...
Comment: BTW @Joe the OP, added the "Edit" section to my answer with more info
Answer: Answering based on watching hundreds of hours of the sport.
A player's shift is however long they stayed on ice without any break of the game clock. That is if there is a stoppage like a penalty or TV timeout and the player was on ice before and after it, it's still the shift as the game clock didn't pass without the player off ice.
But if the game clock resets, like it does at the end of the periods, then that players shift also ends. Most skaters shifts are typically averaged from 45 seconds to a minutes, but that doesn't mean all shifts are in that range. You can see players on ice for 2+ minutes in case of a penalty kill, or end of game push to score/keep the other team from scoring.
Shifts are based on line changes, but not always when it comes to individual players.
Some coaches like to always have at least 1 center on ice as much as possible, so they instruct players so that the center on ice comes off only after the next shift's center has come on ice.
If the on ice center comes off and then the replacing center on, there is a short amount of time no center is on ice and a faceoff could be called, and you would end up with no center to take the faceoff (see why centers take faceoffs).
Or you could have a player who had some portion of their shift, then a penalty occurs, and so they remain on ice to penalty kill, even though the rest of their line got off ice. In this case the rest of the line completed a shift, but this player is still continuing theirs since they're part of the penalty kill unit. Similar situation can happen if a player is part of the power play unit.
So in cases 1 to 3, this is the same shift. By the way, as Parker mentioned, who stays on ice is the coaches decisions, not the players.
For case 4 I'm inclined to say it's a new shift, as the game clock has passed since the last time the player was on ice. After  penalties you usually see the offender come back on ice and skate for a while, I believe this is a shift. But sometimes you see the offender sprint the length of ice so a more suitable player can get on ice instead of them. In this case, I'm not sure if that's a 1 or 2 second shift or not (maybe it's just ignored??).
In Case 5 if the player stays on ice, then it's a new shift. But in most cases the offender and most of the penalty kill unit go back on bench for a break.
Case 6 is a new shift as the period ended.
EDIT: Based on Joe's comment on this answer I'm adding the post.
As stated earlier, a shift is however long a player is on ice without game clock break.
A shift is so fundamental you're not gonna see a definition for it on nhl.com.
Hockeyviz, a website that puts visualized basic and advanced stats defines a shift as following:

A shift for a player is the total time from when they set skate on the
ice until they leave the ice; usually they will return to the bench
but sometimes they will go to the dressing room or to the penalty box.

So as stated above, my answer for all cases remains the same.
Alex Kovelav's 5 minute shift is a famous long shift. Within this shift, there is an icing and an offside which both stop the play. There are 3 power plays, 1 by his team, 2 by the opponent against Kovalev himself. Kovalev scores on one of the power plays too. The shift finally comes to an end as the period ends. Many stoppages, all same shift. And if you don't believe it's all the same shift, look at the linked video uploaded by the NHL itself calling it a 5 minute shift!
Comment: A shift is a shift. You're not gonna find a definition for a shift on nhl.com. Advanced hockey stats are things like high danger chance, corsi, fenwick, you're not gonna see shift info on a website like hockey-reference either. You can have multiple faceoffs within a shift. Anyways, added an edit section to my answer to address your comment
Comment: With the edit it is now a good answer now, thanks!
Answer: Being more Advanced stats rather than rules shift lengths vary and can be subject to interpretation.  Typically a shift would be time on ice during the normal course of play through the game which are often less than a minute in the NHL.  Your situations are interesting though.
For 1-3: Typically the coaches get to decide who stays on ice after a stoppage in play.  If the players remain on ice after a stoppage then that is considered part of their shift, not a new shift.
For 4 & 5: This is where I am unsure due to the fact that the player is not on ice but rather in the box and whether they stay afterwards or not is the time in the penalty box considered a shift?
For 6: Starting a new period would be considered a new shift.
I believe other advanced stats may be more useful such as time on ice but the NHL rulebook doesn't provide any context for game statistics.


Swift- Customize multiple Navigation bars in a Tab bar controller

Question: computer science student trying to learn Swift here. Sorry for the image links in advance. Apparently I'm not yet allowed to embed images. I'm playing around with an application that uses navigation controllers and a tab bar controller. The initial view, which I'll call root, is embedded into a navigation controller like this. This is because I want to be able to go back to my root view at some point.
Root segues to a tab bar controller that has two tabs, which I'll call 1A and 2A. 1A and 2A both segue to another VC, which I'll call 1B and 2B. I've embedded 1A and 2A in their own navigation controllers like this so that I can navigate between the A's and B's. If I leave it as is, the navigation bars for 1 and 2 will overlap with the root navigation bar like this. So I wanted to change the height of navigation bars 1 and 2 to be just under the root navigation bar like this.
I tried to accomplish this with the following code in the viewDidLoad methods of 1A and 2A but that didn't do anything.
<code>    override func viewDidLoad() {
        super.viewDidLoad()
        let bounds = self.navigationController!.navigationBar.bounds
        self.navigationController?.navigationBar.frame = CGRect(x: 0, y:   0, width: bounds.width, height: 100)
    }
</code>
I've read apple's documentation on Navigation Controllers and bars etc. And I've visited various threads here but I haven't found a solution specific to my problem. Maybe I'm missing something so rudimentary that there is no question for it. Anyways, an example and explanation would be greatly appreciated. Thanks
Comment: Nooo. You can't do that. And if do it, say, you do it in the most customisable way, users will think that your app has a bug. You can only have one navigation bar per screen!
Comment: Hide the root navigationController's navigationBar when you push to tabbaController and show when you popToRoot
Comment: Apple would reject this, take a look at their guidelines: https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/
Comment: @Glenn eventually, I'm going to replace the root back button with something like a home icon so that it'll be a home button and then below is the back button. Would that still be unacceptable?
Answer: I found the correct answer here: How to move back to the root view controller in storyboard?
I should have been using an unwind segue to navigate back through multiple views


Websocket 431 error: Unexpected server response

Question: I have been building an application for myself to scan certain pumps etc. where I need the 1h and the 5m candle data to track such events. The code was working fine, untill it gave a 431 error: Unexpected server response. I am using c9 to code but I read that it was probably the websocket having to get to many request at once. So I tried putting a setInterval() in there, but still the same error.
Any suggestions on the code and how that problem is solved?
<code>var market1h = 'not yet defined';
var market5m = 'not yet defined';

binance.prevDay(false, (error, prevDay) => {
    let markets = [];
    for ( let obj of prevDay ) {
        let symbol = obj.symbol;
        markets.push(symbol);
    }
    setInterval(get1hData, 1500);
    setInterval(get5mData, 1200);

    function get1hData(){
        binance.websockets.candlesticks(markets, '1h', (candlestickData) => {
        let tick = binance.last(candlestickData);
        market1h = candlestickData[tick];
        io.emit('market1h', market1h);
        });
    }
    function get5mData(){
        binance.websockets.candlesticks(markets, '5m', (candlestickData) => {
        let tick = binance.last(candlestickData);
        market5m = candlestickData[tick];
        io.emit("market5m", market5m);
        });
    }
});
</code>
Answer: strlen(url.path) was the tipping point for me.
strlen 7929 = success
strlen 7942 = fail
I didn't find any official documentation on the 431 response.
If I had to guess: Front end servers reject urls over a certain size; and don't make it to the back end servers for processing.
update:

431 Request Header Fields Too Large response status code indicates
  that the server is unwilling to process the request because its header
  fields are too large.

ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/431


How do I group and add space between checkboxes?

Question: I need to group the checkboxes and put some spacing between each group.
They need to look like this:
<code>item1
item2

item3
item4
</code>
I can easily add an additional field to the options array specifying which group each item belongs to but I how do I render them this way?
I imagine I would have to do this by adding classes. But how do I do that?
Answer: You can normally do this already without any extra effort.
Each option should have a class assigned to it that you can target in your CSS.
You can then apply any spacing you like there.
Comment: @Gurdian How do I apply classes to individual checkbox elements based on what group it belongs in?


D3.js / NVD3.js does not display correct values

Question: I'm new to D3.js and NVD3.js. I created a multi-line chart for displaying statistics. The displayed numbers on y-axis and inside the chart are integers only.
However it does not display the correct values from the dataset. The JSON input looks like this:
[{"key":"Anmeldungen","values":[[1446505200,92],[1447023600,112],[1447542000,361],[1448665200,6],[1449183600,10],[1449788400,2],[1449961200,3],[1450738800,4],[1451343600,9],[1451689200,2],[1452294000,7],[1452380400,5],[1453330800,7],[1453849200,2],[1454540400,4],[1454799600,7]]},{"key":"Abmeldungen ","values":[[1446505200,223],[1447023600,264],[1447542000,82],[1448665200,0],[1449183600,0],[1449788400,0],[1449961200,0],[1450738800,0],[1451343600,0],[1451689200,0],[1452294000,0],[1452380400,0],[1453330800,2],[1453849200,0],[1454540400,0],[1454799600,0]]}]

The first number of the value is a timestamp, that is displayed correctly in the chart. The second number is the integer value I'm having trouble with.
The code for rendering the chart is the following:
var $json = JSON.parse($json);
nv.addGraph(function () {
    data = $json;
    var chart = nv.models.cumulativeLineChart()
            .x(function (d) {
                return d[0]*1000 //timestamp
            })
            .y(function (d) {
                console.log(d); //<--Outputs correct number
                return d[1]
            })
            .color(d3.scale.category10().range())
            .useInteractiveGuideline(true)
        ;

    chart.xAxis
        .tickFormat(function(d) {
            return d3.time.format('%d.%m.%Y')(new Date(d))
        });

    chart.yAxis
        .tickFormat(d3.format('d'));

    console.log(data); // <-- still has the correct data

    d3.select('.diagrammContainer svg').datum(data).call(chart);

    return chart;
});

I also tried to change
chart.yAxis
        .tickFormat(d3.format('d'));

to
chart.yAxis
        .tickFormat(d3.format(',f'));

which displayed floating numbers on the y-axis. But the values are still incorrect. I also do not understand why it converts a few numbers to negatives.
The both console.log´s in the code output the correct values. What does D3.js / NVD3.js do with the numbers that the chart looks like this?
result
Answer: So, after trying to debug this for a little while, I did some googling. These were my two findings:

The values of the data you create the chart from should be objects rather than arrays, so instead of {"key":"Anmeldungen","values":[[1446505200,92],..., you want ..."values":[{ x: 1446505200, y: 92},.... In changing this, you also need to change .x() and .y() functions to return d.x*1000 and d.y, respectively.
Evidently the mishandling of y-values by the nvd3 cumulative line chart is a known issue, but if you change it to a lineChart instead(i.e. var chart = nv.models.cumulativeLineChart() to var chart = nv.models.lineChart()), it will resolve the y-values correctly.

I took the liberty of creating a snippet demonstrating how it works with the data value arrays replaced with {x:_, y:_} objects, and here is a jsfiddle I modified from the one in the github issues thread with your data, if you'd like to play around with it.

var data = [{"key":"AN","values":[[1446505200,92],[1447023600,112],[1447542000,361],[1448665200,6],[1449183600,10],[1449788400,2],[1449961200,3],[1450738800,4],[1451343600,9],[1451689200,2],[1452294000,7],[1452380400,5],[1453330800,7],[1453849200,2],[1454540400,4],[1454799600,7]]},{"key":"AB ","values":[[1446505200,223],[1447023600,264],[1447542000,82],[1448665200,0],[1449183600,0],[1449788400,0],[1449961200,0],[1450738800,0],[1451343600,0],[1451689200,0],[1452294000,0],[1452380400,0],[1453330800,2],[1453849200,0],[1454540400,0],[1454799600,0]]}];

for (var i = 0; i < data.length; i++) {
 for (var j = 0; j < data[i].values.length; j++) {
   data[i].values[j] = {
     x: data[i].values[j][0],
      y: data[i].values[j][1]
    };
  }
}

console.log(data);

window.nv.addGraph(function() {
  var chart = nv.models.lineChart()
                .x(function(d) {return d.x*1000})
                .y(function(d) {return d.y})
    .useInteractiveGuideline(true)
    .width($('#cumulative-test').width())
    .height($('#cumulative-test').height())
       .color(d3.scale.category10().range());

    chart.xAxis
    .tickFormat(function(d) {
     return d3.time.format('%x')(new Date(d))
    });

    chart.yAxis.tickFormat(d3.format('d'));

    d3.select("#cumulative-test svg").datum(getData()).call(chart);

    nv.utils.windowResize(updateChart);

    function updateChart() {
     chart.width($("#cumulative-test svg").width())
     chart.height($("#cumulative-test svg").height());
     chart.update();
    }

    return chart;

    function getData() {
        return data;
    }

});

<link rel="stylesheet" src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.css" />

 <svg></svg>

Comment: Thank you for taking the time. Changing the "cumulativeLineChart" to "lineChart" finally solved the issue. I also changed the "values" array so it contains objects rather than arrays. Thank you for this hint.


Evaluate $\lim_{x\to0}\frac{1-\cos3x+\sin 3x}x$ without L'Hôpital's rule

Question: I've been trying to solve this question for hours. It asks to find the limit without L'Hôpital's rule.
$$\lim_{x\to0}\frac{1-\cos3x+\sin3x}x$$
Any tips or help would be much appreciated.
Comment: @GFauxPas What proof of LHR do you have in mind which would make using it here *circular*?
Comment: Are you familiar with derivatives yet?
Comment: Can you use the Taylor expansions of $\cos, \sin$?
Comment: Comment: You shouldn't use LHR as it would be *circular* here, do you see why?
Comment: What's with the *italics*?
Comment: Because the limit is of the form $\frac {f(x)-f(0)}{x-0}$
Answer: Do you know how to do without L'Hôpital's rule
$$
\lim_{x\to 0}\frac{\sin x}{x}
\quad \text{
and   }\quad
\lim_{x\to 0}\frac{\cos x-1}{x}?
$$
Then try the "simpler" version of your problem:
$$
\lim_{x\to 0}\frac{\sin 3x}{x},
\qquad
\lim_{x\to 0}\frac{\cos 3x-1}{x}.
$$
Answer: If you are given that $\lim_{x \to 0}{\sin x \over x } = 1$, then
since $1-\cos (3x) = 2 \sin^2 ({3 \over 2} x)$ (half angle formula), we have
\begin{eqnarray}
{1 -\cos (3x) +\sin (3x) \over x } &=& {2 \sin^2 ({3 \over 2} x) \over x} +{\sin (3x) \over 3x} {3x \over x} \\
&=& 2 ({\sin ({3 \over 2} x)  \over {3 \over 2} x})^2  { ({3 \over 2} x)^2 \over x} + 3 {\sin (3x) \over 3x} \\
&=& {9 \over 2} x ({\sin ({3 \over 2} x)  \over {3 \over 2} x})^2 + 3 {\sin (3x) \over 3x}
\end{eqnarray}
Taking limits gives $3$.
Answer: Since $\lim_{x\to 0}\frac{\sin x}{x}=1$ it follows that $\lim_{x\to 0}\frac{\sin(3x)}{x}=3$.
On the other hand, since
$$ 1-\cos(3x) = 2\sin^2\left(\frac{3x}{2}\right) $$
it follows that $\lim_{x\to 0}\frac{1-\cos(3x)}{x}=0$. It should not be difficult to finish from here.
Comment: As an alternative to the double angle formula, one could multiply the numerator and denominator by of the cosine limit by $1+\cos(3x)$ because then you can use that $1-\cos^2(3x)=\sin^2(3x)$.
Answer: If I write it in this form, does it look familiar ?
$$\lim_{x\to 0} \frac{[-\cos(3x) + \sin(3x)] - (-1)}{x - 0}$$
$$\lim_{x\to 0} \frac{[-\cos(3x) + \sin(3x)] - [-cos(0) + sin(0)]}{x - 0}$$
Answer: Taylor expansion is always a good solution since the method will provide the limit and more.
Remembering that $$\cos(t)=1-\frac{t^2}{2}+O\left(t^4\right)$$ $$\sin(t)=t-\frac{t^3}{6}+O\left(t^4\right)$$ replace $t$ by $3x$ to get $$1-\cos (3 x)+\sin (3 x)=1-\left(1-\frac{9 x^2}{2}+O\left(x^4\right) \right) +\left( 3 x-\frac{9 x^3}{2}+O\left(x^4\right)\right)$$ $$1-\cos (3 x)+\sin (3 x)=3 x+\frac{9 x^2}{2}-\frac{9 x^3}{2}+O\left(x^4\right)=3 x+\frac{9 x^2}{2}+O\left(x^3\right)$$ $$\frac{1-\cos (3 x)+\sin (3 x) }x=3+\frac{9 x}{2}+O\left(x^2\right)$$ which shows the limit and how it is approached.
Answer: Here is a similar approach also relying on the standard table limit $\lim\limits_{x\to 0}\frac{\sin x}{x}=1$:
$\lim\limits_{x\to 0}\frac{1-\cos(3x)+\sin(3x)}{x}=\lim\limits_{x\to 0}\frac{\frac{(1+\sin(3x))^2-\cos^2(3x)}{x}}{1+\sin(3x)+\cos(3x)}=\lim\limits_{x\to 0}\frac{2\cdot\frac{\sin (3x)}{x}(1+\sin(3x))}{1+\sin(3x)+\cos(3x)}=3$