Guard eligibility to run the ball

Question: Can a guard take a snap from the center if the QB or RB doesn't? Is the guard an eligible running back?
Comment: The term guard I'm using to ask this question is in formation. The guard pulls behind the center after the snap. The center holds the ball between his legs and behind him, and the pulling guard takes the snap. At no time does a back contact the ball. Hope this explains further what I was asking. Thank you for all the feed back. Coach D, I agree with your article 4 and this not being a legal snap.
Answer: The answer is no.  A guard cannot take the snap directly from the center.
Anyone not on the line of scrimmage can take a snap - rules of football.  A guard is a position next to the center on the line of scrimmage so the answer is - No.
A guard however can receive a handoff (not a snap) from anyone including the quarterback.  The guard can also pick the ball up off of the ground if the center chooses to leave it there (many trick play variations here).

Article 4: Legal Snap. A snap is a backward pass. The snap must be
  received by a player who is not on the line at the snap, unless the
  ball first strikes the ground. If the ball first strikes the ground,
  or is muffed by an eligible backfield receiver, or quarterback under
  center, it can be recovered and advanced by any player.
Comment: @Joe - Added rule.  This is pretty basic though.
Comment: Thanks.  Though this seems to suggest that it would be possible to run a snap to a guard as long as it bounced off the ground first...
Comment: @Joe  That is what I said in my original answer.  If it is on the ground it is also not a snap, and is at best considered a loose ball and at worst a fumble.
Answer: If you are asking whether a player that typically plays guard can take the snap, the answer is yes... with a real caveat:
From the NFL rules...
First, Rule 5, Section 1, Article 2:

PLAYERS NUMBERED BY POSITION
  All  players  must  wear  numerals  on  their  jerseys  in  accordance with  Rule  5,  Section  4,  Article  3(c).
  Such numerals must be by playing position, as follows:
  (a)   quarterbacks, punters, and placekickers: 1-19;
  (d)   offensive guards and tackles: 60-79;

But second, Rule 5, Section 3, Article 1:

REPORTING CHANGE OF POSITION
  An offensive player wearing the number of an ineligible pass receiver (50-79 and 90-99) is permitted to line up in the position of an eligible pass receiver (1-49 and 80-89), and an offensive player wearing
  the number  of  an  eligible  pass  receiver  is  permitted  to  line  up  in  the  position  of  an  ineligible  pass  receiver, provided that he immediately reports the change in his eligibility status to the Referee, who will inform the defensive team.

So, combined with Coach-D's answer on how a snap must be performed, I believe this narrows it down that a person who usually plays as guard can take the snap... but only after they report as eligible (since all backfield players are eligible, and you must be in the backfield to take the snap).
That player also cannot return to playing guard until they skip a play (or a timeout, possession change or similar events).
Comment: OK the OP has clarified and he isn't asking for the "typically plays guard".  I hope the questions on the site haven't become that trivial where we expect the worst from the OPs.
Comment: If they line up at quarterback they are not a guard!  Also numbers isn't a football rule it is kind of an NFL rule.   Anyone can line up at QB.  In the NFL you have to report as eligible - but even this is murky at best in the NFL.  A "guard" could also have an eligible number.   I think the OP could clarify their question but the answer is NO a guard cannot take a direct snap from the snapper (center).  If the "guard" is in the backfield lined up as a QB, then he is a QB, not a guard.   An answer like this suggest that players are assigned a position, and they aren't.
Comment: While that is true, that players don't have assigned positions... it's still also true that if you watch the lineup announcements before the game, read the program, check the roster webpage, play fantasy sports, or have sports cards... players of course are indeed regularly associated with a set position. So while I absolutely agree that there is never any requirement they play in that position, some people have shown they are disposed to interpret this in that direction, so I decided to further clarify for that viewpoint. And that's why I tried to say "typically plays guard" consistently :-)
Comment: No worries, sometimes that's how it goes.  Certainly can be frustrating when people aren't clear.  I try to make the best of it, and remain calm about it all as best as possible.
Answer: I would think this analogous to the Wildcat formation, in that:

The ball is snapped to someone who isn't traditionally the quarterback
Five players must report as eligible receivers should the not-a-quarterback choose to throw the ball
The player's initial position isn't relevant, so long as all other positions properly report

A guard that is declared as a guard likely can't suddenly line up as the quarterback, and if they could suddenly shift the formation, it wouldn't be wise; all of a sudden one's very important quarterback is now on the line of scrimmage, staring down several men who are more than capable of running right through them.
Comment: @Coach-D:  How so?  I never said that the guard was on the line, I merely stated that the guard was coming in *as* a quarterback or someone that would normally receive the snap.  Do you have any sources to definitively prove that this is not legal?
Comment: @Makoto - Anyone can line up at quarterback - that is not the question.  He asked if a guard can take a snap - the person who lined up as the guard, not Fred who believes he is a guard in his heart but is asked to play quarterback.  You are turning a valid question into something silly.
Comment: I think you two are taking different interpretation of the question here - crucially, whether we're talking about "someone who normally plays guard" or "someone who lined up on the offensive line". Despite the assertion, it's not obvious to me which interpretation the OP means, particularly given that there is a reasonable interpretation at least at the NFL level that any offensive player wearing numbers 50-79 *is* an offensive lineman, even if they line up somewhere else.
Comment: A quarterback like Tim Tebow or Cam Newton probably wouldn't necessarily be too shy about it.  But I think you're right about there being rules for lining up based upon your jersey number, hopefully someone can dig into that more.  Additionally I believe players must report as eligible receivers even if they are not running a pass play, as there are rules about having uncovered linemen on the line of scrimmage making a formation illegal, at least at some levels.  And let's go one up on the wildcat, and go to the A-11, which should cover much of this craziness 8-)
Comment: This answer is wrong - sorry.
Comment: If the guard comes in as a quarterback, then he is not a guard and is a quarterback.   A "guard" is a position on the line, not a philosophical position a player usually plays.
Comment: @Coach-D:  I'm still not seeing how this is wrong, then.  What I'm looking for is some concrete, definitive rule that states that a player that normally plays a specific position can't suddenly take over another spot, and when I thought of that, then I realized that the Wildcat formation could be rendered invalid based on that.  I'm well aware that any player can suddenly be playing quarterback, but if they're asked to and have shown the prior capabilities, they *can* take a snap.
Comment: @Makoto - Your answer also doesn't make sense because a guard never declares that they are a guard.  In the NFL they ask players that play guard to try to wear a range of numbers - this is not a hard rule.   Offensive lineman are asked to wear certain numbers but this is not a hard rule and certainly not a pure football rule.  Also as far as I know any number can play quarterback in the NFL without a penalty as long as they declare themselves eligible - again the number constraint is just an NFL thing, not a football rule.

Guard eligibility to run the ball


O que é Code Smell?

