Spring Framework em projeto modular pelo Apache Maven

Question: Eu criei um projeto web modular utilizando o Apache Maven com a seguinte estrutura:
proj-build
|--- proj-utils
|--- proj-persistence
|--- proj-services
|--- proj-web
`--- proj-ear

Descrição
proj-build: Este agrupa os módulos somente para a realização da build em cadeia nos módulos, isto é, cada projeto possui sua própria configuração quando é realizado o build, sem qualquer relacionamento com este projeto parent(proj-build).
proj-utils: Este módulo reúne classes utilitárias como: Classes Exceptions, Classes que configuram SessionFactory do Hibernate, etc..
proj-persistence: Este módulo reúne classes entidades, classes DAO, interfaces DAO. Possui dependências como JPA, Hibernate, etc..
proj-services: Este módulo reúne classes que implementam a lógica de negócio. Possui dependência do módulo proj-persistence.
proj-web: Este módulo reúne as classes Controllers, páginas HTML, CSS, Javascript e quaisquer outros recursos que necessitar nas páginas. Possui dependência com o módulo proj-services, Spring MVC, Spring Security, JSTL, Java Servlet, etc..
proj-ear: Este módulo tem dependência com todos os outros módulos exceto o proj-build. Este módulo empacota os outros módulos em um pacote EAR.
A minha dúvida é: Como eu aplico o Spring Framework DI/IoC como dependência neste projeto modular? Eu aplico a dependência em todos os módulos ou em algum módulo específico?
Answer: As configurações do Spring podem ser distribuídas pelos projetos, cada uma configurando os seus respectivos componentes. Isso garante a possibilidade de testes unitários em cada módulo.
Alguns módulos vão ter dependências. Por exemplo, o proj-services provavelmente vai precisar  do proj-persistence, certo? Nesse caso há duas saídas:
Import de configuração
A configuração de um projeto pode incluir a configuração de outro, simplesmente fazendo uma importação.
Imagine que você você tem um arquivo chamado spring-config-service.xml e esse projeto depende do utils e do persistence. Então na configuração deste projeto, faça assim:
<import resource="classpath:/spring-config-persistence.xml" />
<import resource="classpath:/spring-config-util.xml" />

Inclusão via anotação em testes unitários
Outra alternativa (até mais flexível) é incluir as configurações apenas nos testes unitários.
Exemplo:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:/spring-config-service.xml",
        "classpath:/spring-config-persistence.xml",
        "classpath:/spring-config-util.xml"})
@Configurable
public class UnitTests { ... }

No exemplo acima, pode-se ver que é possível acrescentar quantas configurações forem necessárias para inicializar o Spring no teste atual.
Isso é muito bom porque você poderia criar até configurações específicas para o teste, com mocks e tudo o que precisar, embora o mesmo pode ser alcançado usando profiles.
Nota importante
Nos dois casos de importação o projeto deve declarar devidamente suas dependências do Maven e os arquivos de configuração devem estar nos seus respectivos diretórios resource para que estejam disponíveis no classpath de teste.
Configuração da aplicação final
Finalmente, tratando-se de uma aplicação web que vai ser distribuída em um WAR, você pode definir todas as configurações que deverão ser carregadas com um parâmetro, assim:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-config-web.xml
        classpath:/spring-config-service.xml",
        classpath:/spring-config-persistence.xml",
        classpath:/spring-config-util.xml"})
    </param-value>
</context-param>

Nota: se as configurações estiverem empacotadas em arquivos Jar e o Spring reclamar que não acha, tente adicionar um asterisco (*) após o termo classpath na definição, como no seguinte abaixo.
classpath*:/spring-config-util.xml

Comment: Primeiramente obrigado por me responder. E só para esclarecer, no primeiro caso que é sobre o módulo `proj-services`, em que é utilizado os `imports` para que seja possível injetar os DAO's e classes utilitárias no módulo `proj-services` pelo que eu entendi. Já no ultimo caso, que é a configuração do arquivo `web.xml`, é referenciado todos os arquivos de configuração de cada módulo, que é por onde o container tomará toda a configuração para interagir com todos os módulos como um todo, pelo que eu entendi. Me corrija se eu entendi errado.
Comment: (OBS.: no comentário acima o container que estou querendo dizer é o container de DI/IoC do Spring) Mas no caso dos arquivos `pom.xml` de cada módulo, estes terão a dependência do artefato `spring-context` certo? Com exceção do módulo `proj-web`, no qual este terá a dependência do `spring-mvc`, que de forma transitiva terá o `spring-context`.
Comment: @klaytonbrito Quanto ao primeiro comentário. Se você usar o import em um arquivo não precisa declarar todos no `web.xml`. Quanto ao segundo, você pode declarar o `spring-context` em todos mesmo, inclusive no web. Não é boa prática depender diretamente de dependências não declaradas. Para evitar redundâncias, use um *parent pom* com uma seção `dependencyManagement` que declare todas as dependências do projeto.
Comment: Entendi. Sobre o _parent pom_ é bom reaproveitar o `proj-build`? Ou é melhor criar outro módulo para dependências? Uma outra coisa, eu criei um `context.xml` que contém a configuração de um DataSource JNDI para conexão com banco de dados e coloquei no `META-INF` do módulo `proj-web` para que possa ser utilizado pelo Spring Security, mas o `hibernate.cfg.xml` que está no `proj-persistence` vai precisar apontar para o Datasource JNDI do context.xml, se eu utilizar essa propriedade assim irá funcionar corretamente? `java:/comp/env/jdbc/projbanco`
Comment: O *parent pom* é melhor ser um projeto à parte, só para isso. Pelo menos para mim funciona melhor. Quanto ao *datasource* você pode configurar o Hibernate pelo Spring ([exemplo](http://www.baeldung.com/hibernate-4-spring)). Aí não repete a configuração.
Comment: Entendi, o link da configuração do Hibernate que você passou é bem interessante. Muito obrigado pela ajuda cara. Suas respostas me esclareceram muitas coisas e aprendi várias coisas novas.


Checking if a set is closed under modular multiplication

Question: I have to check if the set {1, 3, 7, 9, 11, 13, 17, 19} forms a group under multiplication modulo 20, and the only idea that I've had so far is: attempt brute force on all the elements (multiplying them all out and making a massive table), followed by induction on each element, to show that powers of each of them also belong to the set.
We've only started talking about groups and mod arithmetic last week, so I'm still trying to find my way around. I'm sure there's a better way to do this, and any advice would be much appreciated.
Answer: These are all the numbers between $0$ and $19$ which are relatively prime to $20$. It is almost obvious that the product of two numbers relatively prime to $m$ is itself relatively prime to $m$.
For a formal proof, let's concentrate on $m=20$. Suppose that $a$ and $b$ are relatively prime to $20$. We show that $ab$ must be relatively prime to $20$. For if it is not, then $ab$ is divisible by $2$ or by $5$ (or both). But if $ab$ is divisible by the prime $2$, then $a$ or $b$ must be. the argument for the prime $5$ is the same.
Comment: That makes a ton of sense. It seems like a proof of this shouldn't be too hard, but I've had to eat those very words too many times before, haha.

Thank you!
Comment: Also, would the same argument work for a smaller set of numbers that are relatively prime to 20, say, {1,3,7,9}?
Comment: It **need** not. The stressed fact that these are *all* the numbers (mod $20$) is what forces being closed under multiplication mod $20$. It *so happens* that the four numbers you mention are closed under multiplication mod $20$, but that is a more complicated fact.
Answer: The largest possible group of positive integers under multiplication modulo $n$ is that containing all of its units, i.e. all positive integers smaller than $n$ and relatively prime to it. In this case your set is exactly the one for 20.
Answer: HINT. Note that each of the numbers you have is relatively prime to $20$, and that the set contains all numbers between $1$ and $20$ that are relatively prime to $20$.
Comment: Thank you and @hwhm for your prompt responses!
Answer: In fact it is easy to check $\pm\{1, 3, 7, 9 \}$ is closed under multiplication and inversion, viz.
$$ 3\:\{3,7,9\}\equiv \{9,1,7\},\ \ \ 7\:\{7,9\}\equiv \{9,3\},\ \ \ 9\cdot 9\equiv 1 $$
Comment: Does this imply that the entire set is closed though? Wouldn't we have to prove (by induction maybe?) that, say, 3*(7^8) also belongs to the set? Or does this just follows from the property you've mentioned?

Thanks!
Comment: A subset S is closed under multiplication iff $\rm\:s\cdot t\in S\:$ for all $\rm\:s,t\in S$. The above includes all such products, except the trivial $\rm\:1\cdot n\equiv n$. It's equivalent to checking only the upper triangular part of the multiplication table for S (exploiting commutativity).
Comment: Super; this makes my life so much easier. Thank you!
Comment: @Chris Note that I've also exploited the *balanced* residue system $0, \pm1, \pm2,\ldots\:$ This halves work since we can ignore signs. Combined with the commutativity optimization, this reduces the number of products needing checking by roughly a factor of $4$. But, generally, the method using unit groups is better. My point was simply to point out that the brute force  approach is not as difficult as it may appear at first glance, if one does it smartly.
Comment: I understand now, thank you.


Como impedir que os elementos de uma div ultrapasse o pai?

Question: Ola, gostaria de que minhas divs laterais nao ultrapasse o pai. A quantidade de divs dependerá de quantas informações tiver no banco (se tiver 10 supermercados, por exemplo, aparecerá 10 divs)
div pai: divOptions
divs filhas: .eachOptions
HTML:

                                                        <input class="radioBTN" type="radio" name="radioButton"
                                                        id="radioBTN1">

Supermercado BigBom

R$ 10,85

                                                            <input class="radioBTN" type="radio" name="radioButton"
                                                            id="radioBTN2">

Supermercado Fonseca

R$ 11,43

                                                                <input class="radioBTN" type="radio" name="radioButton"
                                                                id="radioBTN3">

Supermercado Sempre Vale

R$ 12,30

                                                                    <input class="radioBTN" type="radio" name="radioButton"
                                                                    id="radioBTN4">

Supermercado Unifae

R$ 89,50

CSS PAI :
#divOptions {
background-color: #F5F5F5;
padding-left: 0;
padding-right: 0;
height: 400px;

}
CSS FILHO :
#modalProduto #allMarkets #options .eachOptions {
padding-left: 5px;
position: relative;
border: 2px solid red;

}
Comment: tente dar uma olhada no flexbox creio que ele vá te ajudar https://origamid.com/projetos/flexbox-guia-completo/
Answer: Acredito que se você colocar um

overflow-y: auto

na divOptions, resolverá o seu problema


Kubernetes cannot attach AWS EBS as volume. Probably due to cloud provider issue

Question: I hava a kubernetes cluster up running on AWS. Now when I'm trying to attach a AWS EBS as a volume to a pod, I got a "special device does not exist" problem.

Output: mount: special device /var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/vol-xxxxxxx does not exist

I did some research and found that the correct AWS EBS device path should be like this format:

/var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/aws/us-west-2a/vol-xxxxxxxx

My doubt is that it might because I set up the Kubernetes cluster according to this tutorial and did not set the cloud provider, and therefore the AWS device "does not exit". I wonder if my doubt is correct, and if yes, how to set the cloud provider after the cluster is already up running.
Comment: Can you specify what version you used? Also, was your AWS deployment made using kops?
Comment: See link to my resolution for kubeadm:
https://stackoverflow.com/a/60325491/10843666
Answer: You need to set the cloud provider to properly mount an EBS volume. To do that after the fact set --cloud-provider=aws in the following services:

controller-manager
apiserver
kubelet

Restart everything and try mounting again.
An example pod which mounts an EBS volume explicitly may look like this:
apiVersion: v1
kind: Pod
metadata:
  name: test-ebs
spec:
  containers:
  - image: gcr.io/google_containers/test-webserver
    name: test-container
    volumeMounts:
    - mountPath: /test-ebs
      name: test-volume
  volumes:
  - name: test-volume
    # This AWS EBS volume must already exist.
    awsElasticBlockStore:
      volumeID: <volume-id>
      fsType: ext4

Answer: The Kubernetes version is an important factor here. The EBS mounts was experimental in 1.2.x, I tried it then but without success. In the last releases I never tried it again but be sure to check your IAM roles on the k8s vm's to make sure they have the rights to provision EBS disks.


AngularJS login logout button need refresh to change

Question: Here is my index.html

<!DOCTYPE HTML>

    <title>Koupon - Index</title>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta name="keywords" content="Koupon HTML5 Template" />
    <meta name="description" content="Koupon - Premiun HTML5 Template for Coupons Website">
    <meta name="author" content="Dark Cyber" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/boostrap.css">
    <link rel="stylesheet" href="css/boostrap_responsive.css">

    <link rel="stylesheet" href="css/font_awesome.css">

    <link rel="stylesheet" href="css/styles.css">

    <link rel="stylesheet" href="css/mystyles.css">

Menu

Home

Layanan

Sewa Mobil

Shuttle

Paket Wisata

Blog

FAQ

Tertarik menjadi mitra kami?

Contact

Sign in

Sign out

Sign up

Member Login

Welcome back, friend. Login to get started

            <form class="dialog-form" ng-submit="handleLogin()" ng-controller="LoginController">
                Username
                <input type="text" placeholder="yourUsername" ng-model="login.username" class="span12">
                Password
                <input type="password" placeholder="My secret password" ng-model="login.password" class="span12">

                    <input type="checkbox">Remember me

                 {{ error }}

                <input type="submit" value="Sign in" class="btn btn-primary">
            </form>

Not member yet

Forgot password

Password Recovery

Fortgot your password? Don't worry we can deal with it

            <form class="dialog-form">
                E-mail
                <input type="text" placeholder="email@example.com" class="span12">
                <input type="submit" value="Request new password" class="btn btn-primary">
            </form>

Get it Anywhere

Ultrices varius semper laoreet molestie purus euismod fames odio volutpat eleifend turpis nec cras quam litora dignissim curae lacus platea sociis mauris hendrerit sed fringilla dignissim cum mi amet orci

Koupon on Twitter

Recent News

Gravida porttitor vulputate
05 August, 2013

Dignissim phasellus magnis mus duis nisl ut lacus vehicula velit

A duis
29 July, 2013

Class augue curae accumsan tempor semper id integer adipiscing mattis

About Koupon

Tellus auctor sem sociosqu cras cursus vitae erat aliquam adipiscing iaculis suscipit curabitur hac hac congue netus integer ridiculus volutpat varius suspendisse velit venenatis facilisi velit quis volutpat enim ipsum

Company

Home

Blog

Press

Jobs

Investors

For Business

Advertising

Runnig a Deal

Accept Payments

Referral Program

Developers/API

Merchant Terms

Get Help

FAQ

Customer Support

Return Policy

Terms Of Use

Privacy Statement

Keep in touch

Mauris mus tortor leo augue non sociosqu ridiculus sagittis odio

I define 2 LoginController in login dialog and login link
Here is my app.js

........
........

rentalkika.controller('LoginController', function ($rootScope, $scope, $http, $location, sessionService){
$scope.login = { username: "", password: "" };
if(sessionService.get('sessionToken') != null){
$scope.isLoggedIn = true;
}else {
$scope.isLoggedIn = false;
}

$scope.handleLogin = function () {

 //authService.login($scope);

 var configLogin = {
  params: {
   username: $scope.login.username,
   password: $scope.login.password
  },
  headers: {
   'X-Parse-Application-Id' : 'xxxx',
   'Content-Type' : 'application/x-www-form-urlencoded'

  }
 }

 $http.get('http://18.104.22.168:1337/parse/login', configLogin).then(function (response) {
  console.log(response.data);
  $.magnificPopup.close();
  sessionService.set('isLoggedIn', 'yes');
  sessionService.set('role', response.data.role_name);
  sessionService.set('sessionToken', response.data.sessionToken);
  $scope.isLoggedIn = true;
  $location.path('/dashboard');
 }, function (error){
  $scope.error = error.data.error;
 });

}

$scope.logout = function () {
 sessionService.destroy('isLoggedIn');
 sessionService.destroy('role');
 sessionService.destroy('sessionToken');
 $scope.isLoggedIn = false;

}

});

rentalkika.factory('sessionService', function () {

var sessionService = {};

sessionService.set = function (key, value) {
 return sessionStorage.setItem(key, value);
};

sessionService.get = function (key) {
 return sessionStorage.getItem(key);
};

sessionService.destroy = function (key) {
 return sessionStorage.removeItem(key);
};

return sessionService;

});

What I want is when I successfully submit login, the sign in button will change to sign out button, then vice versa when I successfully click sign out button.
My problem is the button sign in will change to sign out after I refresh browser.
Is something missing or wrong with my code?
Answer: You can Define both HTML elements and use angular ng-show to show each depending on the variable.For example hasNotsignedIn like this:
<input ng-show="hasNotsignedIn" type="submit" value="Sign in" class="btn btn-primary">

<input ng-show="!hasNotsignedIn" type="button" value="Sign out" class="btn btn-primary">

then Set the variable in the controller by default $scope.hasNotsignedIn=true;
When you post the form then $scope.hasNotsignedIn=false;
and  on click of sign out button set $scope.hasNotsignedIn=true;
Then do it like this
rentalkika.controller('LoginController', function ($rootScope, $scope, $http, $location, sessionService){
$scope.login = { username: "", password: "" };
$scope.hasNotsignedIn = true;  //Changeed
if(sessionService.get('sessionToken') != null){

}else {

}

$scope.handleLogin = function () {

    //authService.login($scope);

    var configLogin = {
        params: {
            username: $scope.login.username,
            password: $scope.login.password
        },
        headers: {
            'X-Parse-Application-Id' : 'xxxx',
            'Content-Type' : 'application/x-www-form-urlencoded'

        }
    }

    $http.get('http://184.108.40.206:1337/parse/login', configLogin).then(function (response) {

        $scope.hasNotsignedIn = false; //changed

        console.log(response.data);
        $.magnificPopup.close();
        sessionService.set('isLoggedIn', 'yes');
        sessionService.set('role', response.data.role_name);
        sessionService.set('sessionToken', response.data.sessionToken);
        $scope.isLoggedIn = true;
        $location.path('/dashboard');
    }, function (error){
        $scope.error = error.data.error;
    });

}

$scope.logout = function () {
    sessionService.destroy('isLoggedIn');
    sessionService.destroy('role');
    sessionService.destroy('sessionToken');
    $scope.hasNotsignedIn = true;  //changed

}

});

Comment: which controller? because I have `LoginNavController` and `LoginController` in sign in and sing out button in LoginNavController while login function in LoginController.
Comment: Let me show you in the edit but an gonna show you in the functions
Comment: Well in LoginController it would work there But according to your design YOu have two controllers for login and logout?
Comment: You just needed one controller called authentication to do that.The design is not good that is why you are facing such problems.
Comment: According to what I see there is no need for LoginNavController
Comment: Now You have to move the value from one controller to another which can be expensive for you
Comment: now I define `LoginController` twice in login form it self and login link. and doesn't work. would you like to correct my code?
Comment: Let me look att it


Where Xenakis used intersection?

Question: I understood intersection in Xenakis sieve theory, as he explained himself here. But can anyone provide me a musical example from its production where he effectively used this?
Comment: You might need to seek out someone who is very familiar with Xenakis's music. I looked through the pdf you linked and it's quite heady stuff and very specific to Xenakis himself (since he wrote it). Because of the difficulty and specificity, you'd more than likely need to find a scholar who really specializes in that music.
Answer: Although I can't trace a thread between sieve theory and Xenakis's own compositions, a generalization of it (weighted sieves: set-theoretic operations defined as in fuzzy set theory) is used effectively by Sever Tipei's 1980's compositions using his (Sever's) MP1 software.  An accessible composition and an accessible description(!) is Maiden Voyages.

Where Xenakis used intersection?


Problema no algoritmo sobre porcentagem

Question: eu tinha que fazer esse algoritmo :

Em 2010, uma pequena cidade brasileira tem 20.000 habitantes. A previsão
  do IBGE é que esta cidade cresça a uma taxa de 5% ao ano. Sabendo
  disso, faça um algoritmo que imprima na tela o ano e a população
  prevista para a cidade em tal ano, com o ano variando de 2011 até 2030.

utilizando a estrutura for
e eu fiz esse algoritmo:
float populacao;
int conta,taxa,total;

populacao=20.000;
taxa=1.05;
for (conta=2011;conta<=2030;conta++)
{
    total=populacao*taxa;
    populacao=total;

    printf("O ano de %d tera %f de habitantes \n",conta,populacao);
}

mas o resultado da populacao ta dando 20.000000pra todos os anos,oque ta errado?
Answer: Sua taxa e total estão definidas como int, mas ela é um float. Mude isso e seu algoritmo estará funcionando perfeitamente.
float populacao,taxa,total;
int conta;

populacao=20.000;
taxa=1.05;
for (conta=2011;conta<=2030;conta++)
{
    total=populacao*taxa;
    populacao=total;

    printf("O ano de %d tera %f de habitantes \n",conta,populacao);
}

Answer: #include <stdio.h>
int main(void)
{
    float populacao,taxa,total;
    int conta;

    populacao = 20.000;
    taxa = 0.05;
    for (conta=2011; conta<=2030; conta++)
    {
       total = populacao + (populacao * taxa);
       populacao = total;
       printf("O ano de %i tera %f de habitantes \n",conta,populacao);
    }
    return(0);
}

Problema no algoritmo sobre porcentagem


Loading and reusing content with jquery

Question: I am new to JQuery and need som direction.
I have created a page with a few buttons. When I click one of the buttons, new content is loaded and put in one div. The buttons stays visible at all time.
When I click the other button, some other content is loaded from the server and put in the same div after I have emptied it.
In one of the button's content I have a "slideshow". When I switched between the contents a few times the animation gets corrupted. I think the problem I'm having is that I reload the content each time and adds it again to the same div. This isn't a good way anyway, I should reuse the content in some way.
My question(s) is:

how do I load content from a server and store it in some way in the client
check if the content is loaded already
reuse the content next time it should be shown instead of loading it from the server once again
not overlapping the content in any way

My scripts:
 $(document).ready(function() {
            $("#section2").load("main_mid.php");
              $("#taylor_made").click(function () {
                $("#section2").empty();
                $("#section2").load("taylor_made.php");
                });

            $("#sm_tool").click(function () {
                $("#section2").empty();
                $("#section2").load("main_mid.php");
                });
         });

My buttons:

        <button id="sm_tool" class="big_buttons" type="button"></button>
        <button id="taylor_made" class="big_buttons" type="button"></button>

The area the content is added to:

In my example above, I simplified the world a bit. In pratice, there will be a few (10-15) buttons with different content associated. It may be a bit much to load all at once. I'm updating my question. It's actually a normal web page where the menu is built up with buttons and links.
Also to be noted, some of the pages contains images and some have some kind of dynamic content (e.g. the slide shows loads and starts the animation with scripts when the content has been loaded).
Thank's in advance!
Answer: Either use query's data api. http://api.jquery.com/jQuery.data/ or load the content into 2 separate divs and toggle them with .hide() .show()
var price_page = null;
$("#prices").click(function () {
    if(price_page==null){
        $("#section2").load("prices.php", function(data) {
            price_page = data;
            $("#section2").removeAttr("class").addClass("price_mid_area");
        });
    }else{
        $("#section2").html(price_page).removeAttr("class").addClass("price_mid_area");
    }
});

Comment: Thanks for your answer. According to the link you posted, this is not supported in IE: "Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties." How would I handle this in IE?
Comment: I guess you could just store it in a javascript variable.
Comment: I solved it using .load, storing the data in js vars. Also, in order to get the desired look for the different pages, I used .removClass and .addClass. Works like a charm. I post the code in my own answer to help others. Thank you!
Comment: I posted a slightly modified version of your code which should work better.
Comment: Thank you! Could you please explain what's the benfit of using your implementation!
Comment: in your code, `$("#section2").html(price_page);` gets run even if price_range is null. The .load() callback is run when the request is complete. Until that happens, the rest of the code keeps executing.
Answer: An easy way to accomplish your goal is to keep an invisible div that can store the content and just append to it. Or you can create a new invisible div with the content, then locate it later. For example you can do something like:

 $("#sm_tool").click(function () {

        //Check here if you need to do somewith with the existing content.
        $("#storagediv").load("main_mid.php");

                });

Answer: Store them in different hidden div's, and use hidden div's as source of your content. Check using if hidden divs has child elements (except text block)
Answer: you can use two different divs(one for taylor_made and other for sm_tool) instead of using only one. You can load them first time you click and can toggle between them from next time onwards.
Answer: Perhaps this would solve some of your issues:
Create two content divs, say "section2_sm_tool" and "section2_taylor_made", one of which is styled as "display:none".
In document ready, load both main_mid.php and taylor_made.php into their respective containers, as you are already doing for main_mid.php.
Then, on each button click, instead of re-loading the content you simply .hide() one div and .show() the other.
This approach assumes the content does not change while the user is clicking the two buttons.
Comment: Ok, i simplified the world a bit in my example. In pratice, there will be quite a few (10-15) buttons with different content associated. It may be a bit much to load all at once. I'm updating my question.
Comment: In that case, maybe section2 could be an iframe and not a div. Each button could then in turn set the src attribute of the iframe.
Comment: Isn't the content loaded each time if I do like that? Is it cashed just like a normal web page, depending on browser configuration of course?
Comment: You are correct; the content will be loaded each time you change the .src attribute of the iframe subject to all the normal caching mechanisms.
Answer: This is how I solve it with help from ilia choly:
var price_page;
$("#prices").click(function () {
                if(price_page==null){
                    $("#section2").load("prices.php", function(data) {
                        price_page = data;
                    });
                }

                $("#section2").removeClass();
                $("#section2").addClass("price_mid_area");
                $("#section2").empty();
                $("#section2").html(price_page);

            });

prices is the ID of a button.
Using the .removeClass and .addClass, I can change the css-attributes for the different pages as well.

Loading and reusing content with jquery


understanding the matrix transpose

Question: Can you explain me, please, what does it mean the transpose of a matrix ? I know the definition in the context of matrix theory and its generalization to adjoint operators (transpose of a linear application).
What is the fundamental idea behind transpose ?
and why it is introduced and considered in today's mathematics ?
Thank you
Comment: The reason is here, http://en.wikipedia.org/wiki/Dual_space
is advance linear-algebra.
Answer: I'll try to explain some of the History, which is unusual because it started at the highest level of abstraction and worked its way down.
The study of symmetric differential operators predates the systematic study of symmetric matrices. While studying differential operators such as
$$
                 Lf = -\frac{d}{dx}p\frac{d}{dx}f + V f
$$
on an interval $[a,b]$ with two endpoint conditions such as (a) $f(a)=f(b)=0$ or (b) $f(a)=f(g)$, $f'(a)=f'(b)$, it was found that
$$
                \int_{a}^{b} (Lf)g\,dx = \int_{a}^{b}f(Lg)\,dx,
$$
provided $f$, $g$ satisfy the endpoint conditions. And it was this property that was isolated as the reason for the integral 'orthogonality' of eigenfunction solutions of $Lf=\lambda f$. For example, the classical Fourier series functions are eigenfunctions of $L=-\frac{d^{2}}{dx^{2}}$ with periodic endpoint conditions on $[0,2\pi]$:
$$
     1,\cos x,\sin x,\cos 2x,\sin 2x,\cos 3x,\sin 3x,\cdots\;.
$$
This is an infinite-dimensional space of functions with infinitely many eigenvalues $0,1^{2}, 2^{2}, 3^{2},\cdots$.
If you take any two of these which are different--call them $f$ and $g$--then $\int_{0}^{2\pi}fg\,dx=0$. And this happens for a broad class of eigenfunction solutions associated with such an operator $L$, including Bessel functions, Legendre Polynomials, Hermite Polynomials, etc..
The study of eigenfunction solutions came out of Fourier's separation of variables technique from ~1805. The trick they found to finally explain the general orthogonality of solutions of these ODEs was this: If $Lf=\lambda f$ and $Lg=\mu g$ with $\mu \ne \lambda$, then
$$
          (\lambda-\mu)(f,g) = (Lf,g)-(f,Lg) = 0.
$$
This abstract pairing eventually became a general inner product $(\cdot,\cdot)$ as shown above, and symmetric operators became a focus because of the properties similar to Fourier series expansion in orthogonal functions $1,\cos x,\sin x,\cos 2x,\sin 2x,\cdots$ on $[0,2\pi]$.
In the context of matrices, a matrix $A$ which is equal to its transpose is the natural symmetric operator, because
$$
                    y^{T}(Ax) = (A^{T}y)x.
$$
Written as an inner product $(x,y) = y^{T}x$, this becomes $(Ax,y)=(x,A^{T}y)$. So symmetry in this context is $A=A^{T}$, which is the same as symmetry across the diagonal. Like a symmetric differential operator, a symmetric matrix also has a basis of eigenfunctions which are mutually orthogonal for different eigenvalues; this is easily shown using the same trick used to show orthogonality for eigenfunction solutions of symmetric ODEs coming from separation of variables--same notation, just different objects.
One of the reasons this seems so foreign at the level of matrices is that it's coming from a much more abstract infinite-dimensional setting where symmetry arises naturally in the study of differential equations of Physics and Engineering. But because of this natural connection, there are many applications of symmetric matrix theory as well.

understanding the matrix transpose


E possível eu gravar uma informação usando user.uid de um no firebase?

Question: Não tenho conhecimento sobre a área, então no momento possuo muitas dúvidas e uma delas é essa:
Possuo um script que a proposta e pegar o user.uid quando ele estiver logado atravez de email e senha do firebase auth e pelo use.uid fazer a gravação do troco no firebase, a estrutura de onde ele deveria ser gravado e a seguinte users --> user.uid que no banco fica assim: cB9r9Y4zQcZ81cKqPGroA3HDVqi1 --> address ---> troco porém com as tentativas de amador não to conseguindo fazer essa gravação, minha tentativa foi a seguinte:

// Initialize Firebase (ADD YOUR OWN DATA)
var config = {
  apiKey: "xxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxxxxx",
  databaseURL: "xxxxxxxxxxxxx",
  projectId: "xxxxxxxxxxx",
  storageBucket: "xxxxxxxx",
  messagingSenderId: "xxxxxxxxxxxx"
};
firebase.initializeApp(config);

// Reference messages collection
var messagesRef = firebase.database().ref('users').child(user.uid).child('address');
// Listen for form submit
document.getElementById('trocoForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
  e.preventDefault();
  // Get values
  var troco = getInputVal('troco');
  // Save message
  saveTroco(troco);
  // Show alert
  // por alert aqui
  // Clear form
  document.getElementById('trocoForm').reset();
}
// Function to get get form values
function getInputVal(id) {
  return document.getElementById(id).value;
}
// Save message to firebase
function saveTroco(troco) {
  var newTrocoRef = messagesRef.push();
  newTrocoRef.set({
    troco_id: troco,
  });
}

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    var user = firebase.auth().currentUser;

    if (user != null) {
      user.providerData.forEach(function(profile) {
        console.log("Sign-in provider: " + profile.providerId);
        console.log("  UID: " + user.uid);
        console.log("  Name: " + profile.displayName);
        console.log("  Email: " + profile.email);
      });
    }
    // User is signed in.
  } else {
    // No user is signed in.
  }
});
<form id="trocoForm">

    Informe seu troco
    <input type="tel" pattern="([0-9]{1,3}\.)?[0-9]{1,3},[0-9]{2}$" maxlength="15" name="troco" id="troco"></input>

    <button type="submit">Submit</button>

 Exemplo 50,00
</form>

loguei em usuário e rodei um script para ver se conseguia recuperar o user.uid e consegui mas não consigo fazer a gravação por ele, o script usado foi:
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
      var user = firebase.auth().currentUser;

if (user != null) {
  user.providerData.forEach(function (profile) {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  UID: " + user.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
  });
}
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Answer: Tava faltando apenas isso para o projeto dar certo:
if (user) {
    uid=user.uid;
  }
});

e editar a linha:
var messagesRef = firebase.database().ref('users').child(user.uid).child('address');

Para:
var messagesRef = firebase.database().ref('users').child(uid);

E o código ficou assim:
// Initialize Firebase (ADD YOUR OWN DATA)
var config = {
  apiKey: "xxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxxxxxxxxxxxxx",
  databaseURL: "xxxxxxxxxxxxxxxxxxxxx",
  projectId: "xxxxxxxxxxxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxxxxxxxxx",
  messagingSenderId: "xxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    uid=user.uid;
    // Reference messages collection
    var messagesRef = firebase.database().ref('users').child(uid);
    // Listen for form submit
    document.getElementById('trocoForm').addEventListener('submit', submitForm);
    // Submit form
    function submitForm(e){
      e.preventDefault();
      // Get values
      var troco = getInputVal('troco');
      // Save message
      saveTroco(troco);
      // Show alert
      // por alert aqui
      // Clear form
      document.getElementById('trocoForm').reset();
    }
    // Function to get get form values
    function getInputVal(id){
      return document.getElementById(id).value;
    }
    // Save message to firebase
    function saveTroco(troco){
      var newTrocoRef = messagesRef.push();
      newTrocoRef.set({
        troco_id: troco,
      });
    }
  }
});

Tava faltando eu deixar claro para o código quem era o uid.


Developments in musical form in mid-nineteenth - early-twentieth century music

Question: I am now studying new approaches to harmony in the Romantic and Impressionistic eras, but I haven't seen anything about formal functions.
It seems like even if they were still using Sonata form (which based on my basic study of Debussy, doesn't seem the case at least by the early 20th century), the definition of a sonata would have to be fundamentally changed to fit the sort of harmonic innovations that were happening.
What are some approaches to analyzing particularly form of the late Romantic/Impressionistic eras? (I don't know if I'm allowed to say this, but recommendations for relevant resources would be appreciated as well as answers).
Answer: Actually, the standard forms from the Classical tradition are still largely in play in the mid-nineteenth and into the twentieth century.
Seth Monahan recently published a very well-received book, Mahler's Symphonic Sonatas, that shows how Mahler used the tradition of sonata form in order to create narratives within his works. Sure, these sonata structures are different than you'd find in Haydn or Mozart, including regarding the harmonic innovations that you referenced; but the sonata process is still evident.
We see composers like Richard Strauss writing tone poems in rondo form, and all kinds of composers were writing character pieces in the traditional ternary form.
Keep in mind that some forms only appear in certain places; sonata forms aren't going to occur everywhere, but typically just in their traditional spots of first (and sometimes final) movements of larger works. You'll find sonata forms in instrumental sonatas from Fauré, Berg, Saint-Saëns, Debussy, Schoenberg, Franck, Respighi, Ravel, etc.
Along with Monahan's book, I strongly recommend finding a copy of Richard Strauss: New Perspectives on the Composer and His Work; James Hepokoski's "Strauss's Don Juan Revisited" is required reading for anyone interested in form in this repertoire!
Comment: Since you bring up Hepokiski, I would also recommend his little book entirely about Sibelius' 5th symphony. A phenomenal example of the way that traditional forms were being shifted and abstracted by late 19th, early 20th century composers.
Comment: @PatMuchmore Great point; it's an overlooked book, only because his other work is so seminal.
Comment: Really opened my ears to the revolutionary side of Sibelius. I'd always liked his work, but thought of it as more retrograde than I do now.


Removing Activity from BackStack (Flag_Activity_no_history) does not work

Question: I've a Start button in my MainActivity. If I click on this button I go to the next Activity (InfoActivity). Now, I want to remove the MainActivity from the BackStack, if I click on the button. I've tried this:
View.OnClickListener startButtonListener = new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, InfoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
    }
};

But that removes not the MainActivity from the BackStack, it removes the InfoActivity from the BackStack.
I know that I could insert the flag into the AndroidManifest. But that is not possible for me, because if I go to the PreferencesActivity from the MainActivity and I using the flag in the AndroidManifest, the MainActivity is removed if I return from the PreferencesActivity back to the MainActivity.
So I want to remove the MainActivity from the BackStack, if I click on the button Start.
Answer: Add finish();
Like this :
View.OnClickListener startButtonListener = new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, InfoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        this.finish();
    }
};

Answer: As said you should use Intent.FLAG_ACTIVITY_NO_HISTORY on the activity you dont want to track in your case on MainActivity.
Other way to do it is Intent.FLAG_ACTIVITY_CLEAR_TOP on your Info activity this will clear whole history (even things before MainActivity)


How can you prepopulate a field based on another field's value?

Question: this one was easy in Drupal 7. I defined a condition "If field A has value B, then field X will automatically get value Y".
How can I get this working for a Drupal 8 webform?
Comment: I'm voting to close this question as off-topic because it's a support request for a third-party module hosted on drupal.org where this should be added as an issue. You also find the requested information in this screencast: https://www.youtube.com/watch?v=ic4wu-iZd4Y
Comment: OK. The screencast does not answer my question.
Comment: agree with Bert. that screencast is only covering how to make fields Visible if a specific option in a prior Element is chosen. it is not any help for how to set the value for the conditional Element
Answer: FYI, the module maintainer will send you here if you enter a support question - he will not answer it in the issue queue.


SSRS Subscriptions - Email to variable email address

Question: I'm fairly new to SSRS and I've been assigned to create a subscription. I understand how they are created, but I'd like to have the address field be a variable, versus hard-coding the addresses.
So basically in my report, I generate a list of help desk items to be assigned. Few fields include date, assigned technician, and technician's email address.  I would like to set up the subscription so that if a help desk item is assigned to that technician, email just those individuals (get the email from the dataset and place it in the subscription email address box. Is this possible?
Is there going to be programming involved? I do have some knowledge of ASP.NET/VB.Net; currently using 2010 Ultimate for developing and Visual Studios 2008 for SSRS.
Thanks for any help.
K~ru
Answer: Sounds like a Data-Driven Subscription
One of the things it allows you to do is provide a dataset as the list of email address to be sent to, so for UserA is runs for and sends them an email (granted their email is in the database) and then same thing for UserN and so on.


Creating an adjacency matrix and its notation?

Question: Lets say I divide an image up into small squares (100 in total). I pick say 20 squares at random, and each is denoted by, $\text{Z}$. So the first square is $\text{Z}_{\text{1}}$, the second is $\text{Z}_{\text{2}}$ and so fourth. I want to see if their boundaries $\mathcal{B}$ intersect, i.e. if the squares happen to be directly next to each other on the image.
I created an adjacency matrix:
\begin{equation}
A_{\text{i,j}}=\left\{
\begin{alignedat}{3}
1,&\quad \text{if} \quad \text{i}\neq\text{j}\enspace\text{and}\enspace\exists\mathcal{B}:  \mathcal{B}\in\text{Z}_{\text{i}}\cap\text{Z}_{\text{j}}\\
0,&\quad \text{if} \quad \text{i}=\text{j} \\
0,&\quad \text{otherwise}
\end{alignedat}\,
\right\}
\end{equation}
1) How do I remove the right curly bracket?
2) Does the condition, $\exists\mathcal{B}: \mathcal{B}\in\text{Z}_{\text{i}}\cap\text{Z}_{\text{j}}$, make sense or is there a better way to write it?
Answer: 1) To remove the curly bracket you can use \right. instead of \right\}.
2) The conditions makes sense.  You could write $Z_i \cap Z_j \neq \emptyset$ to be slightly more succinct.  Or even just use words to be more plain:

Set $A_{i,j} = 1$ if $Z_i$ and $Z_j$ are adjacent (and not equal), otherwise $0$.
Comment: Does the $\neq 0$ mean the union of the set is not empty?
Comment: It means the intersection is not empty.
Comment: ok thanks. I have written the condition as $\exists\mathcal{B}: \text{Z}_{\text{i}}\cap\text{Z}_{\text{j}}\neq0$ and also explained in the text the meaning in words for completeness. Thanks for your swift reponse.
Comment: Well, the condition you have written in the comment looks strange.  If $\exists B B \in Z_i \cap Z_j$ then you know $Z_i \cap Z_j \neq \emptyset$.  The two statements are equivalent.  By the way, note the difference between $0$ (a number) and $\emptyset$ (a set).
Comment: Yes, I had just edited my comment upon looking back on it just before you replied.

Thank you for bringing to my attention to the symbol, $\emptyset$. I think I will use the original condition from my OP, simply because its easier for me and my readers (from a physics/Eng background) to understand. Thanks once again.
Comment: Thinking about this, it may be confusing to say $Z_i \cap Z_j \neq \emptyset$ (or $\exists B\, B \in Z_i \cap Z_j$).  In the context of image processing, a square is probably thought of as a collection of pixels, not an ideal square from geometry.  So two adjacent squares would not have any pixels in common.  You could just say $A_{i,j} = 1$ if $Z_i$ and $Z_j$ touch (either on a side or a corner.)
Comment: Aside: A common mistake of authors writing math is to think that it's not formal unless it is written in mathematical notation.  For a simple definition the English language is often easier to understand.  With that I will leave it to you...
Comment: Hi, my application is not actually squares but shapes of arbitrary shapes. I will think of using english to write that condition instead. I do think you are right, its probably going to be clearest writing plain english
Answer: I didnt understood your first question so i will directly answer the second one. The condition makes sense as long as you can compute the adjency matrix A and it should ne written as :
Given x a vector where x_i=1 if the square i is chosen, 0 otherwise. Hence x contains 20 composants equal to 1 and 80 equal to zero. You compute the product Ax  ans see it the resulting vector is null. If it is the case, there is no intersection, if not there must be some squares with common boundery.


How to add html inside an if else statement in php?

Question: I have this code where if something then display a link, else display another link. the if and else are php code, and the links are html as you will know, but I was wondering how do you make it so it will not give me any errors, how do I combine php with html?
  <?php foreach ($user_socs as $user_soc) {
  if ($soca == $user_soc) {

  Leave Society;

  } else {
  Join Society;

  }

Comment: seems like a duplicate:  http://stackoverflow.com/questions/722379/can-html-be-embedded-inside-php-if-statement
Comment: ``html logic``html logic``
Comment: This tutorial might help: http://php.net/manual/en/tutorial.firstpage.php
Answer: This might help you. This one is from the basics of PHP:
<?php foreach ($user_socs as $user_soc) {
     if ($soca == $user_soc) {
         echo "Leave Society";
     } else {
         echo "Join Society";
     }
}
?>

Answer: Remember PHP should be surrounded by <?php ?>. Simply end the "PHP part" and then start it again when you finished your HTML.
      <?php foreach ($user_socs as $user_soc) {

      if ($soca == $user_soc) {

      ?> Leave Society <?

      } else {
      ?> Join Society<?

      }

Also, you can write HTML in echo statement, but you should escape some special characters like " to not interfere with the php code itself.
      <?php foreach ($user_socs as $user_soc) {

      if ($soca == $user_soc) {

      echo "Leave Society";

      } else {
      echo "Join Society";

      }

See http://php.net/manual/en/function.echo.php to more information.
Answer: Try this
<?php foreach ($user_socs as $user_soc) {
      if ($soca == $user_soc) { ?>

      Leave Society;

 <?php          } else { ?>
      Join Society;

      <?php }

Answer: Use alternate syntax:
<?php
      $aUserSocs = array( 'link1', 'link2', 'link3' );
      $soca = 'link2';
      $iCountUserSocs = count( $aUserSocs );
      for( $i = 0; $i < $iCountUserSocs; ++$i ):
?>
        <?php if( $soca == $aUserSocs[ $i ] ): ?>
            Leave Society;
        <?php else: ?>
            Join Society;
        <?php endif; ?>
    <?php endfor; ?>

Comment: Alternate syntax requires closures for loops and conditionals. Else and elseifs can be placed inside if statements so long as they use :


Sincronizar 3 Select com Loading + JQuery/ Ajax

Question: Olá, boa dia.
estou com meu aplicativo aqui na seguinte questão.
tenho a página index.html,
nessa página eu tenho uma
 para que seja apresentado o loading conforme o código abaixo:

 Carregando...

Agora eu tenho o arquivo.js
 function onCarregaFunVeiEqu () {

    $.ajax({
        url: ''''''''getFun.php'''''''',
        type: ''''''''get'''''''',
        async: false,
        beforeSend: function(){
            $("#loader").show();
            $("#loader").css({display:"block"});
        },
        success: function(response){
            var obj = JSON.parse(response);
                obj.forEach(function (o, index) {
                    onSincFun(o.cdfun, o.nmfun, o.nusen, o.nmatri);
                });

            $.ajax({
                url: ''''''''getVei.php'''''''',
                type: ''''''''get'''''''',
                async: false,
                success: function(response){
                    var obj = JSON.parse(response);
                        obj.forEach(function (o, index) {
                        onSincVei(o.cdve, o.nuplaca, o.detip, o.demdl);
                    });

                    $.ajax({
                        url: ''''''''getEquipe.php'''''''',
                        type: ''''''''get'''''''',
                        async: false,
                        success: function(response){
                            DeleteEqu();
                            var obj = JSON.parse(response);
                                obj.forEach(function (o, index) {
                                    onSincEqu(o.cdequ, o.deequ, o.dearea, o.nmobra);
                                });
                        }
                    });
                }

            });
        },
        complete: function(data){
            //$("#loader").hide();

        }
    }).always (function() {
        $("#loader").show();
        $("#loader").css({display:"block"});
    }).done (function() {
        $("#loader").hide();
        $("#loader").css({display:"none"});
    });

}

o que acontece é :
o Loading.. ele aparce, porém já some...
e enquanto isso ele tá sincronizando..
ou seja ele tinha que sincronizar TUDO para depois desaparecer o Loading...
alguém tem uma sugestão?
Answer: O problema é que você colocou as condições de hide ao final da primeira requisição ajax, e são 3
Tente isso:
function onCarregaFunVeiEqu () {

$.ajax({
    url: ''''''''getFun.php'''''''',
    type: ''''''''get'''''''',
    async: false,
    beforeSend: function(){
        $("#loader").show();
        $("#loader").css({display:"block"});
    },
    success: function(response){
        var obj = JSON.parse(response);
            obj.forEach(function (o, index) {
                onSincFun(o.cdfun, o.nmfun, o.nusen, o.nmatri);
            });

        $.ajax({
            url: ''''''''getVei.php'''''''',
            type: ''''''''get'''''''',
            async: false,
            success: function(response){
                var obj = JSON.parse(response);
                    obj.forEach(function (o, index) {
                    onSincVei(o.cdve, o.nuplaca, o.detip, o.demdl);
                });

                $.ajax({
                    url: ''''''''getEquipe.php'''''''',
                    type: ''''''''get'''''''',
                    async: false,
                    success: function(response){
                        DeleteEqu();
                        var obj = JSON.parse(response);
                            obj.forEach(function (o, index) {
                                onSincEqu(o.cdequ, o.deequ, o.dearea, o.nmobra);
                            });
                    }
                }).done (function() {
                   $("#loader").hide();
                   $("#loader").css({display:"none"});
                });
            }

        });
    },
    complete: function(data){
        //$("#loader").hide();

    }
    }).always (function() {
        $("#loader").show();
        $("#loader").css({display:"block"});
    }).done (function() {
        //$("#loader").hide();
        //$("#loader").css({display:"none"});
    });

Eu comentei o código que esconde a div de loading, e coloquei ela no final da ultima requisição sua.
o .done() executa no fim da requisição
e $("#loader").hide(); esconde o loader
Comment: como eu posso fazer para que o "Loading" fique visível até o final ?

Já fiz ele separado...
Tinha criado 3 function.. com sync = False;
também não deu certo.

Depois eu fiz 3 function com sync = True;
também não deu muito certo.

mais pelo que eu sei não é muito bom deixar o sync = false.
pois pode "congelar" a tela do usuário.
Comment: parece que deu certo!

Obrigado, faltou atenção rsrs...
Estava batendo cabeça faz uns 3 dias...

já aproveitando o gancho.
tem alguma coisa aqui fórum ou exemplo...

eu não sei o nome,
de ficar a tela toda "travada/ embaçada" e o loading carregando ...


OpenJDK font dependencies

Question: I compiled OpenJDK in Ubuntu and dropped the JRE package in our embedded system (Flavour of linux). OpenJDK does not have redistributable fonts. I dropped dejavu fonts in jre/lib/fonts directory.
My application works fine if i copy Lucida fonts (which is distributed with Sun/Oracle JRE), to jre/lib/fonts.
Please let me know the steps to use Dejavu fonts with openjdk,
Comment: I think this answer can be useful with understanding this issue : https://stackoverflow.com/a/43610853/2957102
Answer: Check <code>/etc/java-6-openjdk/fontconfig.properties</code> - it should specify fonts for OpenJDK.
You don't say what Linux flavour is on the embedded system, but if it has a package management system, try installing DeJaVu via that.
For reference, my fontconfig.properties looks like this:
<code>#
# Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.  Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#

# Version

# Uses Ubuntu 8.04 (hardy), Debian 6.0 (Squeeze) (and more recent releases)
# fonts and file paths.
version=1

# Component Font Mappings

# Chinese fonts
allfonts.umingcn=AR PL UMing CN
#allfonts.umingcn.motif=AR PL UMing CN
allfonts.uminghk=AR PL UMing HK
#allfonts.uminghk.motif=AR PL UMing HK
allfonts.umingtw=AR PL UMing TW
#allfonts.umingtw.motif=AR PL UMing TW
allfonts.wqy-microhei=WenQuanYi Micro Hei
allfonts.wqy-zenhei=WenQuanYi Zen Hei
#allfonts.wqy-zenhei.motif=WenQuanYi Zen Hei
allfonts.shanheisun=AR PL ShanHeiSun Uni
#allfonts.shanheisun.motif=AR PL ShanHeiSun Uni

# Indic scripts
allfonts.bengali=Lohit Bengali
allfonts.gujarati=Lohit Gujarati
allfonts.hindi=Lohit Hindi
#allfonts.malayalam=Lohit Malayalam
allfonts.oriya=Lohit Oriya
allfonts.punjabi=Lohit Punjabi
allfonts.tamil=Lohit Tamil
allfonts.telugu=Lohit Telugu
allfonts.sinhala=LKLUG

serif.plain.latin-1=DejaVu Serif
#serif.plain.latin-1.motif=LuxiSerif-Regular
serif.plain.japanese-kochi=Kochi Mincho
serif.plain.japanese-sazanami=Sazanami Mincho
serif.plain.japanese-vlgothic=Sazanami Mincho
serif.plain.korean-baekmuk=Baekmuk Batang
#serif.plain.korean-baekmuk.motif=Baekmuk Batang
serif.plain.korean-un=UnBatang
#serif.plain.korean-un.motif=UnBatang

serif.bold.latin-1=DejaVu Serif Bold
#serif.bold.latin-1.motif=LuxiSerif-Bold
serif.bold.japanese-kochi=Kochi Mincho
serif.bold.japanese-sazanami=Sazanami Mincho
serif.bold.japanese-vlgothic=Sazanami Mincho
serif.bold.korean-baekmuk=Baekmuk Batang
#serif.bold.korean-baekmuk.motif=Baekmuk Batang
serif.bold.korean-un=UnBatang Bold
#serif.bold.korean-un.motif=UnBatang Bold

serif.italic.latin-1=DejaVu Serif Oblique
#serif.italic.latin-1.motif=LuxiSerif-Oblique
serif.italic.japanese-kochi=Kochi Mincho
serif.italic.japanese-sazanami=Sazanami Mincho
serif.italic.japanese-vlgothic=Sazanami Mincho
serif.italic.korean-baekmuk=Baekmuk Batang
#serif.italic.korean-baekmuk.motif=Baekmuk Batang
serif.italic.korean-un=UnBatang
#serif.italic.korean-un.motif=UnBatang

serif.bolditalic.latin-1=DejaVu Serif Bold Oblique
#serif.bolditalic.latin-1.motif=LuxiSerif-BoldOblique
serif.bolditalic.japanese-kochi=Kochi Mincho
serif.bolditalic.japanese-sazanami=Sazanami Mincho
serif.bolditalic.japanese-vlgothic=Sazanami Mincho
serif.bolditalic.korean-baekmuk=Baekmuk Batang
#serif.bolditalic.korean-baekmuk.motif=Baekmuk Batang
serif.bolditalic.korean-un=UnBatang Bold
#serif.bolditalic.korean-un.motif=UnBatang Bold

sansserif.plain.latin-1=DejaVu Sans
#sansserif.plain.latin-1.motif=LuxiSans-Regular
sansserif.plain.japanese-kochi=Kochi Gothic
sansserif.plain.japanese-sazanami=Sazanami Gothic
sansserif.plain.japanese-vlgothic=VL PGothic
sansserif.plain.korean-baekmuk=Baekmuk Gulim
#sansserif.plain.korean-baekmuk.motif=Baekmuk Gulim
sansserif.plain.korean-un=UnDotum
#sansserif.plain.korean-un.motif=UnDotum

sansserif.bold.latin-1=DejaVu Sans Bold
#sansserif.bold.latin-1.motif=LuxiSans-Bold
sansserif.bold.japanese-kochi=Kochi Gothic
sansserif.bold.japanese-sazanami=Sazanami Gothic
sansserif.bold.japanese-vlgothic=VL PGothic
sansserif.bold.korean-baekmuk=Baekmuk Gulim
#sansserif.bold.korean-baekmuk.motif=Baekmuk Gulim
sansserif.bold.korean-un=UnDotum Bold
#sansserif.bold.korean-un.motif=UnDotum Bold

sansserif.italic.latin-1=DejaVu Sans Oblique
#sansserif.italic.latin-1.motif=LuxiSans-Oblique
sansserif.italic.japanese-kochi=Kochi Gothic
sansserif.italic.japanese-sazanami=Sazanami Gothic
sansserif.italic.japanese-vlgothic=VL PGothic
sansserif.italic.korean-baekmuk=Baekmuk Gulim
#sansserif.italic.korean-baekmuk.motif=Baekmuk Gulim
sansserif.italic.korean-un=UnDotum
#sansserif.italic.korean-un.motif=UnDotum

sansserif.bolditalic.latin-1=DejaVu Sans Bold Oblique
#sansserif.bolditalic.latin-1.motif=LuxiSans-BoldOblique
sansserif.bolditalic.japanese-kochi=Kochi Gothic
sansserif.bolditalic.japanese-sazanami=Sazanami Gothic
sansserif.bolditalic.japanese-vlgothic=VL PGothic
sansserif.bolditalic.korean-baekmuk=Baekmuk Gulim
#sansserif.bolditalic.korean-baekmuk.motif=Baekmuk Gulim
sansserif.bolditalic.korean-un=UnDotum Bold
#sansserif.bolditalic.korean-un.motif=UnDotum Bold

monospaced.plain.latin-1=DejaVu Sans Mono
#monospaced.plain.latin-1.motif=LuxiMono-Regular
monospaced.plain.japanese-kochi=Kochi Gothic
monospaced.plain.japanese-sazanami=Sazanami Gothic
monospaced.plain.japanese-vlgothic=VL Gothic
monospaced.plain.korean-baekmuk=Baekmuk Gulim
#monospaced.plain.korean-baekmuk.motif=Baekmuk Gulim
monospaced.plain.korean-un=UnDotum
#monospaced.plain.korean-un.motif=UnDotum

monospaced.bold.latin-1=DejaVu Sans Mono Bold
#monospaced.bold.latin-1.motif=LuxiMono-Bold
monospaced.bold.japanese-kochi=Kochi Gothic
monospaced.bold.japanese-sazanami=Sazanami Gothic
monospaced.bold.japanese-vlgothic=VL Gothic
monospaced.bold.korean-baekmuk=Baekmuk Gulim
#monospaced.bold.korean-baekmuk.motif=Baekmuk Gulim
monospaced.bold.korean-un=UnDotum Bold
#monospaced.bold.korean-un.motif=UnDotum Bold

monospaced.italic.latin-1=DejaVu Sans Mono Oblique
#monospaced.italic.latin-1.motif=LuxiMono-Oblique
monospaced.italic.japanese-kochi=Kochi Gothic
monospaced.italic.japanese-sazanami=Sazanami Gothic
monospaced.italic.japanese-vlgothic=VL Gothic
monospaced.italic.korean-baekmuk=Baekmuk Gulim
#monospaced.italic.korean-baekmuk.motif=Baekmuk Gulim
monospaced.italic.korean-un=UnDotum
#monospaced.italic.korean-un.motif=UnDotum

monospaced.bolditalic.latin-1=DejaVu Sans Mono Bold Oblique
#monospaced.bolditalic.latin-1.motif=LuxiMono-BoldOblique
monospaced.bolditalic.japanese-kochi=Kochi Gothic
monospaced.bolditalic.japanese-sazanami=Sazanami Gothic
monospaced.bolditalic.japanese-vlgothic=VL Gothic
monospaced.bolditalic.korean-baekmuk=Baekmuk Gulim
#monospaced.bolditalic.korean-baekmuk.motif=Baekmuk Gulim
monospaced.bolditalic.korean-un=UnDotum Bold
#monospaced.bolditalic.korean-un.motif=UnDotum Bold

dialog.plain.latin-1=DejaVu Sans
#dialog.plain.latin-1.motif=LuxiSans-Regular
dialog.plain.japanese-kochi=Kochi Gothic
dialog.plain.japanese-sazanami=Sazanami Gothic
dialog.plain.japanese-vlgothic=VL PGothic
dialog.plain.korean-baekmuk=Baekmuk Gulim
#dialog.plain.korean-baekmuk.motif=Baekmuk Gulim
dialog.plain.korean-un=UnDotum
#dialog.plain.korean-un.motif=UnDotum

dialog.bold.latin-1=DejaVu Sans Bold
#dialog.bold.latin-1.motif=LuxiSans-Bold
dialog.bold.japanese-kochi=Kochi Gothic
dialog.bold.japanese-sazanami=Sazanami Gothic
dialog.bold.japanese-vlgothic=VL PGothic
dialog.bold.korean-baekmuk=Baekmuk Gulim
#dialog.bold.korean-baekmuk.motif=Baekmuk Gulim
dialog.bold.korean-un=UnDotum Bold
#dialog.bold.korean-un.motif=UnDotum Bold

dialog.italic.latin-1=DejaVu Sans Oblique
#dialog.italic.latin-1.motif=LuxiSans-Oblique
dialog.italic.japanese-kochi=Kochi Gothic
dialog.italic.japanese-sazanami=Sazanami Gothic
dialog.italic.japanese-vlgothic=VL PGothic
dialog.italic.korean-baekmuk=Baekmuk Gulim
#dialog.italic.korean-baekmuk.motif=Baekmuk Gulim
dialog.italic.korean-un=UnDotum
#dialog.italic.korean-un.motif=UnDotum

dialog.bolditalic.latin-1=DejaVu Sans Bold Oblique
#dialog.bolditalic.latin-1.motif=LuxiSans-BoldOblique
dialog.bolditalic.japanese-kochi=Kochi Gothic
dialog.bolditalic.japanese-sazanami=Sazanami Gothic
dialog.bolditalic.japanese-vlgothic=VL PGothic
dialog.bolditalic.korean-baekmuk=Baekmuk Gulim
#dialog.bolditalic.korean-baekmuk.motif=Baekmuk Gulim
dialog.bolditalic.korean-un=UnDotum Bold
#dialog.bolditalic.korean-un.motif=UnDotum Bold

dialoginput.plain.latin-1=DejaVu Sans Mono
#dialoginput.plain.latin-1.motif=LuxiMono-Regular
dialoginput.plain.japanese-kochi=Kochi Gothic
dialoginput.plain.japanese-sazanami=Sazanami Gothic
dialoginput.plain.japanese-vlgothic=VL Gothic
dialoginput.plain.korean-baekmuk=Baekmuk Gulim
#dialoginput.plain.korean-baekmuk.motif=Baekmuk Gulim
dialoginput.plain.korean-un=UnDotum
#dialoginput.plain.korean-un.motif=UnDotum

dialoginput.bold.latin-1=DejaVu Sans Mono Bold
#dialoginput.bold.latin-1.motif=LuxiMono-Bold
dialoginput.bold.japanese-kochi=Kochi Gothic
dialoginput.bold.japanese-sazanami=Sazanami Gothic
dialoginput.bold.japanese-vlgothic=VL Gothic
dialoginput.bold.korean-baekmuk=Baekmuk Gulim
#dialoginput.bold.korean-baekmuk.motif=Baekmuk Gulim
dialoginput.bold.korean-un=UnDotum Bold
#dialoginput.bold.korean-un.motif=UnDotum Bold

dialoginput.italic.latin-1=DejaVu Sans Mono Oblique
#dialoginput.italic.latin-1.motif=LuxiMono-Oblique
dialoginput.italic.japanese-kochi=Kochi Gothic
dialoginput.italic.japanese-sazanami=Sazanami Gothic
dialoginput.italic.japanese-vlgothic=VL Gothic
dialoginput.italic.korean-baekmuk=Baekmuk Gulim
#dialoginput.italic.korean-baekmuk.motif=Baekmuk Gulim
dialoginput.italic.korean-un=UnDotum
#dialoginput.italic.korean-un.motif=UnDotum

dialoginput.bolditalic.latin-1=DejaVu Sans Mono Bold Oblique
#dialoginput.bolditalic.latin-1.motif=LuxiMono-BoldOblique
dialoginput.bolditalic.japanese-kochi=Kochi Gothic
dialoginput.bolditalic.japanese-sazanami=Sazanami Gothic
dialoginput.bolditalic.japanese-vlgothic=VL Gothic
dialoginput.bolditalic.korean-baekmuk=Baekmuk Gulim
#dialoginput.bolditalic.korean-baekmuk.motif=Baekmuk Gulim
dialoginput.bolditalic.korean-un=UnDotum Bold
#dialoginput.bolditalic.korean-un.motif=UnDotum Bold

# Search Sequences

sequence.allfonts=latin-1
sequence.allfonts.GB18030=latin-1,wqy-microhei,umingcn,shanheisun,wqy-zenhei
sequence.allfonts.GB2312=latin-1,wqy-microhei,umingcn,shanheisun,wqy-zenhei
sequence.allfonts.GBK=latin-1,wqy-microhei,umingcn,shanheisun,wqy-zenhei
sequence.allfonts.x-euc-jp-linux=latin-1,japanese-vlgothic,japanese-sazanami,japanese-kochi
sequence.allfonts.EUC-KR=latin-1,korean-un,korean-baekmuk
sequence.allfonts.Big5=latin-1,umingtw,shanheisun,wqy-microhei,wqy-zenhei
sequence.allfonts.Big5-HKSCS=latin-1,uminghk,shanheisun,wqy-microhei,wqy-zenhei
#sequence.fallback=uminghk,shanheisun,wqy-zenhei,japanese-vlgothic,japanese-kochi,japanese-sazanami,korean-un,korean-baekmuk,bengali,gujarati,hindi,oriya,punjabi,malayalam,tamil,telugu,sinhala
sequence.fallback=wqy-microhei,uminghk,shanheisun,wqy-zenhei,japanese-vlgothic,japanese-sazanami,japanese-kochi,korean-un,korean-baekmuk,bengali,gujarati,hindi,oriya,punjabi,tamil,telugu

# Exclusion Ranges

exclusion.japanese-kochi=0390-03d6,2200-22ef,2701-27be
exclusion.japanese-sazanami=0390-03d6,2200-22ef,2701-27be
exclusion.japanese-vlgothic=0390-03d6,2200-22ef,2701-27be

# Font File Names

filename.DejaVu_Sans=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf
filename.DejaVu_Sans_Bold=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf
filename.DejaVu_Sans_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Oblique.ttf
filename.DejaVu_Sans_Bold_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-BoldOblique.ttf

filename.DejaVu_Sans_Mono=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf
filename.DejaVu_Sans_Mono_Bold=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf
filename.DejaVu_Sans_Mono_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Oblique.ttf
filename.DejaVu_Sans_Mono_Bold_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-BoldOblique.ttf

filename.DejaVu_Serif=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf
filename.DejaVu_Serif_Bold=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf
filename.DejaVu_Serif_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Oblique.ttf
filename.DejaVu_Serif_Bold_Oblique=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-BoldOblique.ttf

filename.AR_PL_UMing_CN=/usr/share/fonts/truetype/arphic/uming.ttc
filename.AR_PL_UMing_HK=/usr/share/fonts/truetype/arphic/uming.ttc
filename.AR_PL_UMing_TW=/usr/share/fonts/truetype/arphic/uming.ttc
filename.AR_PL_ShanHeiSun_Uni=/usr/share/fonts/truetype/arphic/uming.ttc

filename.WenQuanYi_Micro_Hei=/usr/share/fonts/truetype/wqy/wqy-microhei.ttc
filename.WenQuanYi_Zen_Hei=/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc
filename.Baekmuk_Batang=/usr/share/fonts/truetype/baekmuk/batang.ttf
filename.UnBatang=/usr/share/fonts/truetype/unfonts/UnBatang.ttf
filename.UnBatang_Bold=/usr/share/fonts/truetype/unfonts/UnBatangBold.ttf
filename.Baekmuk_Gulim=/usr/share/fonts/truetype/baekmuk/gulim.ttf
filename.UnDotum=/usr/share/fonts/truetype/unfonts/UnDotum.ttf
filename.UnDotum_Bold=/usr/share/fonts/truetype/unfonts/UnDotumBold.ttf
filename.Kochi_Gothic=/usr/share/fonts/truetype/kochi/kochi-gothic.ttf
filename.Sazanami_Gothic=/usr/share/fonts/truetype/sazanami/sazanami-gothic.ttf
filename.Kochi_Mincho=/usr/share/fonts/truetype/kochi/kochi-mincho.ttf
filename.Sazanami_Mincho=/usr/share/fonts/truetype/sazanami/sazanami-mincho.ttf
filename.VL_Gothic=/usr/share/fonts/truetype/vlgothic/VL-Gothic-Regular.ttf
filename.VL_PGothic=/usr/share/fonts/truetype/vlgothic/VL-PGothic-Regular.ttf

filename.Lohit_Bengali=/usr/share/fonts/truetype/ttf-bengali-fonts/lohit_bn.ttf
filename.Lohit_Gujarati=/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_gu.ttf
filename.Lohit_Hindi=/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_hi.ttf
filename.Lohit_Kannda=/usr/share/fonts/truetype/ttf-kannada-fonts/lohit_kn.ttf
#filename.Lohit_Malayalam=/usr/share/fonts/lohit-malayalam/lohit_ml.ttf
filename.Lohit_Oriya=/usr/share/fonts/truetype/ttf-oriya-fonts/lohit_or.ttf
filename.Lohit_Punjabi=/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_pa.ttf
filename.Lohit_Tamil=/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_ta.ttf
filename.Lohit_Telugu=/usr/share/fonts/truetype/ttf-telugu-fonts/lohit_te.ttf
filename.LKLUG=/usr/share/fonts/truetype/ttf-sinhala-lklug/lklug.ttf

filename.LuxiSans-Regular=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxisr.ttf
filename.LuxiSans-Bold=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxisb.ttf
filename.LuxiSans-Oblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxisri.ttf
filename.LuxiSans-BoldOblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxisbi.ttf
filename.LuxiMono-Regular=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luximr.ttf
filename.LuxiMono-Bold=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luximb.ttf
filename.LuxiMono-Oblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luximri.ttf
filename.LuxiMono-BoldOblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luximbi.ttf
filename.LuxiSerif-Regular=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxirr.ttf
filename.LuxiSerif-Bold=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxirb.ttf
filename.LuxiSerif-Oblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxirri.ttf
filename.LuxiSerif-BoldOblique=/usr/share/fonts/truetype/ttf-xfree86-nonfree/luxirbi.ttf

# AWT X11 font paths
awtfontpath.latin-1=/usr/share/fonts/X11/Type1
awtfontpath.umingcn=/usr/share/fonts/truetype/arphic
awtfontpath.uminghk=/usr/share/fonts/truetype/arphic
awtfontpath.umingtw=/usr/share/fonts/truetype/arphic
awtfontpath.shanheisun=/usr/share/fonts/truetype/arphic
awtfontpath.wqy-microhei=/usr/share/fonts/truetype/wqy
awtfontpath.wqy-zenhei=/usr/share/fonts/truetype/wqy
awtfontpath.japanese-kochi=/usr/share/fonts/truetype/kochi
awtfontpath.japanese-sazanami=/usr/share/fonts/truetype/sazanami
awtfontpath.japanese-vlgothic=/usr/share/fonts/truetype/vlgothic
awtfontpath.korean-baekmuk=/usr/share/fonts/truetype/baekmuk
awtfontpath.korean-un=/usr/share/fonts/truetype/unfonts
</code>

OpenJDK font dependencies


AngularJS - Move Object from Controller 1 to Controller 2

Question: I'm currently learning AngularJS but I wasn't able to find a solution for this problem even though it seems trivial.
I have two lists / controllers that are getting created by factory service.
I want to remove an object from list 1 and add to list 2. When I display the object in the console after passing it, I can see it but it doesn't appear in my second list.
I have the code on GitHub - As you can see this is an assignment from coursera.
https://github.com/alaimoclaudia/assignment2_solution
Comment: unfortunately, links to code on outside sites are not a replacement for code *in the question body*.  links can change, leaving the question completely unusable by others in the future.  You should [edit] your question and provide a [mcve] of the issue.
Comment: can you create a jsfiddle?
Answer: I am not sure I am answering your question, but I have created a plunker based on your github code:
https://plnkr.co/edit/oNvezy5IQ9EBKMpwWq7j?p=preview
I see only one list of items in the code:
<code>[{
  name: "Milk",
  quantity: "10"
}, {
  name: "Donuts",
  quantity: "10"
}, {
  name: "Cookies",
  quantity: "10"
}, {
  name: "Chocolate",
  quantity: "10"
}, {
  name: "Apples",
  quantity: "10"
}];
</code>
And it seems like the ui behaves as expected.
Comment: Thank you very much for your code - that helped! I figured out that the factory was the problem because it created a new service with every call ... I removed the factory and now it's working :)


Collection was modified; enumeration operation may not execute

Question: I am getting the error: Collection was modified; enumeration operation may not execute. I am trying to delete all open form objects apart from the current one:
    FormCollection fc = Application.OpenForms;
    foreach (Form form in fc)
    {
        if (form.ToString().Contains("_MainFrom.Form1"))
        {
            // Do nothing
        }
        else
        {
            form.Hide();
            form.Dispose();
        }
    }

Answer: You can not modify a collection wile enumerating.
use     foreach (Form form in fc.Cast<Form>().ToList())
Answer: Change
foreach (Form form in fc)

to
foreach (Form form in fc.OfType<Form>().ToList())

This way your are copying to OpenForms collection to a new collection before start removing stuff from the original collection.
Comment: @Albin Sunnanbo This does not work :( I already tried that
Comment: @user1559618, sorry, forgot that `OpenForms` just implements `IEnumerable` and not `IEnumerable`. You need to cast with `OfType()` as in my updated example.
Answer: You cant modify the collection where you are performing enumeration(foreach for example). You should use here others methods such as Remove or use for loop.
Answer: Your question is: "I'm modifying collection of Open forms by closing one of the forms while iterating forms and getting error that I'm modifying collection of Open forms while iterating".
Answer: either don't use foreach iteration OR don't modify collection during iteration. Otherwise they'll find out.
Most common approach is to split such operation into 2 steps:

find objects that need to be added/removed from the collection
act on resulting collection of objects

In your case:
var toClose = fc.Where(
   form => form.GetType().FullName.Contains("_MainFrom.Form1"));
toClose.ToList().ForEach(form => {
   form.Hide(); form.Dispose();
});


Computing an infinite sum using the Residue theorem

Question: Show that  $$\sum_{n=-\infty}^\infty \frac{1}{(3n-1)^2} = \frac{4\pi^2}{27}$$
Here is what I tried so far. I know that I can use the Residue theorem to solve a summation of this form.
$$\sum_{n=-\infty}^{\infty} f(n) = -\sum_k \text{res}_{z=z_k} \pi \cot{\pi z}\, f(z)$$
So the poles of $\frac{1}{(3z-1)^2}$ is z= $\frac{1}{3}$ (order 2).
Next I need to find the residues of $\frac{1}{(3n-1)^2} \times \pi \cot(\pi z)$ at z= $\frac{1}{3}$. But, the limit of $\frac{1}{(3z-1)^2} \times \pi \cot(\pi z)$ at z= $\frac{1}{3}$ is $\infty$.
I am not sure what to do at this point. Any help is appreciated.
Answer: The mistake is that you calculate the residue in the wrong way. Define
$$g(z)=\frac{\pi\cot(\pi z)}{(3z-1)^2}=\frac{h(z)}{(z-\frac{1}{3})^2},$$
where $h(z)=\frac{\pi}{9}\cot(\pi z)$. Note that $z=\frac{1}{3}$ is a pole of order $2$ and $h$ is analytic at $\frac{1}{3}$ with $h(\frac{1}{3})\neq 0$. Thus
$$\text{res}_{z=\frac{1}{3}}g(z)=h'(\frac{1}{3})=-\frac{\pi^2}{9}\csc^2(\pi z)|_{z=\frac{1}{3}}=-\frac{4\pi^2}{27}.$$
In general, if $z_0$ is a pole of order $m$ of the function $g$, then we can write
$$g(z)=\frac{h(z)}{(z-z_0)^m}$$
near the point $z_0$ such that $h$ is analytic at $z_0$ with $h(z_0)\neq 0$. Moreover in this case we have
$$\text{res}_{z=z_0}g(z)=\frac{h^{(m-1)}(z_0)}{(m-1)!}.$$
Comment: Great answer. Thank you very much!
Comment: Can we directly use residue theorem to sum this? Isn't that required that we have no singularities on Real axis? Here we definitly have one at $\frac{1}{3}$
Answer: Just for the fun of it since you did ask for this problem solution using complex analysis and here we don't:
$$\frac{\pi^2}6=\sum_{n=1}^\infty\frac1{n^2}=\sum_{n=1}^\infty\frac1{(3n-2)^2}+\sum_{n=1}^\infty\frac1{(3n-1)^2}+\overbrace{\frac19\sum_{n=1}^\infty\frac1{n^2}}^{=\frac19\frac{\pi^2}6}\implies$$
$$\sum_{n=1}^\infty\frac1{(3n-2)^2}+\sum_{n=1}^\infty\frac1{(3n-1)^2}=\frac4{27}\pi^2$$
Now just observe that
$$\sum_{n=-\infty}^0\frac1{(3n-1)^2}=\sum_{n=1}^\infty\frac1{(3n-2)^2}$$


ActiveRecord MySQL query "Like" from self and associations retrieves null if associations are non existant

Question: I have the following scope:
<code> scope :scope_name_or_email_search, lambda { |query = ''|
    joins(:user_information)
      .where('
        users.email LIKE ? OR
        user_informations.first_name LIKE ? OR
        user_informations.last_name LIKE ?',
             "%#{query}%", "%#{query}%", "%#{query}%")
  }
</code>
This scope is retrieving only users with "user_informations" data.
If i search for "@" only the users with "user_informations" data are retrieved however all of them have the character "@" on their emails.
What would be the best approach?
Comment: You need to use a left join if you want to include users with no `user_information`.
Comment: hey alphabetus, if you got your solution, can you post it as an answer so its helpful to others
Comment: Alternatively you can use a UNION: Combine a query of just `users` that searches for matching `email`, with a query that joins `users` with `user_information` and searches for matching `first_name` or `last_name`.
Comment: @trh indeed i have. Incoming.
Comment: @Barmar i was deep on code. Indeed the right solution. You should post this i will move the right answer to you. Cheers.
Comment: @trh answer is posted.
Answer: The solution is quite simple. I need a join left on the query, so the ActiveRecord scope would become this:
<code>scope :scope_name_or_email_search, lambda { |query = ''|
    left_joins(:user_information)
      .where('
        users.email LIKE ? OR
        user_informations.first_name LIKE ? OR
        user_informations.last_name LIKE ?',
             "%#{query}%", "%#{query}%", "%#{query}%")
  }
</code>


Detect if a LineString / MultiLineString is inside a Polygon or if it intersects it using JTS library

Question: Description
So basically what I would like to know is whether a LineString (or MultiLineString) is contained in a MultiPolygon or if it intersects it.
I'm not entirely sure that it might affect, but the real case scenario is that I have a LineString that represents a hiking track, and I need to know through which world areas (which would be my MultiPolygons) is that track going through. Or in the case it is inside of one of my world areas, I need to know which area is containing that LineString.
My problem
My issue here is that I'm getting false positives. If I perform the same check with a Point (to see if it is contained in a MultiPolygon), instead of a LineString, it works perfectly fine.
Steps to accomplish my goal:

Process my LineString from EPSG 3857 format to EPSG 4326 format (using this formula Converting coordinates from EPSG 3857 to 4326 DotSpatial ), since the LineString I received it was in the EPSG 3857 format.
Read my Geometries (using Gson and JtsAdapter, since they are in GeoJson format, concretely they are MultiPolygons). This point shouldn't be the problem, since I use it to detect if a Point is inside a Polygon somewhere else, and works totally OK.
Check whether my LineString intersects or is contained by any of the MultiPolygons and register all the IDs of this MultiPolygons.

My code:
1.Convert my LineString from EPSG 3857 to EPSG 4326:
private fun reprojectFromEpsg3857ToEpsg4326(geometry: Geometry): Geometry
{
    val e = 2.7182818284
    val X = 20037508.34

    if (geometry is LineString) {
        for (i in 0 until geometry.numPoints) {
            val coordinate = geometry.getCoordinateN(i)
            geometry.getCoordinateN(i).x = (coordinate.x * 180) / X
            geometry.getCoordinateN(i).y = coordinate.y / (X / 180)
            geometry.getCoordinateN(i).y = ((Math.atan(Math.pow(e, ((PI / 180) * geometry.getCoordinateN(i).y)))) / (PI / 360)) - 90
        }
    } else if (geometry is MultiLineString) {
        try {
            for (i in 0 until geometry.numGeometries) {
                for (j in 0 until geometry.getGeometryN(i).coordinates.size) {
                    val coordinate = geometry.getGeometryN(i).coordinates[i]
                    geometry.getGeometryN(i).coordinates[i].x = (coordinate.x * 180) / X
                    geometry.getGeometryN(i).coordinates[i].y = coordinate.y / (X / 180)
                    geometry.getGeometryN(i).coordinates[i].y = ((Math.atan(Math.pow(e,((PI / 180) * geometry.getGeometryN(i).coordinates[i].y)))) / (PI / 360)) - 90
                }
            }
        } catch (e: ArrayIndexOutOfBoundsException) {

        }
    }

    return geometry
}

2.Read my Geometries using Gson and Jts adapter:
private fun getGeometries(gson: Gson): HashMap<Long, Geometry>
{
    val geoJsonGeometries = HashMap<Long, Geometry>()
    val geometriesFolder = File("geometries-folder")

    geometriesFolder.listFiles(getFilenameFilter("geojson")).forEach {
        val reader = FileReader(it)
        var geometry = gson.fromJson(reader, Geometry::class.java)

        if (geometry.geometryType == "GeometryCollection") {
            geometry = geometry.getGeometryN(0)
        }

        val geometryId = java.lang.Long.parseLong(it.name.replace(".geojson", ""))
        geoJsonGeometries[geometryId] = geometry
    }

    return geoJsonGeometries
}

3.Perform the check to see which MultiPolygons are related (either by containment or by intersection) with my LineString:
val geometryIds = ArrayList<Long>()
geometries.forEach { geometryId, mapBoundaries ->
    if (routeAsLineString.intersects(mapBoundaries) || mapBoundaries.contains(routeAsLineString)) {
        geometryIds.add(geometryId)
    }
}

Any help would be very thankful!
Answer: Alright, I got very wrongly the MultiLineString conversion from EPSG 3857 format to EPSG 4326 format. Basically, I wasn't converting the MultiLineString, only the first coordinate was being converted. But there are many Geometry objectes inside a MultiLineString and each of them has many coordinates.
So steps 2 and 3 were correct.
The original conversion was:
for (i in 0 until geometry.numGeometries) {
    for (j in 0 until geometry.getGeometryN(i).coordinates.size) {
        val coordinate = geometry.getGeometryN(i).coordinates[i]
        geometry.getGeometryN(i).coordinates[i].x = (coordinate.x * 180) / X
        geometry.getGeometryN(i).coordinates[i].y = coordinate.y / (X / 180)
        geometry.getGeometryN(i).coordinates[i].y = ((Math.atan(Math.pow(e,((PI / 180) * geometry.getGeometryN(i).coordinates[i].y)))) / (PI / 360)) - 90
    }
}

But should have been:
for (i in 0 until geometry.numGeometries) {
    for (j in 0 until geometry.getGeometryN(i).coordinates.size) {
        val coordinate = geometry.getGeometryN(i).coordinates[j]
        geometry.getGeometryN(i).coordinates[j].x = (coordinate.x * 180) / X
        geometry.getGeometryN(i).coordinates[j].y = coordinate.y / (X / 180)
        geometry.getGeometryN(i).coordinates[j].y = ((Math.atan(Math.pow(e,((PI / 180) * geometry.getGeometryN(i).coordinates[j].y)))) / (PI / 360)) - 90
    }
}


Undefined error: 0 OR Unable to load autoload.php. Drush now requires Composer

Question: I've installed drush in /usr/local/lib/drush/drush and composer in /usr/local/bin/composer.
When I try to run drush /usr/local/lib/drush/drush I get the following:

/usr/local/lib/drush/drush: line 129: /Applications/MAMP/bin/php/php5.2.17/bin: is a directory /usr/local/lib/drush/drush: line 129: exec: /Applications/MAMP/bin/php/php5.2.17/bin: cannot execute: Undefined error: 0 –

OR the following:

Unable to load autoload.php. Drush now requires Composer in order to install its depedencies and autoload classes. Please see README.md

What am I doing wrong? I'd like to install drush to use with MAMP if anyone has any suggestions. I've done through the readme and nothing seems to be working.
Comment: Have you set the environment variable DRUSH_PHP?  It looks like Drush is trying to exec the 'bin' directory that PHP is in, rather than the php executable itself. Point directly at php, as shown in tenken's answer.
Answer: Drush switched to requiring composer. The documentation provides details on how to install both composer and drush, but it boils down to:

Install composer globally:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Install drush globally (for your user), you can specify the version:
composer global require drush/drush:6.*

Add the composer path to your path (in your .bashrc or .zshrc or other):
export PATH="$HOME/.composer/vendor/bin:$PATH"

Comment: when I run mv composer.phar /usr/local/bin/composer I get a denied permission message. It seems like I can't access this path.
Comment: You'll have to run that command as the superuser. If your server uses `sudo`, prefix that command with it.
Answer: These were the steps I used to install drush globally using composer in Linux (not in ~/.composer/vendor/bin logged in as root which makes absolutely no sense):

Login as root
Install composer if necessary.  See. http://getcomposer.org/doc/00-intro.md#system-requirements.
composer global require drush/drush:6.*
or
composer global require drush/drush:dev-master
cd ~/.composer
composer config --global bin-dir /usr/local/bin
composer config --global vendor-dir /usr/local/share
composer install
cp -r vendor/ /usr/local/share/drush/drush/
cd /usr/local/share/drush/drush
composer install

Now any user with /usr/local/bin in their path can run drush.
Security precaution: You might want to chown and chmod /usr/local/bin/drush so only authorized users in a certain group can execute drush.
Notes: Lines 5 and 6 create the file ~/.composer/config.json.  Line 10 is needed to delete (yes, delete) the /usr/local/share/drush/drush/vendor/drush folder which is unnecessary.
Comment: You guided me there. In my case it was simply to go to '/usr/share/drush7' and run 'composer install'. Easy.
Comment: I am stuck on Line 8, it gives me the error that cp: /usr/local/share/drush/drush/drush: Not a directory - For all the further directories
Answer: Have you googled for like "OSX + drush + mamp" ... http://kerasai.com/blog/2013/07/30/easy-way-make-drush-work-mamp

The main hiccup with drush on MAMP is that drush doesn't use the PHP
  packaged with MAMP and commonly the PHP shipped with OSX is not
  configured to meet Drupal's requirements. It's possible to reconfigure
  the PHP that ships with OSX to meet Drupal's requirements, but
  wouldn't the smart thing to do be to use MAMP's PHP? You can do this
  by adding the following line to ~/.profile, adjust as needed.

alias drush='DRUSH_PHP=/Applications/MAMP/bin/php/php5.4.10/bin/php /usr/local/drush/drush'

Comment: Thanks! Yes I did google and went through a lot of trial and error...
After adding to .bash_profile I'm getting the following when I try to execute drush:
-bash: /usr/local/drush/drush: No such file or directory
Comment: @radishred From the looks of the question your drush install is at /usr/local/lib/drush/drush, so just replace as necessary
Comment: Thanks Clive, still not working so I started over using homebrew and for the most part was pretty easy.
Comment: No .profile but default on Mountain lion for me


Is a bijective graph homomorphism also an automorphism?

Question: Let $f$ be a map from a finite graph $G$ to itself.
Then

$f$ is an homomorphism if $f(x)$ and $f(y)$ are adjacent for all adjacent vertices $x$ and $y$ in $G$.
$f$ is an automorphism if, for all vertices $x$ and $y$ in $G$, $x$ and $y$ are adjacent if and only if $f(x)$ and $f(y)$ are adjacent.

If $f$ is a bijective homomorphism, how do I show it is also an automorphism? I've seen a proof of the equivalent statement for groups but I can't see how to translate it to the language of graph theory.
Comment: $f$ gives you a bijection $g$ from the cartesian product of the set of vertices with itself (pairs of vertices). In particular, since $f$ is a homomorphism $g$ restricts to an injective function on the set of edges (which is a subset of the set of pairs of vertices). An injective function from a finite set to itself is bijective. Therefore, $g$ restricted to the set of edges is bijective. Hence $f$ is an automorphism.
Comment: When you say $f$ is a bijection, do you mean on verticies, on edges, or both?
Answer: Suppose $G$ has $m$ edges and $f: G \to G$ is a bijective homomorphism.
Then each pair of adjacent vertices determines an edge on the image of $f$.
Thus there exist $m$ edges in the image of $f$, which are all distinct because $f$ is injective.
Let $x$ and $y$ be non-adjacent vertices in $G$.
Then $f(x)$ and $f(y)$ are also non-adjacent, otherwise the image of $f$, which is contained in $G$, would have $m + 1$ edges.
Hence $f$ is an automorphism.


The elements in the bounded derived category of a hereditary category

Question: I am looking for a proof for the following statement.

Let $\mathcal A$ be a hereditary category, and $D^b(\mathcal A)$ be its bounded derived category. Then for any $M \in D^b(\mathcal A)$, we have
  $$M \cong \oplus_i H^iM[-i].$$

Most of the proofs I have found are similar. For example, 2.2 in this document.
The author writes an exact sequence
$$0 \rightarrow X^{n-1} \rightarrow E^n \rightarrow H^nX \rightarrow 0.$$
But what is this $E^n$, and why there is an exact sequence like this? Then how is the second commutative diagram obtained from the first?
I think the main problem for my understanding this proof is the definition of $E^n$. Maybe it is related to $\operatorname{Ext}$'s, but I need to know exactly what it is.
Thanks very much.
Answer: I'll try to fill in some details for the proof from the link you provided. Here $X^*$ is a complex of objects of $\mathcal{A}$, with differential $d^*$.
Recall the long exact sequence for the $\operatorname{Ext}$ spaces: starting from the short exact sequence
$$0\to \ker d^{n-1} \to X^{n-1} \to \operatorname{im} d^{n-1} \to 0 $$
and applying the functor $\operatorname{Hom}(H^nX,-)$, you get an exact sequence
$$ \operatorname{Ext}^1(H^nX,\ker d^{n-1})\to \operatorname{Ext}^1(H^nX, X^{n-1}) \stackrel{\lambda}{\to} \operatorname{Ext}^1(H^nX,\operatorname{im} d^{n-1}) \to \operatorname{Ext}^2(H^nX,\ker d^{n-1}). $$
Since the category $\mathcal{A}$ is hereditary, the $\operatorname{Ext}^2$ space vanishes, so $\lambda$ is surjective.
Now, elements of the $\operatorname{Ext}^1$ spaces correspond to short exact sequences.  Unwinding the definition of $\lambda$, it being surjective precisely means that there is a short exact sequence from $X^{n-1}$ to $H^nX$ and a commutative diagram
\begin{array}{ccccccccc}
0 & \xrightarrow{} & X^{n-1} & \xrightarrow{} & E^n & \xrightarrow{} & H^nX & \xrightarrow{} & 0\\
 &  & \downarrow &  & \downarrow &  & \downarrow{=} & & \\
0 & \xrightarrow{} & \operatorname{im}d^{n-1} & \xrightarrow{} & \ker d^{n-1} & \xrightarrow{} & H^nX & \xrightarrow{} & 0.
\end{array}
(Simply view the lower exact sequence as an element of $\operatorname{Ext}^1(H^nX,\operatorname{im} d^{n-1})$, and the upper exact sequence is then a preimage of the lower one by $\lambda$.)
From there, the proof in the paper only uses the morphisms constructed above.

If you are mainly interested in the case where $\mathcal{A}$ has enough projectives, then you might be interested in Happel's original proof, which can be found in Lemma 4.1 of this paper.
Comment: Thank you very much. I forget to consider $\operatorname{Ext}^1$ as extensions, so I didn't consider the lower line as an element of $\operatorname{Ext}^1(H^nX,\operatorname{im} d^{n-1})$. Now I understand the proof. Thank you very much for the explanation.


How to get a data from a input box in html and pass it as a parameter in Rest API request in Flask Python

Question: I need to create an API end point like :
@app.route('/user/<username>')
def user(username)
  -- do something with the username

in the index.html the code for input box is :
<input type="username" name="user_name" id="uname" placeholder="Input your  name">

Pls advise how I can pass this input as the 'username' variable?
Comment: You want to query `/user/` api after user entered that `username` ?
Comment: Can you provide a more detailed  solution? Thanks
Answer: You need to get the value after user submit. Using javascript to get that value and make the request to Flask server.
function makeRequest(event) {
  fetch('/user/'+ event.target.value)
    .then(function(response) {
      console.log(response)
    })
}
....
<input type="text" id="foo" value="bar" onkeyup="makeRequest(this)" />


Stuck on a proposition

Question: Suppose four numbers $\{a,b,c,d\}$ where $a$ and $c$ random variables from a continuous distribution with support on $\mathbb{R}$.
Does $b\neq d$  imply $|a−b|−|c−d|+a−c\neq 0$ almost surely?
I really want to believe this proposition is true but that is typically not enough to make it so.
Edit:
MickMack's counter example made me realize I need to refine the proposition to make it:
Does $|b|\neq|d|$  imply $|a−b|−|c−d|+a−c\neq 0$?
Answer: Are there any constraint on b and d?
If we take $b=2$ and $d=-2$, then:
$|a-b|-|c-d|+a-c=|a-2|-|c+2|+a-c$
If we only suppose that a and c are sampled from a continuous distribution, then :
$P(a<2,c<-2)$ might be $>0$
In this case :
$|a-b|-|c-d|+a-c=|a-2|-|c+2|+a-c = 2-a-(-2-c)+a-c=0$
Comment: Maybe you only need to say that : $|b|\neq|d|$
Answer: I am not sure why you say that $a$ and $c$ are sampled.
For a continuous distribution, the probablility you get an exact value is always zero.
Idea is that for a continuous distribution, you have an uncountable infinity of possible values, so that the probability of an exact realization is zero. It is the same thing with the probability that you get a value related to a value you previously got.
It is different for a non continuous distribution.
And if you take only numbers, you have counterexamples, for instance ex $\{1,1,0,-1\}$ you get $0$
Comment: $b$ and $d$ are *not* random variables.

Stuck on a proposition


Estou com um problema com esse slideshow

Question: Faz tempo que venho tentando achar o problema mais n consigo (nota: sou novato nesta área), acontece que quando o background troca a imagem, num pequeno intervalo ele da tipo um flash, e como mudei de jquery para css, pois não estava conseguindo suavizar o efeito slider, esse flash está me irritando. E o interessante que  só acontece no primeiro loop, depois ele continua a trocar imagens normalmente. Enfim está aqui o código, espero que me ajudem.
.body{
    overflow-x: hidden;
    background-image: url("imagens/fundo.png");
    background-repeat: no-repeat;
    background-size: cover;
    animation: linear;
    animation-name: body;
    animation-duration: 30s;
    animation-iteration-count: infinite;
    animation-delay: .1s;
}`
`@keyframes body{
    0%  {background-image: url("imagens/slide.jpg"); background-size: 100% 100%;}
    20%  {background-image: url("imagens/slide1.jpg"); background-size: 100% 100%;}
    40%  {background-image: url("imagens/slide2.jpg"); background-size: 100% 100%;}
    60%  {background-image: url("imagens/slide3.jpg"); background-size: 100% 100%;}
    80%  {background-image: url("imagens/slide4.jpg"); background-size: 100% 100%;}
    100%{background-image: url("imagens/slide5.jpg"); background-size: 100% 100%;}
    }

Answer: Acontece que as imagens estão sendo baixadas no momento em que o CSS troca o frame. Adicione este código na página só para garantir que as imagens já estejam carregadas e assim evitar que na hora de trocar via css, haja este pequeno flash.


Como usar o zipalign no Andriod Studio?

Question: Trabalho com o android studio no mac, e no momento gero o app com o zipalign que vem junto a ide utilizando comando via terminal. Toda vez que gero o app mostra essa mensagem da imagem, existe a possibilidade de configurar automaticamente na IDE?
Comment: Tente copiar o `zipalign` da pasta `android-studio\sdk\build-tools\20.0.0\` para `android-studio\sdk\tools\`, houve uma migração recente (antes ele ficava nessa pasta `\sdk\tools`) e me parece que não foi alterado nas `IDE's`
Comment: Funcionou, colocar sua dica como resposta.
Answer: Basta copiar o zipalign da pasta android-studio\sdk\build-tools\versao_do_seu_build para android-studio\sdk\tools.
Houve uma migração recente no SDK (antes ele ficava nessa pasta ...\sdk\tools) e me parece que não foi alterado nas IDE's
Comment: Muito bom, funcionou aqui

Como usar o zipalign no Andriod Studio?