Question: Comecei a estudar swift e me deparei com um termo muito utilizado chamado Code Smell pelo que consegui entender na Wikipedia e em alguns outros sites ele é qualquer sintoma no código fonte que indica um problema mais profundo, e.g: código duplicado.
Por esta definição eu acabo me questionando a seguinte coisa, Code Smell não é a mesma coisa que os princípios DRY, KISS e YAGNI?
Como posso identificar code smell/bad smell em um código?
Comment: Você conhece a expressão "onde há fumaça há fogo"? O sentido disso é, bom, *nem sempre* fumaça quer dizer fogo, mas é um bom indício, então melhor ficar alerta... Da mesa forma, no meu entendimento, *"code smell"* tem o sentido de indicar coisas que não estão "erradas" no código, mas que podem indicar um problema mais profundo. Às vezes o programador se desvia das "boas práticas" por um bom motivo. Mas na maioria das vezes, o faz por ignorância, então é bom ficar atento às possíveis consequências (revisar o código), pois pode não estar quebrado agora mas tem boa chance de quebrar no futuro.
Comment: Já eu achava que era algo relacionado à [dívida técnica](http://pt.stackoverflow.com/q/32420/3117), mas não tenho certeza.
Comment: @Math está lá no artigo da Wikipedia, _"Code smells are an important reason for technical debt."_
Comment: @Piovezan tem razão, eu não cheguei a ler a página, mas sabia que tinha algo a ver :P
Comment: @Math
Nunca tinha ouvido falar em dívida técnica, acho que são tantos fatores que devem ser considerados na hora de ver se um código pode ser refatorado ou não
que me deixam mais confuso, acabo lembrando de uma frase antiga dos programadores "Se esta funcionando,não mexa."
Comment: @mgibsonbr Muito bem falado.
Comment: Em bom português, code smell é a famosa "gambiarra".
Answer: Determinar o que é ou não um code smell é sempre um julgamento subjetivo, e sempre irá variar de acordo com a linguagem de programação, o desenvolvedor e a metodologia de desenvolvimento.
Existem ferramentas que detectam certos tipos de code smells, como:
Java: Checkstyle, PMD e FindBugs.
.Net: ReSharper.
Para Php.
Alguns Code smells comuns:
Código duplicado: código idêntico ou muito similar existe em mais de um local.
Método longo: um método, função ou procedure muito extenso.
Classe extensa: uma classe que acabou ficando muito extensa (God Object).
Feature envy (sem tradução): uma classe que utiliza em excesso métodos de outra classe.
Intimidade inapropriada: uma classe que possui dependência de detalhes de implementação de outra classe.
Legado recusado: uma classe que sobrepõe (override) o método da classe genérica de forma que o contrato da classe genérica não é cumprido pela classe derivada.
Classe preguiçosa: classe que faz muito pouco.
Complexidade artificial: uso forçado de design patterns extremamente complicados, onde um design simples seria suficiente.
Identificadores excessivamente longos: em particular, o uso de convenções de nomes para evitar ambiguidades, o que deveria estar implícito na arquitetura do software.
Answer: Não são a mesma coisa. Muitos code smells (mau cheiro no código) irão seguir esses princípios de DRY, KISS e YAGNI, que são prevalentes em desenvolvimento de software, mas nem todos irão (exemplos: Excessively short identifiers, Constants class).
Mas independente disso, se as situações de mau cheiro fossem óbvias para todo mundo, não seria preciso compilar uma lista de code smells em primeiro lugar. Bastaria dizer "siga sempre princípios como o DRY, KISS e YAGNI".
Como foi dito, há ferramentas que detectam alguns code smells, mas a forma mais completa de saber se o seu código tem code smells é pegar uma boa lista de code smells (tem uma por exemplo no livro "Código Limpo" do Robert C. Martin), estudá-los e ver se existem no seu código. Se todos foram óbvios e você evitou todos no seu código, parabéns! Você é muito bom em aplicar os princípios de DRY, KISS e YAGNI, entre outros.
Caso contrário, você conheceu melhor os code smells e os princípios por trás deles e com isso saberá ficar mais atento a código com mau cheiro, podendo aplicar isso em seu código existente e em códigos futuros. Isso o ajudará a ter código mais robusto e seguindo bons princípios.
Answer: code smell/bad smell, é o termo usado para evidenciar que algo no código não faz sentido(falta de coesão), caso esse problema não seja tratado irá se espalhar, o custo e esforço para corrigi-lo aumentará. Alguns exemplos são classes com mais de uma reponsabilidade e falta de modularização.

O que é Code Smell?


How to use RedisTimeSeriesCommands with jedis in Java Spring Boot

Question: I am currently utilizing jedis version 4.3.0 in my Java Spring Boot project. I am interested in utilizing the Redis time series commands interface to store time series data in Redis. However, I am unsure whether I can directly employ Redis time series commands to interact with the time series data without the need for additional dependencies such as JRedisTimeSeries. If direct utilization is possible, how should I establish a connection and implement methods from that interface?
I have tried to create bean for RedisTimeSeriesCommands
@Bean
    public RedisTimeSeriesCommands redisTimeSeriesCommands() {
        return new RedisTimeSeriesCommands() {
            @Override
            public String tsCreate(String key) {
                return null;
            }

            @Override
            public String tsCreate(String key, TSCreateParams createParams) {
                return null;
            }

            @Override
            public long tsDel(String key, long fromTimestamp, long toTimestamp) {
                return 0;
            }

            @Override
            public String tsAlter(String key, TSAlterParams alterParams) {
                return null;
            }

            @Override
            public long tsAdd(String key, double value) {
                return 0;
            }

            @Override
            public long tsAdd(String key, long timestamp, double value) {
                return 0;
            }

            @Override
            public long tsAdd(String key, long timestamp, double value, TSCreateParams createParams) {
                return 0;
            }

            @Override
            public List<Long> tsMAdd(Map.Entry<String, TSElement>... entries) {
                return null;
            }

            @Override
            public long tsIncrBy(String key, double value) {
                return 0;
            }

            @Override
            public long tsIncrBy(String key, double value, long timestamp) {
                return 0;
            }

            @Override
            public long tsDecrBy(String key, double value) {
                return 0;
            }

            @Override
            public long tsDecrBy(String key, double value, long timestamp) {
                return 0;
            }

            @Override
            public List<TSElement> tsRange(String key, long fromTimestamp, long toTimestamp) {
                return null;
            }

            @Override
            public List<TSElement> tsRange(String key, TSRangeParams rangeParams) {
                return null;
            }

            @Override
            public List<TSElement> tsRevRange(String key, long fromTimestamp, long toTimestamp) {
                return null;
            }

            @Override
            public List<TSElement> tsRevRange(String key, TSRangeParams rangeParams) {
                return null;
            }

            @Override
            public List<TSKeyedElements> tsMRange(long fromTimestamp, long toTimestamp, String... filters) {
                return null;
            }

            @Override
            public List<TSKeyedElements> tsMRange(TSMRangeParams multiRangeParams) {
                return null;
            }

            @Override
            public List<TSKeyedElements> tsMRevRange(long fromTimestamp, long toTimestamp, String... filters) {
                return null;
            }

            @Override
            public List<TSKeyedElements> tsMRevRange(TSMRangeParams multiRangeParams) {
                return null;
            }

            @Override
            public TSElement tsGet(String key) {
                return null;
            }

            @Override
            public TSElement tsGet(String key, TSGetParams getParams) {
                return null;
            }

            @Override
            public List<TSKeyValue<TSElement>> tsMGet(TSMGetParams multiGetParams, String... filters) {
                return null;
            }

            @Override
            public String tsCreateRule(String sourceKey, String destKey, AggregationType aggregationType, long timeBucket) {
                return null;
            }

            @Override
            public String tsCreateRule(String sourceKey, String destKey, AggregationType aggregationType, long bucketDuration, long alignTimestamp) {
                return null;
            }

            @Override
            public String tsDeleteRule(String sourceKey, String destKey) {
                return null;
            }

            @Override
            public List<String> tsQueryIndex(String... filters) {
                return null;
            }

            @Override
            public TSInfo tsInfo(String key) {
                return null;
            }

            @Override
            public TSInfo tsInfoDebug(String key) {
                return null;
            }
        }
    }

But I dont know how to implement methods.
Answer: In your implementation you to inject/expose the right Jedis client to use the commands in https://github.com/redis/jedis/blob/master/src/main/java/redis/clients/jedis/timeseries/RedisTimeSeriesCommands.java which you can get via UnifiedJedis
At the top level you probably need a RedisConnectionFactory of type JedisConnectionFactory, something like:
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
  return new JedisConnectionFactory();
}

@Bean
public UnifiedJedis unifiedJedis(RedisConnectionFactory factory) {
  // Assumes factory is JedisConnectionFactory
  JedisConnectionFactory jedisFactory = (JedisConnectionFactory) factory;

  // Configure as needed
  JedisPoolConfig poolConfig = new JedisPoolConfig();
  // Set pool config as needed

  // Return the UnifiedJedis instance
  return new UnifiedJedis(jedisFactory.getHostName(), jedisFactory.getPort(), poolConfig)
}

@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory factory) {
  RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
  template.setConnectionFactory(factory);
  return template;
}

Then wire the UnifiedJedis into your Bean and use the TS methods exposed:
unifiedJedis.tsCreate("myTSKey");


Alternate to copying app.config settings to web.config?

Question: I am working on a class library that uses Microsoft enteprise library logging application block. I have some settings in my app.config file.
Now, when a developer uses this library in a web applications, they have to copy entire config sections and appsettings part from the app.config to the web.config.
Is there something which can be done to bypass this step and makes it easier for developers to use my library without manual copy of all those settings.
Answer: Could try putting the repeated sections in an external config file, adding that file as a reference to the web.config project, and then referencing it in both the app.config & the web.config.
Comment: I thought of going this way but is this the best and cleanest approach? I assume there must be some better ways to handle this
Answer: Enterprise Library has a visual config editor that you can use to load your web.config.
You can choose the settings you want and have them persisted to this file. Personally, I would not use Enterprise Library unless I had no choice. Simply too much glop code and overhead.
Comment: Point is I am creating a library, and have all the settings in the app.config. Now when a developer uses my libary, application will look for the current settings in the application and not in the library's app.config. Now every time developer has to copy those settings from library's  app.config to app's web.config.


Can't transfer files via FTP through VPN after switch to new router (with identical network and port-forwarding settings)

Question: I have a problem with the following setup: A friendly local business has a time stamp clock on site A. This clock provides data via an integrated ftp server. Also on site A: a Raspberry Pi 3 running Debian Wheezy acting as OpenVPN server. Port forwarding on the router was set to enable VPN and SSH connections from the internet via a dynamic DNS address. This enabled users from site B, where the payroll accounting magic is happening, to first establish a tunnel to site A's network and then fetch time stamp clock data with the help of a proprietary Windows software using the (active) FTP protocol.
It all worked fine until they switched their internet provider. The new router (to which I don't have access) was set up identical to the old one with all clients on the network having the same IPs – and the same port forwarding settings as well. After the switch, I still can SSH into the raspberry, open a tunnel to site A's network, and ping the time stamp clock. But whenever I try to fetch the data via FTP (no matter if I try it with the proprietary software from the manufacturer or with a standard FTP client), I errors like "LIST requested action not taken" or something similar.
My guess is that this somehow is an active FTP protocol problem where the answers from the time stamp clock are not routed back through the tunnel properly. But this is just a guess – and I have no idea how to debug and fix this. Maybe anyone here does? Anything that hints me in the right direction is highly appreciated!
Thank you and greetings from Germany!
Comment: The new router, contrary to the claims made, is almost certainly not setup identically to the old one.  Have the ISP, or whoever did the setup and made the false claim, to fix it.
Comment: The information  you have provided is not enough to troubleshoot the issue. If it was working before, and not working now, there must be something that changed. Comparing the new settings with old one would be the first step to start troubleshooting.
Comment: But how can FTP be blocked if the tunnel is otherwise working? I just don't get my head around that.
Comment: OpenVPN and FTP settings are identical (as they haven't changed). All I did was updating the raspberry in the hope that this would fix things. I have no router access; I assumed – as SSH and VPN tunnels are working – that the configuration here is okay. But I don't know how I could possibly verify that. Is it technically possible that the router forwards the tunnel correctly but prevents FTP from working? How? As you might have already guessed, I'm not an expert, so sorry if these are dumb questions – I just don't understand what is going on here.
Comment: That would be difficult to answer. FTP is complicated than ssh. Without router access, your options are limited. You can try to run Wireshark/tcpdump and analyze the traffic, see if the connection is established, authentication is working, and so on. You will need to have good understanding of a working ftp session, and then if you see the issue is with Network (traffic is not making through), present it to your new service provider.
Comment: As far as I can see: FTP is working fine in passive mode, so the connection basically works. In active mode, I can connect but see no files et cetera.
Answer: The problem that happens sometime is the following:  say that:
Site A's LAN is 192.168.1.x   and
RaspberryPi's LAN address is 192.168.1.10
Time clock's LAN address is 192.168.1.11
Now RaspberryPi hands out OpenVPN addresses to it's clients (site B, say using 10.1.2.0) so:
SiteB's client has 10.1.2.5 and RaspberryPi itself is set as a server as 10.1.2.1
What happens now is that RaspberryPi routes the 10.1.2.0 traffic to 192.168.1.0 network allowing you to access the time clock. So far so good (i assume this was never touched). This 192.168 traffic is then handled by the LAN router to reach the time clock.
The problem happens when the LAN router sometimes see the packets as coming from RaspberryPi's 10.1.2.0 address instead of 192.168.1.10 address. So, it sends the packet to the time-clock but the responses are routed to the regular Internet gateway instead.
The solution for that is to have a static route on the LAN router which sets RaspberryPi 192.168.1.10. as the gateway for all 10.1.2.0 traffic.
The other solution which i hate to suggest is to setup an open VPN client on the time clock that connects to the RaspberryPi bypassing the LAN router issues altogether.


How to check YouTtube videos URL is validation now?

Question: I have some code that check YouTube videos URL is valid in PHP.
<?php
      $rx = '~
      ^(?:https?://)?              # Optional protocol
       (?:www\.)?                  # Optional subdomain
       (?:youtube\.com|youtu\.be)  # Mandatory domain name
       /watch\?v=([^&]+)           # URI with video id as capture group 1
       ~x';

      $has_match = preg_match($rx, $vid1, $matches);
?>

it works similarly for this kind of URLs e.g.
https://www.youtube.com/watch?v=cpPG0bKHYKc
But it doesn't work correctly for some URLs such as:
https://youtu.be/auz2t9nBcwU
Comment: I'm gonna get correctly information and add video urls in my blogs.
Comment: As you know, https://youtu.be/auz2t9nBcwU is also valid video url in youtub but my module doesn't detect this is correction url.
Comment: $vid1 is video's url.
https://www.youtube.com/watch?v=cpPG0bKHYKc
Comment: Thanks, but second url is also valid, I think.
Let you try it.
Comment: You can get this url in Youtube video control > menu(right mouse click ) > copy url.
Comment: Thanks your advice.
But I don't understand.
Can you provide me more details code?
Comment: Posted an answer which I think explains what I mean... if not post a comment. If it explains and works please accept the answer.
Answer: As the comments in your regex state the protocol and subdomain are optional. Either form of the domain name is allowed. The last part of the regex is where you run into issues. The /watch\?v= then anything but an & is required. Your second URL doesn't have /watch in it. You could make the /watch optional but then youtube.com/anything would be allowed. I'd recommend putting the allowed formats in your alteration. Something like:
^(?:https?://)?(?:www\.)?(?:youtube\.com/watch\?v=([^&\n]+)|youtu\.be/([a-zA-Z\d]+))$

I think would do it for you.
Demo: https://regex101.com/r/TKPtPD/1
The [a-zA-Z\d]+ is also what appears to be the valid characters after the youtu.be domain. If more characters can be present you'll need to update that class.
Comment: It's really helpful for me.
Thanks a lot.


Como implementar o padrão DAO em subclasses?

Question: Estou desenvolvendo uma aplicação que se trata de uma loja de armas.
Possuo a classe Produto com as subclasses Arma, Faca e Municao. Neste projeto estou aplicando o padrão DAO, porém não entendi muito bem como funciona a sua aplicação em subclasses.
Possuo a classe ProdutoDAO:
public class ProdutoDAO implements GenericDAO<Produto> {

    Connection connection = null;

    @Override
    public void save(Produto produto) throws SQLException {
        try {
            connection = new ConnectionFactory().getConnection();
            String sql = "INSERT INTO PRODUTO(ID, ID_MARCA, DESCRICAO,"
                    + "PESO) VALUES (?, ?, ?, ?);"    ;
            PreparedStatement pstm = connection.prepareStatement(sql);
            pstm.setInt(1, produto.getId());
            pstm.setString(2, produto.getDescricao());
            pstm.setDouble(3, produto.getPeso());
            pstm.execute();
        } catch (SQLException sqle) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir o produto no "
                    + "banco de dados." + sqle.getMessage());
            sqle.printStackTrace();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Ocorreu um erro. Contate o suporte.\n" + ex.getMessage());
            ex.printStackTrace();
        } finally {
            connection.close();
        }
    }
}

A minha dúvida é em relação à classe ArmaDAO. Como devo implementá-la?
Ela deve estender a classe ProdutoDAO? A classe ProdutoDAO deve ser abstrata?
Answer: O padrão DAO é uma maneira de separar sua camada de persistência de dados das demais camadas. Entendo que organização pode ser feita da maneira que achar melhor.
Não me preocuparia em fazer nenhum tipo de herança entre estas classes. O assunto é extenso, mas herança é algo que precisa mais ser evitado do que usado.
Com isto em mente, considere criar um ArmaDAO separado. Se precisar algo do ProdutoDAO, considere usar ele dentro do ArmaDAO usando composição e não herança. Você não mencionou se está usando algum mecanismo de injeção de dependência, mas sua classe poderia ficar assim:
public class ArmaDAO implements GenericDAO<Arma> {

    @Autowired
    private ProdutoDAO produtoDAO; //usando ProdutoDAO dentro de ArmaDAO, sem herança, com composição

    public void salvarArma(Arma arma) {
         Produto produto = produtoDAO.buscar(); // buscar do ProdutoDAO
         // cria conexão e busca/salvar algo de Arma
    }

E sua classe ProdutoDAO continuaria basicamente como está.


how to create multi-page screen with libgdx scene2d?

Question: I want to create a multi-page level selection screen (just like in angry birds level selection) that user could navigate between pages by dragging (swiping) his/her finger on the screen horizontally.
I checked ui widgets in scene2d so I just found 'ScrollPane' that maybe useful but its functionality differs from what I want.
Anybody has any ideas?
Comment: As far as I know there is nothing built into LibGDX for this function. However, it is possible to implement this with input listeners and a ScrollPane. You would have to determine how many 'pages' you want and then build a table where each cell is the size of the pane. Then when a user does a 'flick' you would change the scrollX value to match what the next/previous page is.
Answer: nEx.Software has a nice little tutorial that explains how to do just this at http://nexsoftware.net/wp/2013/05/09/libgdx-making-a-paged-level-selection-screen/.  His solution involves extending ScrollPane to add paging functionality.
Answer: this is more simple:
http://moribitotechx.blogspot.co.uk/2012/09/23-tutorial-libgdx-mtx-test7levelscreen.html
good luck


Summation notation for the sum of roots of a polynomial N at a time

Question: I've been studying Vieta's formula and would like a to find the general Sigma notation for the sum of roots 2 at a time.
For example consider the the polynomial:
$$
  ( z - \alpha_1)( z - \alpha_2)( z - \alpha_3)( z - \alpha_4) = 0
$$
The roots are: $\alpha_1, \alpha_2, \alpha_3$ and $\alpha_4$.
The sum of the roots, taken 2 at a time is:
$$
   \alpha_1 \alpha_2 + \alpha_1 \alpha_3 + \alpha_1  \alpha_4 + \alpha_2 \alpha_3 + \alpha_2 \alpha_4 + \alpha_3\alpha_4
$$
I would like to express this in Sigma notation.  I presume a
$$
   \sum \sum \alpha_i\alpha_j
$$
is used but can't figure out the Sigma terminals.  Then extend this to $n$ roots.
Thanks in advance.
Comment: See https://en.wikipedia.org/wiki/Elementary_symmetric_polynomial
Comment: I was going to write an answer with a bunch of less than signs, but it's the very first equation in the page @MartinR linked. Go with that.
Answer: How about
$$\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \alpha_i \alpha_j.$$
Edit:  One way to wrestle with these things is to plot the subscripts as points.  In your example, you'd have
$$(1,2), (1,3), (1,4), (2,3), (2,4), (3,4).$$
If you plot those points, you get a nice triangle.  Then set up the limits of summation the way you would a double integral.
Comment: Thank-you so much for that information.  Neat!
Answer: $$
\alpha_1 \alpha_2 + \alpha_1 \alpha_3 + \alpha_1  \alpha_4 + \alpha_2 \alpha_3 + \alpha_2 \alpha_4 + \alpha_3\alpha_4
$$
is the second elementary symmetric polynomial $e_2(\alpha_1, \alpha_2, \alpha_3, \alpha_4)$. It can be expressed as
$$
e_2(\alpha_1, \alpha_2, \alpha_3, \alpha_4) = \sum_{1 \le i < j \le 4} \alpha_i \alpha_j \, .
$$
This notation easily extends to $n$ roots:
$$
e_2(\alpha_1, \ldots, \alpha_n) = \sum_{1 \le i < j \le n} \alpha_i \alpha_j
$$
and to products of higher degree:
$$
e_3(\alpha_1, \ldots, \alpha_n) = \sum_{1 \le i < j < k\le n} \alpha_i \alpha_j \alpha_k
$$
and generally
$$
e_k(\alpha_1, \ldots, \alpha_n) = \sum_{1 \le i_1 < i_2 < \cdots < i_k\le n} \prod_{j=1}^k  \alpha_{i_j}\, .
$$
Answer: There is a specific sum notation for this kind of summation. The symmetric sum notation $\sum_{\color{blue}{\mathrm{sym}}}$ is the sum over all permutations of the elements of a predefined set $S$. If we sum over a subset $T\subseteq S$ only, then this notation is used to sum over all $\binom{|S|}{|T|}$ subsets of size $|T|$ in $|S|$.

If $S=\{\alpha_1, \alpha_2,\alpha_3,\alpha_4\}$, then
\begin{align*}
\color{blue}{\sum_{\mathrm{sym}}\alpha_1\alpha_2}&
\color{blue}{=\alpha_1\alpha_2+\alpha_1\alpha_3+\alpha_1\alpha_4+\alpha_2\alpha_3+\alpha_2\alpha_4+\alpha_3\alpha_4}\\
&=\sum_{1\leq i< j\leq 4}\alpha_i\alpha_j
\end{align*}

Hint: Another specific sum notation used in a different context ist the cyclic sum notation $\sum_{\color{blue}{\mathrm{cyc}}}$, which is the sum over elements of a predefined set $S$ in a cyclic manner $\alpha_1\to \alpha_2\to \alpha_3\to \alpha_4\to \alpha_1$.
Comment: Very useful Markus.  Thank-you.
Comment: @Stephan: You're welcome. :-)


Phonegap link within page not working

Question: I have page in which has anchor tag. I have a button in the upper part of the page and when I click it I want the page to go to the bottom. So I have this
Click Upper
Some vertically long content....
Click Lower

When I click the Click Upper, it says 404 on the console

I even tried using id instead of name like so Click Lower
Not working either. My app is made of angularjs and typescript as well.
Comment: Could you try adding `target="_self"` in the `Click Upper` anchor tag?
Comment: It worked! You may want to put your comment as an answer
Answer: Try adding target="_self" in the Click Upper anchor tag.

Phonegap link within page not working


Metric on real line

Question:
Let $(X,d)$ be a metric space and fix some $x_{0}\in X$. Show that the function $f(x) = d(x_{0},x)$ is Lipschitz continuous?

My problem wasn't with solving the question originally I did that using the triangle inequality and showing $\lvert f(x) - f(y)\rvert\le d(x,y)$, but the definition for Lipschitz continuity is $d_Y(f(x),f(y))\le K d_X(x,y)$ where $K > 0$, why can we assume that $d_Y$ is the the euclidean metric?
Comment: It's implicit in the problem: $f:X\to\mathbb R$, is a real function, so it is natural to use the standard metric on $\mathbb R$, which is $d_{\text{Eucl}}(a,b)=|a-b|$.
Answer: It is always the metric of your image space you need to look at. And since there was no other metric on $\mathbb{R}$ given, which is apparently the image space of $f$, one implicitly means the standard metric, i.e. the Euclidean one.
Comment: Yeah, but I thought he/she already got that.
Comment: And then we just take $K=1$ as well.

Metric on real line


Symlink not updating as expected when using an absolute with relative path

Question: I am trying to use symbolic links. I did some reading and found the following commands:
Creation -> ln -s {/path/to/file-name} {link-name}
Update -> ln -sfn {/path/to/file-name} {link-name}
Deletion -> rm {link-name}

Creations and deletions work fine. But updates do not work. After performing this command, the symlink becomes invalid.
I have read here and there that it is not possible to update/override a symlink. So there is contradictory information on the net. Who is right? If a symlink can be updated/overridden, how can I achieve this?
Update
Here is my directory structure:
~/scripts/test/
~/scripts/test/remote_loc/
~/scripts/test/remote_loc/site1/
~/scripts/test/remote_loc/site1/stuff1.txt
~/scripts/test/remote_loc/site2/
~/scripts/test/remote_loc/site2/stuff2.txt
~/scripts/test/remote_loc/site2/
~/scripts/test/remote_loc/site3/stuff3.txt

From ~/scripts/test/, when I perform:
ln -s /remote_loc/site1 test_link

a test_link is created, and I can ls -l it, but it seems broken (contrary to what I said above in my question).
How can I perform a multiple directory level link?
Comment: I recommend to use `unlink` instead of `rm`. With `unlink` you never risk to lose any files in a source directory by accidentally using wrong switches.
Comment: Why use of `-n`? (may be the problem). Also if your ln supports `-t` then use it, for these cases, and `-T` or `destination/` for other cases.
Comment: You are using a leading / in your command
Comment: @jpsy your advice about unlink would be very good, **if it was true**. Try touch zzzz; unlink zzzz. (unlink calls, unlink same as rm, but with no fancy options, and no recursion).
Answer: Using -f with ln will overwrite any link that was already there, so as long as you have the correct permissions, it should work... It's always worked for me. What operating system are you using?
Comment: Does not work. Needs `-n`. See accepted answer.
Comment: MacOS requires `-n` to update.
Comment: If you switch the `ln` parameters, as I am prone to do, will the `-f` switch destroy your existing files (link targets)? In either case, we have the `-i` parameter (which will prompt the user for overwrite) as well, if you want a bit of security.
Comment: @palswim This SO post implies it is safe because `-f` just calls `unlink()` and `link()` under the hood: http://stackoverflow.com/a/1466570/157385. I do wish I'd just remember the correct order, though!
Comment: I have updated my question with more information on my issue.
Comment: I am under linux.
Comment: -f does NOT unlink (at least not generally), refuted on Raspian.
Comment: Sorry to be picky but which Linux? is it a Gnu/Linux or non-Gnu Linux (such as android)?
Comment: I used `rm syslink` then creation and it worked. I think the fact the linked folder has a different user made it fail although I tried with root beforehand. super strange.
Comment: As for remembering the correct order, just remember it goes `ln -s source destination`
Answer: Ok, I found where my error is: one should not put the first / in path.
In other words, the commands in my questions should be:
Creation -> ln -s {path/to/file-name} {link-name}
Update -> ln -sfn {path/to/file-name} {link-name}

instead of
Creation -> ln -s {/path/to/file-name} {link-name}
Update -> ln -sfn {/path/to/file-name} {link-name}

considering my case.
Comment: For some additional information on why that is, the differences are one is a `relative` path (without the leading /) and the other is an `absolute` path (with the leading /). If you're administrating a Linux system it is CRITICAL that you understand the differences. For instance the difference between `rm -rf ./*` and `rm -rf /.*` decides whether you keep your job or not :)
Comment: -n  (--no-dereference) makes it treat {link name} like a normal file rather than following the link. Given that you need to operate on that link not follow it you must use this option.
Comment: This doesnt answer the question 'how to update/overide a sym link'
Comment: This answer should be highlight answer with `-n` parameter for replacing symbol link.
Comment: The ln -sfn {path/to/file-name} {link-name} line does.
Comment: What difference does the `-n` option make?
Comment: This worked for my to update symbolic link for my CentOS 7 system.
Answer: First issue:
Quoting you:

Creations and deletions work fine. But updates do not work. After
  performing this command, the symlink becomes invalid.

The problem With the given directory structure:

~/scripts/test/ ~/scripts/test/remote_loc/
  ~/scripts/test/remote_loc/site1/
  ~/scripts/test/remote_loc/site1/stuff1.txt
  ~/scripts/test/remote_loc/site2/
  ~/scripts/test/remote_loc/site2/stuff2.txt
  ~/scripts/test/remote_loc/site2/
  ~/scripts/test/remote_loc/site3/stuff3.txt

and using the command:

ln -s /remote_loc/site1 test_link

Is that it creates a symbolic link in your $PWD, or present working directory, that points to a non-existing file off the /, or root, at /remote_loc/site1
If your PWD is in ~/scripts/ then you should have used this:
ln -s remote_loc/site1 test_link
else you could have used the full absolute path like:
ln -s /home/yourusername/remote_loc/site1 test_link
Second issue:
Quoting you:

I have read here and there that it is not possible to update/override
  a symlink. So there is contradictory information on the net. Who is
  right? If a symlink can be updated/overridden, how can I achieve this?

To answering your question "Who is right", I am not sure what exactly you read, or how it was understood. But, the following should help clear up:

What can be updated, and
What can not be updated without using
appropriate switches.

Updating symbolic links with targets that are not directories.

ln -sf:
  The -f or  --force remove existing destination files, This is used to update a link's target or destination.

Example:
 ln -sf /tmp/test /tmp/test.link; ls -go /tmp |grep test
 -rw-r--r-- 1    0 Jun  8 17:19 test
 lrwxrwxrwx 1    9 Jun  8 17:27 test.link -> /tmp/test

But, as you can see, it will give the absolute path if absolute paths are in ln's arguments. Giving a full path is necessary when the present working directory is different than the link's parent directory.

Relative Paths:

ln -sfr:
  The -r or --relative creates symbolic links relative to the link's location.

Example:
ln -sfr /tmp/test  /tmp/test.link  ; ls -go /tmp| grep test
-rw-r--r-- 1    0 Jun  8 17:19 test
lrwxrwxrwx 1    4 Jun  8 17:27 test.link -> test

But, updating a link to a directory will not work if the target is a directory.
Example:
ln -sf /tmp/testdir  /tmp/testdir.link  ; ls -go /tmp  |grep testdir
drwxr-xr-x 2 4096 Jun  8 17:48 testdir
lrwxrwxrwx 1    7 Jun  8 17:47 testdir.link -> testdir

As you can see, despite using absolute path names given in ln's argument above without the -r option, the symbolic link is still relative to the link.

Update Links to Directories:

ln -sfrn:
  The -n or --no-dereference treats LINK_NAME as a normal file if it is a symbolic link to a directory.

Example:
ln -sfn /tmp/testdir /tmp/testdir.link; ls -go /tmp| grep testdir
drwxr-xr-x 2 4096 Jun  8 17:48 testdir
lrwxrwxrwx 1   12 Jun  8 17:48 testdir.link -> /tmp/testdir

As contrasted with:
ln -sfnr /tmp/testdir /tmp/testdir.link; ls -go /tmp| grep testdir
drwxr-xr-x 2 4096 Jun  8 17:48 testdir
lrwxrwxrwx 1    7 Jun  8 17:48 testdir.link -> testdir

Answer: $ touch test1 test2
$ ln -sf test2 test1
$ ls -l test[12]
lrwxrwxrwx 1 user01 user01 5 2012-05-17 14:41 test1 -> test2
-rw-r--r-- 1 user01 user01 0 2012-05-17 14:41 test2

Comment: When I perform tests with 1 level of directory, it works, but I am trying to use multi-level directories, and it does not work. I have updated my question.


Uso do SQLite Android

Question: Desenvolvi dois aplicativos para aprender Android e usei banco de dados MySQL. Até agora não encontrei necessidade de usar o SQLite e para ser sincero não entendi nem mesmo o porquê de sua existência.
Qual a utilidade do SQLite em um projeto?
Comment: SQLite é salvamento local, MySQL é remoto. Se você está utilizando MySQL para salvamento local, você está fazendo errado. É uma péssima abordagem.
Comment: Acho que me expressei errado, não utilizo o MySQL para salvamento local.
Answer: Em geral é usado para armazenar dados da aplicação no próprio dispositivo, como todo banco de dados.
Se não está fazendo isto deve retirar qualquer referência a ele na aplicação cliente que vai rodar no dispositivo.
Dê uma lida na perguntas sobre o SQLite aqui. Várias delas são sobre o uso no Android.
Só espero que esteja usando o MySQL no servidor e não no app.
Comment: Não use o MySQL no dispositivo. O SQLite é o disparado o banco de dados mais usado no mundo, deve ter bilhões de bases rodando nele. Eu uso até no servidor, mas não recomendo para iniciantes. Em cliente, desktop ou mobile a maioria das aplicações usa. Dê uma pesquisada na *tag* https://pt.stackoverflow.com/questions/tagged/sqlite?sort=votes&pageSize=50. Agora você pode votar em tudo no site também.
Comment: O SQLite tem suporte nativo no Android para armazenar dados no próprio dispositivo.

Uso do SQLite Android


How many nonprincipal ultrafilters exists on $X$ such that $|X|^2=|X|$?

Question: Let $X$ be an infinite set, idemmultiple ($|X|^2 = |X|$) if that helps.  I am looking for a proof that $X$ has more than $|X|$-many ultrafilters.  It has $|X|$-many principal ultrafilters. Without at least some AC I know of no proof that $X$ must have any non-principal ultrafilters.  So let us assume BPI, the Prime ideal theorem.  If we assume BPI can we prove $|\beta X| > |X|$?   ($\beta X$ is of course the set of ultrafilters on $X$).  If we have AC then it is standard that $|\beta X| = 2^{2^{|X|}}$.  I don't much mind which set theory we work in (the question actually arose in NF, with $X = V$) co's it's the construction (if any) that I am after.
Summary: i am interested in a proof (no theory specified) that BPI implies that an idemmultiple (infinite) set $X$ has more than $|X|$-many ultrafilters
Comment: My hunch is that BPI is so close to AC that the number of ultrafilters is the same under either.
Comment: If I remember correctly, the usual proof of $|\beta X|=2^{2^{|X|}}$ uses AC only in the form of BPI and the statement that $X$ is in bijection with the set of finite subsets of $X$.
Comment: Oh, hrm, the usual proof constructs a *surjection* from $\beta X$ to $P(P(X))$; getting an injection the other way seems to require more.
Answer: Recall the usual proof of $|\beta X|=2^{2^{|X|}}$ using AC.  To sketch the argument, you replace $X$ with the set $Y$ of pairs $(A,S)$ where $A$ is a finite subset of $X$ and $S$ is a finite set of finite subsets of $X$.  Then, you explicitly construct a family of $2^{2^{|X|}}$ pairwise incompatible filters on $Y$, and extend them each to ultrafilters.  This gives $2^{2^{|X|}}$ different ultrafilters on $Y$, and hence on $X$ since $|X|=|Y|$.
With a bit of care, you can make this argument still work using only BPI and $|X|^2=|X|$.  First, we still have $|X|=|Y|$.  To prove this, note that we can totally order $X$ by BPI, and so from $|X|^2=|X|$ we can obtain a family of injections $[X]^n\to X$ for each finite $n$.  Also, $|X|^2=|X|$ implies $\aleph_0\leq |X|$ so $|X|\times\aleph_0\leq |X|^2=|X|$.  Thus $|X|\leq [X]^{<\omega}\leq|X|\times\aleph_0=|X|$, and so $|Y|=|[X]^{<\omega}\times[[X]^{<\omega}]^{<\omega}|=|X|^2=|X|$.
Now, using BPI, we can extend each of our filters on $Y$ to an ultrafilter.  In fact, we can actually extend them simultaneously to get a family of $2^{2^{|X|}}$ different ultrafilters on $Y$, proving that $|\beta X|=|\beta Y|=2^{2^{|X|}}$.  More generally, suppose you have a family $(B_i)_{i\in I}$ of nonzero Boolean algebras and you wish to find ultrafilters on all of them simultaneously.  Let $B$ be the free product of the $B_i$.  Then $B$ is a nonzero Boolean algebra: if we had $1=0$ in $B$, then we would have $1=0$ in the free product of some finitely many $B_i$ (since $B$ is the direct limit of the finite free products), but that is impossible (for instance, by picking ultrafilters on those finitely many $B_i$ to get a homomorphism from their free product to $\{0,1\}$).  Thus by BPI, $B$ has an ultrafilter, and it can be pulled back along the canonical homomorphisms $B_i\to B$ to get a family of ultrafilters on each $B_i$. (Thanks to Andreas Blass for providing a variant of this argument in the comments.)
Comment: +1. Actually, BPI does let you extend a lot of filters $F_i$ on sets $S_i$ (for $i\in I$) to ultrafilters simultaneously. The idea is to pull the given filters $F_i$ back to filters on $S=\prod_{i\in I}S_i$ and use those to generate a single filter $F$. That is, writing $p_i$ for the projection $S\to S_i$, let $F$ be generated by all the sets $p_i^{-1}(Z)$ for $i\in I$ and $Z\in F_i$. Then if $U$ is an ultrafilter on $S$ extending $F$, its images $p_i(U)$ extend the $F_i$'s.
Comment: @AndreasBlass: Ah, that's very nice.  In algebraic terms, if you have a family of nonzero Boolean algebras $B_i$, you can take the free product $B$ of the $B_i$ which will be nonzero, and then an ultrafilter on $B$ gives an ultrafilter on each $B_i$.
Comment: Thanks very much for prompt and helpful response, Eric.  Let me chew this over.  Thank you.
Comment: Forgive my obtuseness, Eric,---and thank you again---but i haven't got my copy of Jech here (I'm out in the jungle).  Your set $Y$ is clearly a key feature.  What are the multitudinous filters on it that you construct explicitly?
Comment: See https://math.stackexchange.com/questions/2999390/how-many-ultrafilters-there-are-in-an-infinite-space for instance.
Comment: That's nice....


How can I improve this glm and do I need to dummy code?

Question: I have percentage disease data taken from leaves of wheat in a disease trial which were artificially inoculated with isolates of disease from different source plants.
The basic question is, are disease isolates sourced from the same cultivar better at infecting those cultivars? We are looking for an interaction.
I am trying to conduct a logit linked beta glm to determine if there is an interaction between the source cultivar variable and the inoculated host cultivar variable.
My model looks something like this:
beta_model=betareg(mean.proportion.disease ~ Source.CV + inoculant.Host +
                 Source.CV*Inoculant.Host, data = study, link =c('logit'))

I have also tried a binomial glm:
binom_model = glm(mean.proportion.disease ~ Source.CV + inoculant.Host +
                 Source.CV*Inoculant.Host,
               data = study, family = binomial(link = 'logit'))

Both models give me residuals that look like this:

Is there any way I can improve on this and get normal residuals?
I might also be worth noting that there are a few zeros in my data so proportions are transformed according to:  $(y*(n-1)+0.5)/n)$.
Lastly, you've probably already guessed I am a beginner in this realm of statistics, and as such I'm thinking about glm's in the context of simple linear regression. So I can't really understand what the intercept in glm output is telling me, if anyone can help me with this I'd very grateful.
Any comments appreciated.
Comment: Given the name of you outcome variable, `mean.proportion.disease`, and the beta-distribution tag, I assume that this variable is measured on a 0-1 scale. So may I ask why you are using logit here?
Comment: To me it looks like there are naturally occurring groupings in the data that need to be accounted for by your model. Can you relate these residuals back to their source?
Comment: thank you for your comments. the groupings probably relate to the three inoculant host plants used in the trial. there were three, one very susceptible to the disease, one moderately resistant, and one very resistant. this would result in proportions that could be grouped as high, medium, and low. variance about these proportions probably reflect this. in answer to why i used logit i'm afraid i must plead ignorance, this model has been succesfully constructed in sas by our resident statistician, and i am now trying to implement it in r as i know nothing about sas. in his sas he used logit.
Comment: A logit link is perfectly acceptable for modelling a percent or proportion, even one that is continuous. If some previous comments are implying that you must have 0, 1 data, that is not the case.
Comment: It looks as if you are already averaging somehow, because your response is `mean.proportion.disease`. Is that so? Otherwise put, what is a data point, or a raw observation? Is it a leaf, diseased or not?
Comment: the disease proportions used in the data set are average percentage disease of six leaves taken from the same plant treatment. with respect to the experimental design each mean is an individual combination of isolate source and inoculant host.
Answer: In your case, "typical" regression methods aren't appropriate since your dependent variable is bounded below at 0 and above at 1. You probably want to consider some type of truncated regression appropriate for limited dependent variables such as this. Here's a Wiki reference that has some use in explaining the motivations for using these functional forms:
https://en.wikipedia.org/wiki/Truncated_regression_model
Broadly speaking, truncated regression is a subset of generalized linear modeling whose development spans separate disciplines such as biology, economics and statistics. Maddala's more than 30 year old book Limited-Dependent and Qualitative Variables in Econometrics is the canonical source for a discussion of these topics:
http://www.amazon.com/Limited-Dependent-Qualitative-Econometrics-Econometric-Monographs-ebook/dp/B00IE6MRUI/ref=sr_1_1?s=books&ie=UTF8&qid=1446038429&sr=1-1&keywords=qualitative+and+limited+dependent+variables
However, it's a field that has exploded since his book was written and I would be hard-pressed to give you a single reference that summarizes all of the issues, particularly from a bio-statistics POV.
One tip would be to look into beta-binomial models which are a form of probabilistic (i.e., bounded or truncated) modeling that may be appropriate for your percentages. This could leverage an R module designed to integrate the compound function, as opposed to two separate modules as developed here:
https://cran.r-project.org/web/packages/bbmle/vignettes/mle2.pdf
Comment: But the OP is not using typical regression methods at all. The logit link is tailor-made for the bounds of [0, 1] or [0, 100%]. I think you need a really strong case that truncated regression is even competitive with that kind of approach, let alone superior. The answer doesn't really address this comparison. Moreover, truncated regression can, I suggest, only with extreme difficulty be shoe-horned into the generalized linear model framework: what link function would you say it was using?
Comment: (Naturally other links such as probit, loglog, cloglog could also make sense for bounded proportions.)
Comment: In short, no. You have already sprinkled many of your answers and comments on CV with candid criticisms of various kinds and given that you reasonably ask me to clarify, then I will do the same here. My own opinion is that only the beta-binomial suggestion in your answer looks at all related to the question. The other comments on truncated regression are, it seems,  based on misreading the question or to me not yet shown to be related to the question. Any function for a response that doesn't change behaviour as it approaches result 0 or result 1 is utterly unbiological (in this case).
Comment: I think it would be difficult to make a case that a truncated regression model is appropriate for such data, but maybe I have overlooked some nuance. Is there any truncation mechanism at work here?  Or are you proposing this model not because it is suggested by the circumstances, but simply because maybe it would work? In either case, it would seem important to provide some elaboration.  (cc @NickCox)
Comment: Ah! "Truncation mechanisms" That focuses the discussion on the real merits of the suggestion. No, there doesn't seem to be a truncation mechanism at work here, merely that the data is bounded at 0 and 1. Thanks.
Comment: @NickCox Evidently I misread his comments. I thought he was using a functional form which presumed a 0,1 target variable and my response is couched with that assumption
Comment: Percentage disease and logit link GLMs are clearly explained in the post.
Comment: @NickCox  Not everyone is as lucid a reader of the same information, which a more careful parsing on my part would have uncovered. By way of a mea culpa, it looked to me as though the OP was executing separate models for each step of a compound process. Hence, the reference to the complete beta-binomial R module at the end.
Comment: Quite so. But I suggest that some editing of your answer would bring it closer to the question.
Comment: @NickCox  That's a reasonable suggestion, I'm sure, if one agrees with you that truncated models are inferior or less than competitive. The OPs challenges do not lend themselves to cookbook recipes where the answers can be looked up in the back of a text. In addition, I'm sure you'll agree that your opinions in this regard is one among many and that proponents of the methodology might take issue. In my view, my response is valid and suggestive of possible approaches to try, one's that you don't agree with. That being said, are you suggesting that I edit out the word "typical?" I can do that
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/30824/discussion-between-djohnson-and-nick-cox).
Comment: Thanks; I would rather that the discussion remain for others to judge and comment if and as they see fit.
Comment: Fair enough! And it's true about my "candid" comments. "Criticisms" is a somewhat more loaded, adjudicating choice of words reflecting of a bias or disapproval on your part. As far as I'm concerned, I'm not wedded to any method one way or the other. It was merely a thought and a suggestion, again, one that you don't agree with based on your, evidently, superior knowledge of the methodologies. For my part, I'm interested in understanding more about your objections to it from an applied POV with an emphasis on the practicality of the approaches.
Comment: The criticisms referred to were yours, e.g. a comment on "siloed experts of each discipline", where I happen to agree strongly, although the style is not quite mine. No matter; in this case, the absence of a dataset inhibits play and experimentation, but my experience is that the functional form is usually more important than which distribution family one posits. The point about link functions adjusting to the boundaries is not mine but standard across biostatistics, for example.
Comment: Cool. You have a lot of knowledge to share and I welcome the opportunity to absorb that sort of thing. Actually, this is the single biggest reason why I, personally, have chosen to participate on CV -- to learn and to share. So, thank you for that. I'm relieved to note that you didn't think my suggestion was "wrong," merely that it was...sub-optimal?
Comment: The "candid" comment where I really pushed the line was probably the one about "naive" questions wrt factor analysis...I held my breath on that one.


Serial Port Send Data in VB.NET with Packed message

Question: I have the Manual of Programming protocol,  but when I write code vb.net returns error message.
The following is the table structure of bytes array
position    1      2      3      4      5      6      7  8
Name        SOH    LEN    SEQ    CMD    DATA   Post-amble     BCC    ETX
Lenth/bytes 1  1      1      1      0-200      1      4      1
Value   (01h)   (20h-FFh)   (20h-FFh)   (20h-FFh)   (20h-FFh)   (05h)   (30h-3Fh)   (03h)
Abbreviations:
"SOH"- (Start Of Heading) start of packed message
"LEN"- total number of bytes from position 2 to position 6, plus fixed offset of 20h.
"SEQ"- serial number of packet. SLAVE puts the same "SEQ" in the reply message. In case when SLAVE
receives a message with the same "SEQ"and "CMD" like the last correctly received message, the device ignores
the message and repeats the last packet sent to the HOST.
"CMD" – code of command
"DATA"- data, according to the command. If there is no data, the length field is zero.
"BCC" – control sum(0000h-FFFFh). Sum of data bytes from position 2 to position 6. The control sum is
transferred in ASCІІ type (12АВ is transferred as 31h 32h 3Аh 3Вh).
"ETX" – (End of TeXt) end of packed message.
Codes sample:
Public Class Form1
Private WithEvents sp As System.IO.Ports.SerialPort

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    For Each y As String In System.IO.Ports.SerialPort.GetPortNames
        Me.ComboBox1.Items.Add(y)
    Next
    sp = New IO.Ports.SerialPort("COM4")
    sp.StopBits = IO.Ports.StopBits.One
    sp.BaudRate = 9600
    sp.DataBits = 8
    sp.Parity = IO.Ports.Parity.None
    sp.Handshake = IO.Ports.Handshake.None

    sp.Open()
    Dim by As Byte = &H20

    ' MsgBox(&H20)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Dim By(9) As Byte
        By(0) = 1
        By(1) = &H2 + &H20
        By(2) = &H58
        By(3) = &H45
        By(4) = &H5
        Dim S As String = Hex(&H58 Xor &H45)
        '  MsgBox(S)
        By(5) = &H30
        By(6) = &H30
        By(7) = &H31
        By(8) = &H3D
        By(9) = &H3

        sp.Write(By, 0, By.Length - 1)
       ' MsgBox(sp.ReadByte)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
    Dim rec As System.IO.Ports.SerialPort = sender
    MsgBox(Hex(rec.ReadByte))
End Sub

End Class
Comment: Could you rewrite the question? It's difficult to understand what you're asking for.
Comment: I have EFD machine from daisy technologies (e xpert SX) am writing code in vb.net to send command. One of command code is 45h to print z report. I tried to write code as shown above but returns error. may be because of BCC. I don't know. Please healp.
Comment: There are a *lot* of things wrong with this code.  You should not hard-code the values.  SEQ number needs to be a variable for example.  BCC needs to be calculated.  The most glaring thing you got wrong is the sp.Write() call, don't subtract 1 from by.Length
Comment: Thank you Hans Passant. Could you give me some example of this problem?
Answer: Annael you could probably do this, by invoking an updating function and giving a delay of 500ms will make a difference. Now on receiving data you can receive input data
Dim inputData As String = ""// Declare this as a global variable in the program
    Private WithEvents sp As System.IO.Ports.SerialPort

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   For Each y As String In System.IO.Ports.SerialPort.GetPortNames
            Me.ComboBox1.Items.Add(y)//the code you have written to add Serial ports

SerialPort1.PortName = ComboBox1.Text//this will access your com port as your button
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim by As Byte = &H20
                By(0) = 1
                By(1) = &H2 + &H20
                By(2) = &H58
                By(3) = &H45
                By(4) = &H5
                Dim S As String = Hex(&H58 Xor &H45)
                '  MsgBox(S)
                By(5) = &H30
                By(6) = &H30
                By(7) = &H31
                By(8) = &H3D
                By(9) = &H3
            SerialPort1.BaudRate = 115200
            SerialPort1.Open()
            SerialPort1.Write(By)
        Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

            Threading.Thread.Sleep(500) ' 500ms delay induced to receive the email
            inputData = SerialPort1.ReadExisting 'or SerialPort1.ReadLine

            Me.Invoke(New EventHandler(AddressOf DoUpdate))

    Public Sub DoUpdate()

                MsgBox(inputData)


MGF of Poisson Z=X+2Y

Question: If $X\sim P(2)$ and $Y \sim P(3)$ using the moment generating function, what kind of distribution has random variable $Z=X+2Y$.
So far as I know :
$$
M_X(t)=e^{-\lambda(1-e^t)}=e^{-2(1-e^t)}
$$
$$
M_Y(t)=e^{-\lambda(1-e^t)}=e^{-3(1-e^t)}
$$
$$
M_{2Y}(t)=e^{-\lambda(1-e^t)}=e^{-3(1-e^{2t})}
$$
$$
M_{X+Y}(t)=e^{-5(1-e^t)}
$$
Since
$$
X+Y \sim P(\lambda_1+\lambda_2)
$$
so I am guessing that $$ Z=X+2Y \sim P(\lambda_1+2\lambda_2)$$ but I can find it from the equation
$$M_{X+2Y}(t)=e^{-2(1-e^t)} e^{-3(1-e^{2t})}=e^{(-2(1-e^t)-3(1-e^{2t})}$$
I don't know how to rearrange this equation to get the distribution.
How to get rid of "$2t$".
Comment: Your guess is incorrect, unfortunately. $2Y$ is not distributed as Poisson.
Comment: The easy way to see that Z can't be Poisson is to compute the mean and variance. If it were, the mean and variance would be the same. Out of curiosity, what makes you certain that Z has a distribution that you know a name for?
Comment: @Tim Yes,i know, I had written in my question. I also edited. But my question is about Z=X+2Y since it doesn't have Poisson ~ (λ1+2λ2). I wrote the MGF for Z but i can't see it the answer from there.
Comment: @Glen_b That's why i asked here, that was the simplest thing I could conclude as my answer. I wrote the MGF of the variable Z=X+2Y but from there i don't know how to rearrange to get MGF of some known distribution
Comment: @Cherryl I made few improvements in the formatting - please check if there is no mistakes.
Comment: @Glen_b  Since i calculated the MGF of Z=X+2Y how can i use it get the distribution ? Obviously is not one from the familiar distributions.
Comment: Notionally, you can invert the transformation (though I don't know whether you'll necessarily end up with any nice closed-form). Have you seen Laplace transforms? The MGF is a Laplace transform (up to a sign flip of the argument), and you can apply the inverse Laplace transform (keeping the sign flip again) to get back to the original probability function. Alternatively you might try to use pgfs or even discrete convolution
Answer: No, your $Z=X+2Y$ will not have a poisson distribution (you should expect it to have to small point probabilities at odd integers, and too high at even, compared to Poisson).
You didn't really say that $X$ and $Y$ are independent, but I will assume so much.  EDIT: I found that this distribution is known as the Hermite distribution.
For this problem it will be convenient to use pgf's (probability generating function). The pgf for a Poisson variable with parameter $\lambda$ is $\DeclareMathOperator{\E}{\mathbb{E}}G(z)=\E z^X=e^{\lambda (z-1)}$. Then we calculate the pgf of $Z$ as
$$
 G_Z(z)= \E e^{X+2Y} = \E z^X \cdot \E e^{2Y}=G_X(z)G_Y(z^2)
$$
and inserting the parameter values 2 for $X$, 3 for $Y$ we get
$$
   G_Z(z)=\exp\left\{  2(z-1)+3(z^2-1) \right\}
$$
which certainly is not the pgf of any Poisson random variable.
We can find the probability mass function by expanding the pgf in a power series. I will use maple:
G := z -> exp( 2*(z-1) + 3*(z^2-1) )
                              /             2\
                 G := z -> exp\2 z - 5 + 3 z /
S1 := series(G(z), z=0, 100) :
S2 :=  sort( convert(S1,polynom) ) :
ps := map(i -> coeff(S2,z,i), [seq(i,i=0..99)]) :
add(ps)
1230201581592231835090021705882732508724506091485915653564875278\

  48000526534413904564309823833442956185744700756387658829897786\

  002504758907395407/8289033054959573892412837535227749840302277\

  58541379236843775436718019022859048977460196496524216398837958\

  212205265551360000000000000000000000 exp(-5)
evalf(%)
                          1.000000000
evalf(ps)
[
[0.006737946999, 0.01347589400, 0.03368973500, 0.04941161132,

  0.07524040818, 0.08939009688, 0.1050371071, 0.1066306851,

  0.1054355016, 0.09451723482, 0.08216474795, 0.06649390044,

  0.05216469070, 0.03871482954, 0.02788698595, 0.01920419661,

  0.01285814431, 0.008290674603, 0.005207234170, 0.003166237682,

  0.001878794019, 0.001083572101, 0.0006109049235,

  0.0003357931503, 0.0001807089934, 0.00009504707551,

  0.00004901338891, 0.00002475219374, 0.00001227088289,

  0.000005967411318, 0.000002852003999, 0.000001338983094,

                -7                -7                -7
  6.184371932 10  , 2.809325136 10  , 1.256614172 10  ,

                -8                -8                -8
  5.534051189 10  , 2.401804243 10  , 1.027240962 10  ,

                -9                -9                -10
  4.332975626 10  , 1.802574590 10  , 7.400750733 10   ,

                -10                -10                -11
  2.998926265 10   , 1.200056117 10   , 4.742713913 10   ,

                -11                -12                -12
  1.852018065 10   , 7.146737691 10   , 2.726403463 10   ,

                -12                -13                -13
  1.028366661 10   , 3.836490437 10   , 1.415815929 10   ,

                -14                -14                -15
  5.170114897 10   , 1.868415403 10   , 6.684138498 10   ,

                -15                -16                -16
  2.367418890 10   , 8.303642362 10   , 2.884589421 10   ,

                -17                -17                -17
  9.926970182 10   , 3.384724660 10   , 1.143642594 10   ,

                -18                -18                -19
  3.829768330 10   , 1.271301538 10   , 4.183805419 10   ,

                -19                -20                -20
  1.365253276 10   , 4.417990328 10   , 1.417987144 10   ,

                -21                -21                -22
  4.514448654 10   , 1.425880696 10   , 4.468425869 10   ,

                -22                -23                -23
  1.389554316 10   , 4.288357079 10   , 1.313571045 10   ,

                -24                -24                -25
  3.993983741 10   , 1.205586530 10   , 3.613024042 10   ,

                -25                -26                -27
  1.075151891 10   , 3.177126405 10   , 9.324127135 10   ,

                -27                -28                -28
  2.717868033 10   , 7.869294731 10   , 2.263426221 10   ,

                -29                -29                -30
  6.467827602 10   , 1.836311462 10   , 5.180437626 10   ,

                -30                -31                -31
  1.452283891 10   , 4.046094469 10   , 1.120343793 10   ,

                -32                -33                -33
  3.083401674 10   , 8.435336890 10   , 2.294031526 10   ,

                -34                -34                -35
  6.202256673 10   , 1.667182276 10   , 4.455813691 10   ,

                -35                -36                -37
  1.184158304 10   , 3.129376210 10   , 8.224281987 10   ,

                -37                -38                -38
  2.149590912 10   , 5.588007681 10   , 1.444860516 10   ,

                -39                -40]
  3.716098685 10   , 9.507457408 10   ]

Answer: Taking the characteristic functions of the underlying random variables you have:
$$\begin{equation} \begin{aligned}
\varphi_X(t) &= \exp \Big( 2 (e^{it}-1) \Big), \\[6pt]
\varphi_{2Y}(t) &= \exp \Big( 3 (e^{2it}-1) \Big). \\[6pt]
\end{aligned} \end{equation}$$
Assuming that $X$ and $Y$ are independent, you then have:
$$\varphi_Z(t) = \varphi_{X}(t) \cdot \varphi_{2Y}(t) = \exp \Big( 3 e^{2it} +2 e^{it} -5 \Big).$$
The distribution of $Z$ can be obtained by inverting the characteristic function via standard methods for inverse-Fourier transformation.  Using a well-known inversion formula we have:
$$\begin{equation} \begin{aligned}
p_Z(z)
&= \lim_{T \rightarrow \infty} \frac{1}{2T} \int \limits_{-T}^{+T} e^{-itz} \varphi_Z(t) dt \\[6pt]
&= \lim_{T \rightarrow \infty} \frac{1}{2T} \int \limits_{-T}^{+T} \exp \Big( 3 e^{2it} +2 e^{it} - itz -5 \Big) dt \\[6pt]
\end{aligned} \end{equation}$$
This integral is hard to solve, so it is easier to proceed in this case by taking a standard convolution.  Doing this yields the closed form solution:
$$\begin{equation} \begin{aligned}
p_Z(z)
&= \sum_{y=0}^{\lfloor z/2 \rfloor} p_Y(y) \cdot p_X(z-2y) \\[6pt]
&= \exp(-5) \sum_{y=0}^{\lfloor z/2 \rfloor} \frac{3^y 2^{z-2y}}{y! (z-2y)!} \\[6pt]
&= 2^z \exp(-5) \sum_{y=0}^{\lfloor z/2 \rfloor} \frac{(\tfrac{3}{4})^y}{y! (z-2y)!}. \\[6pt]
\end{aligned} \end{equation}$$
You can create a function for this PMF in R as follows:
#Create probability mass function for Z
PMF <- function(z) { YY <- floor(z/2);
                     Y <- 0:YY;
                     for (i in 0:YY) { Y[i+1] <- dpois(i, 3)*dpois(z-2*i, 2); }
                     sum(Y); }

#Create data frame of PMF values from Z = 0,...,25
ZZ   <- 25;
Z    <- 0:ZZ;
Prob <- rep(0,length(ZZ));
for (z in 0:ZZ) { Prob[z+1] <- PMF(z) }
DATA <- data.frame(z = Z, Prob =  Prob)

#Plot the PMF
library(ggplot2);

FIGURE <- ggplot(data = DATA, aes(x = z, y = Prob)) +
          geom_bar(stat = 'identity', fill = 'red') +
          theme(plot.title = element_text(hjust = 0.5, face = 'bold')) +
          ggtitle('Probability Mass Function') +
          xlab('z') + ylab('Probability');
FIGURE;

MGF of Poisson Z=X+2Y


colorbox breaks on rel attribute when bxslider is loaded

Question: After much debugging I came to the conclusion these two libraries are colliding. I tested them both separate and they work but when used together (and there is a rel attribute things break)
How to reproduce

If the link has a rel or $('something').colorbox({rel:'something'});
$('somethingelse').bxSlider(...);

colorbox will fail when clicking on any image that has colorbox (not just the shared options) With:

Uncaught TypeError: Cannot read property 'rel' of undefined

Offending lines of code are:

<code>      if (settings.rel !== 'nofollow') {
          $related = $('.' + boxElement).filter(function () {
              var relRelated = $.data(this, colorbox).rel || this.rel;
              return (relRelated === settings.rel);
          });
</code>

I found a similar issue Do I use jQuery noconflict to avoid plugins conflict? however the effect was different. Yet the cause seems similar. According to someone answering that question the problem is that bxSlider whipes out the $.data() set by colorbox.
So my questions are:

Is there a way around this?
Is it a bug in colorbox?
Is it a bug in bxSlider?
Answer: I know its been ages since this question asked but I had the similar problem and after much struggling the error for me was that I was calling colorbox before bxslider, I change the order of calls and it works as a charm. Maybe someone will be helped by this.
Answer: Without seeing more of your code I can't tell what your trying to do. Your <code>$('something').colorbox({rel:'something'});</code> looks a bit strange and I can't tell if your inserting classes, id or an actual rel attribute value. You may want to review colorbox's rel option(rel:'something') and how it behaves. See http://www.jacklmoore.com/colorbox
There are no issues that I see with using those two plugins together. I tried it on jsbin and it works fine with no errors.
See here for yourself: http://jsbin.com/ovucuz/11/edit#javascript,html,live


Every time a word enclosed by "" is typed in an input field, repeat it using JavaScript

Question: I am trying to write some JavaScript so that every time I type a word enclosed by "", the word including the "" is instantly repeated whilst typing.
For example, when typing "Interesting", the input field would immediately display "Interesting.
It would need to work each type "" was used, so that it could be used many times in the input field.
I have the following code to automatically capitalise letters when typing in a input field:
document.addEventListener('DOMContentLoaded', function(){
    let input_note = document.getElementById('note_text');
    input_note.addEventListener('input', upThing)
})

function upThing(ev){
    ev.target.value = ev.target.value.toUpperCase();
}

This may provide a starting point but is still a long way off.
Answer: You can use a Regular Expression to match for the quotes and then join the matches together in the label.
I also advice you change your real-time text transformation to be done through CSS instead of JavaScript, this is because if you change the value of an input while the client has their input position a few characters behind the last character, it'll be reset to the end.

const noteInput = document.getElementById("note-text");
const noteQuotes = document.getElementById("note-quotes");

noteInput.addEventListener("input", (event) => {
  noteQuotes.innerText = Array.from(event.target.value.toUpperCase().matchAll(/"(.*?)"/gm), (match) => match[0]).join(", ");
});
#note-text {
  text-transform: uppercase;
}
<input id="note-text" type="text">

Edit: I may have misunderstod your question. :)
Comment: Thanks for taking the time on this Nora. Since the input where I want to do the real time text transformation is ``, what purpose does `` serve? I have tried the above code and it has not worked, but I have likely misunderstood!
Answer: I would use REGEX expression to match the value from the input to begin with
You can look up the regex expressions here
Answer: My answer checks the last character to verify its a quote. Then determine if its the first quote or not by setting the value of the start variable. Then if its the last quote, append the value and reset the start variable.

let input_note = document.getElementById('note_text');
let start = -1;

input_note.addEventListener('input', upThing)

function upThing(ev){
    let obj = ev.target
    isQuote = (obj.value[obj.value.length-1] == "\"")

    if(isQuote && start == -1){
      start = obj.value.length;
    }
    else if(isQuote && start > -1){
      obj.value += " " + obj.value.slice(start,obj.value.length-1)
      start = -1;
    }

}
#note_text {
  text-transform: uppercase;
}
<input id="note_text" type="text">
Comment: Thanks for pulling this together - I have tried using it but nothing seems to happen when I enclose a word with "" (i.e. "hello") unfortunately


Implementing multi tenancy on Spring Data JPA

Question: I am planning to write a multi tenant aware application using Spring Data JPA as the persistent layer. However I'm not planning to keep separate databases per tenant rather all the data is in a single database. Following beans represent the Project entity and Tenant entity that I'm planning to implement. When fetching a project or fetching the list of all projects, I should be able to filter them according to a specific tenant. I know that I can easily do that by writing methods like bindByIdAndTenant_Id(int id, int id) but I'm worrying about the scalability of the solution. What I need is to have a method like findById(int id) and content will be automatically filtered by the tenant id that is fetched from a context. Is there a way I can do that in Spring Data JPA?
Project Entity
public class Project {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;

@Column(name = "NAME")
private String name;

@Column(name = "DESCRIPTION")
private String description;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "TENANT_ID", referencedColumnName = "id", foreignKey = @ForeignKey(name = "FK_TENANT_IN_PROJ"))
private Tenant tenant;}

Tenant Entity
public class Tenant {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
int id;

@Column(name = "NAME", unique = true)
private String name;}

Comment: You can try using the multi-tenancy capabilities provided as extensions to some JPA implementations (see e.g. here: https://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant and here: https://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/chapters/multitenancy/MultiTenancy.html). At the time of writing, your use case (i.e. using discriminator columns) is not implemented in Hibernate. It is, however, supported in EclipseLink.
Answer: There is (afaik) no such "out-of-the-box" mechanism. How should Spring know how a tenant is identified and what is important to separate the data. Maybe there is even some shared data between tenants so things get more complicated and it's on your own to do that.
I assume your data is accessed using a web layer  and you have to identify the tenant on every call. A "simple" path parameter or a header is (without any further validation) too easy to manipulate so maybe a token (JWT) is a good alternative to store request based tenant information. Here is a nice article about exactly that topic. Another one is talking about pros and cons, especially related to differences in storage architecture.
Personally, I would tend to the "different databases" approach. It's easy to scale out and user data is separated properly. Also backup and restore mechanisms are possible for each tenant without affecting the other users. At least use different schemata for each tenant, but maybe that depends on the database and what exactly is meant by "schema".


Help inequality involving exponential function

Question: How to show that $e^{x} \geq \left (1 + \frac{x}{n} \right) ^{n}$ holds for each non-negative real $x$ and each integer $n \geq 1$ ? I tried series and induction but got stuck. Can you please help?
Comment: Hint :  use, $\exp(y) \geq 1 + y$ for all $y$.
Answer: HINT $\ $ Consider $\rm\ e^z\ \ge\ 1 + z,\ \ z\ =\ x/n $


Access to another page in same directory yields CORS error with file: URL

Question: I am attempting to build a tiny browser-based app which will run from a file: URL without using a server.  (So I can just drop the files on a flash drive, and launch it by just double-clicking the HTML file.)  The app needs to read another file, but each approach I attempt to use yields a CORS error.
My two approaches have been:

Make an AJAX request
Load the content into an iframe and try to read the document

which yield the following errors, respectively:

Access to XMLHttpRequest at 'file:///PATHHERE' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
SecurityError: Blocked a frame with origin "null" from accessing a cross-origin frame.

Per MDN's definition of an origin:
<code>Two URLs have the same origin if the protocol, port (if specified), and host are the same for both.
</code>
Based on that definition, any file: URL should be same-origin and hence CORS (being cross origin) would not apply.
I found that MDN has a an additional page about file: URLs which states that the desired file must be in the same or subdirectory of the page's file to be considered same-origin.  I found that is true for Firefox, but Opera, Chrome, and Safari appear to not follow that idea but rather treat all file: URLs as cross-origin, even if the page is trying to load a copy of itself!
So I could just only use Firefox, except the catch is the file I'm trying to load is a directory and Firefox treats directory listings as cross-origin even if it is a subdirectory of the directory where the original page lives.  The error is "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///myapp/subdir. (Reason: CORS request not http)."  (Although I would content that it is not cross-origin, therefore shouldn't have to be HTTP.)
So is there any way in any current major browser (preferably Chrome since it would be available everywhere I'd want to use this) to get a directory listing over a file: URL?
And if not, is there any good reason why that's not supported, at least for directories under the folder where the page was loaded from?  As in, is there some security reason for it that just isn't obvious to me?  Or is it just the general bias against file: URLs?  (i.e. that any real app would be hosted on a webserver.)
Answer: This is a security feature of internet browsers. Reading a file with file:/// protocol is a big security problem. That is why it is not allowed.
If you still want to read local file in your html page, you can use electron.js - it uses a different approach.
https://electronjs.org/


Does LVS ldirectord Load Balancer support SSL termination / offloading?

Question: I use a ldirectord setup for load balancing a couple of real servers and for the HTTPS conenctions I am considering using some offloading mechanism on the LB - is there some functionality already implemented in the ldirectord, or should I look for another solutions that I will have to pair with ldirectord?
Thanks in advance!
Answer: when using lvs with ssl, set the certificates on the ssl service servers (ldap in my case) to match the load-balancer VIP, not the hosting server DNS names. This means that when you hit the lvs server VIP:ssl port, the cert negotiation matchs the reverse dns name that is expected by the initiating server.
Testing ssl handshake -> openssl s_client -connect hostname:port
the problem isnt the config. A standard lvs config works fine. The problem is the the ssl certificate negotiation. The "client" expects a certifcate that matches the reverse dns for the IP it is connecting to. (ie the load balancer virtual IP interface IP). If the host farm responder responds with "its" certificate, it will look like a spoofed cert because it wont match the connection IP. Therefore the "fix" is to load all the farm responders with the LB virt IP certificate instead
Andrew.
Comment: Who are you expecting to read that comment?
Comment: I find this answer a bit unclear. Maybe it can be improved with an example of what the suggested configuration would look like.
Comment: btw, I tried to sign up, but your site requires me to use a password I cant memorise, namely upper+lower+digits+nonalpha. Totally ignoring human factors. The *pont* of letting people choose their own password is making it something they can remember easily.
Answer: I should start by saying that I haven't configured LVS for a couple of years, now, and it may have moved on.
That said, when I last did it was very much software that worked at layer 3, not layer 4.  If you wanted something that would redirect your incoming TCP/443 connections to one of a pool of back-end servers, LVS was your man.  If you wanted something to receive incoming HTTPS connections, decrypt them, and farm the decrypted requests out to a pool of back-end servers, it wasn't your man.
Edit: yes, I'd consider using apache to do the decrypt and redirect-to-the-pool.  Furthermore, you could use Linux-HA to control two front-end apache boxes (one live, one hot standby), so that the redirector was still always-up, on an IP address that floated between the two under HA's control.
Comment: Thanks for the quick answer! :)

So, I guess I should consider something like an Apache server or Squid proxy infront of / behind the Load Balancer, so that they can work with the SSL encrypt / decrypt.


LilyPond: rests making an empty whole measure

Question: I am writing (in LilyPond) the beautiful lyrical waltz of Shostakovich, and I am getting a whole measure empty. What I want to achieve is the following:

But I am getting this:

I'd tried several combinations of rest but none are working, the best I can get is what I've show here.
My current code looks like this:
(I use Italian language, but certainly you will see the point)
\language "italiano"
upper = \relative do' {
\clef treble
\key fa \major
\time 3/4
    r1
    r1
    r1
    r8 do8 re mi fa sol
}

lower = \relative do {
\clef bass
\key fa \major
\time 3/4
    fa,4 <do' fa la>4 <do fa la>^.
    do, <do' fa la> <do fa la>^.
    fa, <do' fa la> <do fa la>^.
    do , <do' fa la> <do fa la>^.
}

\score {
\new PianoStaff <<
\new Staff = "upper" \upper
\new Staff = "lower" \lower
>>
\layout { }
\midi { }
}

Any ideas on how I can make this work properly?
Comment: Including bar checks would've generated some warning messages that might've helped you track this down.
Answer: Use a capital R2. (including the "dot" for dotted half-note) for your rests to indicate a full-bar rest. See here: http://lilypond.org/doc/v2.18/Documentation/notation/writing-rests#full-measure-rests
Based on the rest placement, Lilypond is interpreting your rests as lasting four beats, thus crossing the bar lines. That seems to be why the blank measure occurs: it's three of the four beats of the third rest.
Answer: As simple as:
R1 * 3/4
Read a whole-bar rest. Which is 4 quarter notes. 4 quarter notes divided by 4, times by 3 is a whole-bar rest in 3/4 time!

Edit TLTR
They are not whole-note rests, either in 3/4 or 4/4 time but whole-bar rests, to be clear. They have a default value of 4 quarters.

My way

Larger than 4 quarter-notes: 5/4  is R1 * 5/4
Equal to 4 quarter-notes: 4/4 is R1 * 1/1, simply R1
Smaller than 4 quarter-notes: 3/4 time is R1 * 3/4

The fraction mirrors the time signature.

I'm seeing it as a whole-bar is 100%, more than 4 quarters is more than 100%, less than 4 quarters is less than 100%.
While the documentation is of course correct and doesn't state the fraction way, apart from larger than 4 quarter-notes,(and @Aaron's answer should probably be the correct answer), I think there are valid reasons for using fractions:

fraction mirrors the time signature
introduces the fraction of a note concept early-on in learning lilypond, it's particularly used in:

tuplets e.g. \tuplet 3/2 { c8 c c} (but this is 3 in space of 2, not tech. a fraction)
placement of delayed ornaments e.g { c8 * 1/4 s\trill s\turn s\prall d8 }
other places like spacing

confusion: if I see 2, I expect to see a half-note not a whole-note (half-notes have the additional pain of looking like whole-notes). With 1 I'm always seeing whole-note symbol.
Comment: In the question I noticed that each of the rests had strange horizontal placement within its measure. With your explanation, now I see that the rests are placed over every fourth quarter note.
Comment: Small correction: the documentation does give the fraction option. It uses the example of: `\time 13/8` //
`R1*13/8 | R1*13/8*12 |`, demonstrating a single-bar and mutli-bar rest.
Comment: Ha ha, indeed looked like a quarter rest was floating over there and the 3/4 did pretty well! You made my day Owain. Thanks
Comment: @shoover I tried to expand and make my answer and make it more clearer.
Comment: Yeah, the distinction is there. Got to be careful about language single-bar and mutli-bar rest as `\override MultiMeasureRest.staff-position = 2` works on both, there's no `SingleMeasureRest`. Ha, ha can go on forever about quirks of LP, even in docs "Full measure rests" never heard the term1


suPHP : proper use of the chroot feature

Question: I started using suPHP recently, and I'm spending an amazing amount of time debugging the configurations and different compile options to get something that actually works. I've tried contacting the development team through their mailing list, but it's obviously made of ghosts...
I am trying to use the chroot parameter, but it trigger a 500 Internal Error which I just can't solve.
I am using DBD MySQL for the DocumentRoot definition:
<VirtualHost *:80>
    ServerName *

    DBDriver mysql
    DBDParams <params>
    DBDocRoot "SELECT document_root FROM domains WHERE name=%s" HOSTNAME

    suPHP_Engine on
    AddType application/x-httpd-php .php .php3 .php4 .php5 .phtml
    suPHP_AddHandler application/x-httpd-php
</VirtualHost>

Once the VirtualHost has set the DocumentRoot, suPHP is supposed to apply an additional chroot. See the relevant section of my /etc/suphp.conf below:
docroot=${HOME}
chroot=${HOME}

allow_file_group_writeable=false
allow_file_others_writeable=false
allow_directory_group_writeable=false
allow_directory_others_writeable=false
check_vhost_docroot=false

The chroot parameters couldn't possibly be simpler, yet suPHP spits:
Caused by SystemException in API_Linux.cpp:465: chdir() failed: No such file or directory

... when I make a request to a PHP script. The suphp log does not contain any information, this line comes from the Apache error log.
Does anyone on Earth actually now how to setup this horrible chroot feature? I've been through countless forums and mails from the listing, but no-one has yet given a proper answer (even though this feature has been patched an unbelievable number of times). Or maybe I should switch to suExec, hoping it'll offer more satisfying results...?
Answer: Your problem is caused by the fact that you do not understand how chroot works. Once you chroot into /home/user, that's the new root and the paths are "relative" to it. So, if you have your files in /home/user/public_html and want to chroot to /home/user then the chdir should actually be /public_html and the fastcgi document root would be the same (/public_html).
It is technically impossible for suPHP to run chroot at a farther point in the way to launching the process.
Comment: I do understand how chroot works. suPHP designers obviously don't. `chdir` is a call made by suPHP, not my script. It calls it before chrooting. I've spotted two errors in `API_Linux.cpp`. suPHP throws this error, but the `chroot` actually happens. However, due to design errors, many other things seem to fail afterwards.
Comment: Actually you are not right. The chdir is indeed made by suPHP but AFTER chroot. Chroot is being done at the initialization of suPHP while chdir is being done when executing a script, on a per script launch basis. So chdir is executed inside the chroot.
Comment: The implementation of the `chroot` feature makes suPHP unable to find `/usr/bin/php5-cgi` (since it's already locked into the user's home). It's obviously triggered to early... The `chroot` call is supposed to be made *at script execution*, not earlier. Because of this, I just can't find a way to configure it correctly. I can't actually place a copy of php5-cgi into each user home, that'd be ridiculous.
Comment: I am sorry but I will have to flag your answer and comments as you do not understand how it works. If you want it to work that way, it means that the already launched binary would require to chroot by its own. You need to build a chroot environment with all the libraries and binaries in order to run PHP inside chroot with suPHP. Not to mention that you downvoted an absolutely correct answer.
Comment: suPHP is supposed to chroot into home directories. If I follow your reasoning, that means that each home directory has to become a chroot environment, that is, each must contain every single PHP binary. Is that the way you hear it?
Comment: No, you can achieve this using bind mounts. You only need one environment.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/15814/discussion-between-florin-asavoaie-and-john-wh-smith).


How to make the wp-cli work in wp-config file with conditional statements?

Question: I am testing using the wp-cli to update my prod,dev,staging,test,and update sites for my domain.
In mywp-config file has conditional statements then I get the following error:
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 22
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 24
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 26
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 28
PHP Notice:  Undefined variable: db_name in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 34
Error: Can't select database. We were able to connect to the database server (which means your username and password is okay) but not able to select the `` database.

This is how I code my wp-config.php file which works!!!
if ($_SERVER["HTTP_HOST"] === 'example.com') {
  $db_name = 'example';
}else if ($_SERVER["HTTP_HOST"] === 'dev.example.com') {
  $db_name = 'example_dev';
}else if ($_SERVER["HTTP_HOST"] === 'staging.example.com'){
  $db_name = 'example_staging';
}else if ($_SERVER["HTTP_HOST"] === 'update.example.com') {
  $db_name = 'example_update';
}

define('DB_NAME', $db_name);

Is there any way I can get the wp-cli to work with this file?
Answer: $_SERVER["HTTP_HOST"]

Doesn't exist when you are using PHP from a command line. Your best option would be to specify a case when you are using the file in a command line, for example:
if (php_sapi_name() == "cli") {
    //set db_name when in cli
} else {
    //set db_name as per host
    if ($_SERVER["HTTP_HOST"] === 'example.com') {
      $db_name = 'example';
    }else if ($_SERVER["HTTP_HOST"] === 'dev.example.com') {
      $db_name = 'example_dev';
    }else if ($_SERVER["HTTP_HOST"] === 'staging.example.com'){
      $db_name = 'example_staging';
    }else if ($_SERVER["HTTP_HOST"] === 'update.example.com') {
      $db_name = 'example_update';
    }
}

As im not too sure what you want $db_name to be when you are in wp-cli i have left out setting it in the first set of braces.