Não consigo carregar campos

Question: Essa é minha tela
<h:panelGrid columns="6">

    <h:outputText value="Nome: * " />

        <f:validateLength minimum="4" maximum="70"/>

    <h:outputText value="Cargo: * "  />

        <f:validateLength minimum="4" maximum="70"/>

    <h:outputLabel value="CPF: *  "/>

    <h:outputText value="RG:* " />

    <h:outputText value="OrgaoExped:* " />

    <h:outputText value="DataExped:" />

    <h:outputLabel value="Cor:" for="Cor"/>

        <f:selectItem itemLabel=""/>
        <f:selectItem itemValue="Branco" itemLabel="Branco"/>
        <f:selectItem itemValue="Pardo" itemLabel="Pardo"/>
        <f:selectItem itemValue="Amarelo" itemLabel="Amarelo"/>
        <f:selectItem itemValue="Negro" itemLabel="Negro"/>

    <h:outputLabel value="Sexo: *" for="sexo"/>

        <f:selectItem itemLabel=""/>
        <f:selectItem itemValue="Masculino" itemLabel="Masculino"/>
        <f:selectItem itemValue="Feminino" itemLabel="Feminino"/>

    <h:outputLabel value="Estado Civil:*"/>

        <f:selectItem itemLabel=""/>
        <f:selectItem itemValue="Casado" itemLabel="Casado"/>
        <f:selectItem itemValue="Solteiro" itemLabel="Solteiro"/>
        <f:selectItem itemValue="Disvociado" itemLabel="Disvociado"/>
        <f:selectItem itemValue="Viúvo" itemLabel="Viúvo"/>

    <h:outputText value="Data nascimento:" />

    <h:outputText value="CNH:" />

    <h:outputText value="Titulo:" />

    <h:outputText value="Zona:" />

    <h:outputText value="Secao:" />

    <h:outputText value="Pis:" />

    <h:outputText value="Nº C Trabalho:" />

    <h:outputText value="Sº C Trabalho:" />

    <h:outputText value="Cº Resevista:" />

    <h:outputText value="Sº Resevista:" />

    <h:outputText value="Nome do banco:" />

        <f:validateLength minimum="4" maximum="70"/>

    <h:outputText value="Numero banco:" />

    <h:outputText value="Conta Cº:" />

    <h:outputText value="Agencia banco:" />

</h:panelGrid>

Essa é minha base de dados

Table: funcionario
  Columns:
  cpf varchar(15) PK
  nome varchar(200)
  rg varchar(15)
  orgaoExped varchar(3)
  estadoCivil varchar(30)
  sexo varchar(10)
  cnh varchar(15)
  titulo varchar(15)
  zona int(11)
  carteiraTrabalho varchar(15)
  serieCTrabalho varchar(15)
  cartResevista varchar(15)
  serieResevista varchar(15)
  cor varchar(10)
  pis varchar(15)
  conta_corrente varchar(11)
  agencia_banco varchar(11)
  nome_banco varchar(30)
  numero_banco int(11)
  cargo varchar(60)
  dataExped date
  dataDeNascimento date
  secao varchar(3)

obs:todos os campos not null.
Classe Dao
public boolean selecionarFuncionario(Funcionario execute) throws Exception {

        PreparedStatement stmt = null;
        try {
            String sql = "select * from funcionario where cpf = '?';";
            stmt = this.conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while(rs.next()){

                execute.setCpf(rs.getString("cpf"));
                execute.setNome(rs.getString("nome"));
                execute.setRg(rs.getString("rg"));
                execute.setOrgaoExped(rs.getString("orgaoExped"));
                execute.setDataExped(rs.getDate("dataExped"));
                execute.setDataDeNascimento(rs.getDate("dataDeNascimento"));
                execute.setCargo(rs.getString("cargo"));
                execute.setEstadoCivil(rs.getString("estadoCivil"));
                execute.setSexo(rs.getString("sexo"));
                execute.setCnh(rs.getString("cnh"));
                execute.setTitulo(rs.getString("titulo"));
                execute.setZona(rs.getInt("zona"));
                execute.setSecao(rs.getInt("secao"));
                execute.setCarteiraTrabalho(rs.getString("carteiraTrabalho"));
                execute.setSerieCTrabalho(rs.getString("serieCTrabalho"));
                execute.setCartResevista(rs.getString("cartResevista"));
                execute.setSerieResevista(rs.getString("serieResevista"));
                execute.setCor(rs.getString("cor"));
                execute.setPis(rs.getString("pis"));
                execute.setConta_corrente(rs.getString("conta_corrente"));
                execute.setAgencia_banco(rs.getString("agencia_banco"));
                execute.setNome_banco(rs.getString("nome_banco"));
                execute.setNumero_banco(rs.getInt("numero_banco"));
                }
        } catch (SQLException ex) {
            Logger.getLogger(FuncionarioDAO.class.getName()).log(Level.SEVERE, null, ex);

        }
        return true;
    }

Controle
public String selecFuncionario() throws Exception{
      FuncionarioDAO cD = new FuncionarioDAO();
      cD.selecionarFuncionario(this.funcionario);
      return "/editar";
  }

Comment: Se alguém puder dar uma força eu agradeço muito,não estou conseguindo carregar os campos.
Comment: Resulta depois de executar.
Comment: 01-Aug-2016 13:52:58.814 INFO [http-apr-8080-exec-97] org.apache.catalina.util.LifecycleBase.start The start() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/ProjetoGrandeRecife]] after start() had already been called. The second call will be ignored.
Comment: Primeiro: Qual é o retorno disso aqui?
ResultSet rs = stmt.executeQuery();

Segundo, INFO [http-apr-8080-exec-97]...
Como diz aí, é só uma INFO, não é um erro.
Comment: No caso seria o retorno da query, para carregar os campos,para dai poder editar.
Comment: Sim, claro. Me expressei mal, só queria saber se a query está retornando os resultados corretamente. (:
Comment: Então ae é onde entra os parceiros do STACKOVERFLOW...pra está tudo certo mais mão consigo ver aonde estou errando.
Comment: desculpa...não. corrigindo
Comment: Então ae é onde entra os parceiros do STACKOVERFLOW...pra está tudo certo mais não consigo ver aonde estou errando.
Comment: "(...)só queria saber se a query está retornando os resultados (...)"
Comment: Não, aparece o resultado que coloquei logo ae em cima nos comentários.
Comment: E ae gente alguém pode me ajudar...
Answer: Você está esquecendo de passar o CPF do funcionário como parametro da query.
String sql = "select * from funcionario where cpf = '?'";
stmt = this.conn.prepareStatement(sql);

stmt.setString(1, execute.getCpf());

ResultSet rs = stmt.executeQuery();

Não consigo carregar campos


Echoing Integers Using an Array with Java

Question: I'm working to create a program that takes in 5 integers via user input, separated by spaces on the same line. From there I need to assign these integers to an array and then echo the array back.
Should be pretty straightforward, but I am having a tough time where my echo back is not inserting spaces between the integers i.e, the users input is {1 2 3 4 5} and the result is 12345, which should ideally be {1 2 3 4 5}.
This is my first opportunity to play with arrays, so any assistance would be helpful!
Below is the code I have written thus far:
package echo5ints;

import java.util.Scanner;

/**
 *
 * @author laure
 */
public class U7D1_Echo5Ints {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int i =0;
    int arr[]=new int[5];

    Scanner input = new Scanner(System.in);

    System.out.print("Please enter 5 numbers: ");

    String line = input.nextLine();
    Scanner numbers = new Scanner(line);

    for(i=0;i<5;i++)
        arr[i]=numbers.nextInt();

    System.out.println("These were the 5 numbers entered: " + arr[0] + arr[1]  + arr[2]  + arr[3]  + arr[4] );
}
}

Answer: try using split instead and printf
System.out.print("Please enter 5 numbers: ");
String line = input.nextLine();
String [] arr = line.split (" ");
System.out.printf("These were the 5 numbers entered: %s %s %s %s %s",
              arr[0], arr[1], arr[2], arr[3], arr[4] );

Answer: The spaces you seems to have added is for code and not for print statements.
Printf only print what appears inside quotes or the values held by variables.
SO your print line should be
  System.out.println("These were the 5 numbers entered: " + arr[0] +" "+ arr[1] +" " + arr[2] +" " + arr[3] +" " + arr[4] );


Inheriting custom fields from top of hierarchy?

Question: I have an organization ABC under which user X is assigned. Custom fields are defined for the organization ABC.
Is there a way in which i can get the custom field of ABC when accessing X ?
Is the custom field inherited through the hierarchy ?
PS: I'm accessing liferay using `jsonws'
Answer: There's no inheritance for Custom Fields. They're typically attached to a single element, e.g. your Organization ABC.
Your question mixes Organization ABC and User X - a Custom Field would be either for a user, or for an organization. It'd be your task to traverse all of the organizations that a user is member of, and this traversal potentially includes the parents of those organizations.
Comment: Yes. The very first sentence of my answer is absolute: *There is no inheritance for Custom Fields*.
Comment: Thanks Olay. Is that same for organization and sub-organization instead of organization and user hierarchy?


How can I do a count in Linq with many to many

Question: So I have
Business
Jobs (many per business)
JobApplications (many per job)

I just want to count the total number of Applications for a business.
But I dont seem to be able to go
Business.Jobs.JobApplications
if I use
Business.Jobs.SelectMany(l => l.JobApplications
is accessible from there but I dont understand how to connect and count.
Comment: `Business.Jobs.SelectMany(l => l.JobApplications).Count()` ?
Comment: Does each `JobApplication` has exactly one `Job` and one `Business`? If so, this is not "many to many".
Comment: @leppie thats the correct answer if you post it as an answer, I'll accept it.
Comment: Is this LINQ using the Entity Framework (or similar)? Because if it is, leppie's code might load all `Jobs` and all `JobApplications` from the database to memory, which might be slow. Can you add some details? Maybe give some code to show what you have, and what the ourput should be (one `Business business`? all of them?)
Comment: @DaleFraser: You can give it to Matthew North
Comment: @Kobi: Fixed it for him :)
Answer: How about:
Business.Jobs.SelectMany(c => c.JobApplications).Count();

Answer: You will have to replace a bit the names.
bussiness
    .Select
    (b => new
        {
            id = b.id,
            applications = b.jobs
                .Select (j => j.jobapplications.Count ()).Sum ()
        }
    )

The above has worked for the following structure:
void Main()
{
    var bussiness = new List<Bussiness>()
    {
        new Bussiness
        {
            id = 1,
            jobs = new List<Jobs>()
            {
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                },
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                },
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                }

            }
        },
        new Bussiness
        {
            id = 2,
            jobs = new List<Jobs>()
            {
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                },
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                },
                new Jobs
                {
                    jobapplications = new List<JobApplications>()
                    {
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications(),
                        new JobApplications()
                    }
                }

            }
        }
    };

    //bussiness.Dump();

    bussiness.Select (b => new {id = b.id, applications = b.jobs.Select (j => j.jobapplications.Count ()).Sum ()})
    .Dump();
}
public class Bussiness
{
    public int id {get;set;}
    public IEnumerable<Jobs> jobs {get;set;}
}
public class Jobs
{
    public IEnumerable<JobApplications> jobapplications {get;set;}
}
public class JobApplications
{

}

You would need to apply it on your structure.


paypal IPN simulator always giving INVALID response when live,

Question: I'm using this: https://github.com/Quixotix/PHP-PayPal-IPN
and during sandbox testing everything was working fine.
My code is pretty much the same as the one in this question: Paypal IPN Valid in sandbox INVALID when live
However, now that I've gone live, every time I do a paypal IPN simulation, it's always "INVALID".
Is it because I'm live? Are simulations only VERIFIED while we're still testing in the sandbox?
Answer: If you are trying to use the simulator while posting to the live paypal IPN address, then it will return an INVALID response.  You have to post to the sandbox address in order for the IPN simulator to return a VERIFIED response.
If using the simulator with a live post address, it will return an HTTP code of 200, but the response will always be INVALID.  Hope this helps.
Answer: I am currently having this same problem as well. Did you change both of the $listener->use_sandbox variables to false (in ipn.php and ipnlistener.php)? Have you enabled IPN notifications in your PayPal account? If you  have not done the latter, you can do so with the following: Profile-->Settings-->My selling tools-->Instant payment notifications-->Update.
What does the 'Message ID' associated with that particular IPN notification say? (you can access this in your IPN history)
Mine has the following (relevant information):
Date/time created: 29/04/2013 16:21 AEST
Latest delivery attempt date/time: 11/05/1985 02:23 AEST
HTTP response code: 200
Delivery status: Sent
IPN type: Other transaction made
I'm wondering why the latest delivery attempt date/time is listed as being in 1985... Perhaps you have something similar for yours? Sorry I have not solved your problem for you, but perhaps I have given you some additional things to look into? And, I'm sure the others that answer will probably want to know these things as well. :-)
PS: you might consider checking your server access logs. When I checked mine, I discovered that the IPNs from the Sandbox were being posted successfully; however, the live ones weren't.
PPS: I fixed my issue by making sure the IP addresses listed here (for use by PayPal) were able to post to my website: explanation and addresses


Stagg US10 TATTOO strings sound buzzy and loose

Question: I bought my Stagg US10 TATTOO 1402/117 soprano ukulele yesterday while I was off home. The guy at the shop told me to look up on the internet how to tune it, but because I am bad at it I downloaded a tuenr app on my android phone and tried to tune it like a normal uke should be tuned, GCEA. When I then tried to play the first chrord, C from the song 'Somewhere over the rainbow' I knew something was off. It didn't sound as it should. Then I downloaded 3 more tuning apps and they all say I tuned it correctly. The strange thing is that it doesn't sound nearly as it should. Also, every string except the C one feels like it is loose and maybe because of that it gives me that buzzy sound which I don't like at all. I would really like you help, beacuse I heard some people playing on this uke on youtube and they sounded pretty good, but mine is just oughhhh...
Thanks a lot :)
Comment: can you upload a recording sample?
Answer: Is it possible that you have some of the strings tuned an octave too low?

If you don't know and cannot hear the difference, you need to get a teacher.
Otherwise, your model, at US $35, is an exceptionally cheap ukulele. It may require a setup by a professional guitar technician to make it play correctly, and in this case, a professional adjustment would cost more money than you paid for this extremely cheap instrument.


Mysql: what to do when memory tables reach max_heap_table_size?

Question: I'm using a mysql memory table as a way to cache data rows which are read several times. I chose this alternative because I'm not able to use xcache or memcache in my solution.
After reading the mysql manual and forum about this topic I have concluded that an error will be raised when the table reaches its maximum memory size. I want to know if there is a way to catch this error in order to truncate the table and free the memory. I don't want to raise the limit of memory that can be used, I need a way to free the memory automatically so the table can continue working.
Thanks.
Answer: If you're out of memory, the engine will raise the error 1114 with the following error message:
The table 'table_name' is full

You should catch this error on the client side and delete some data from the table.
Answer: You should use normal, persistent tables instead and rely on the inherent caching. For tables where the contents can safely be thrown away, MyISAM is a safe engine (provided you are happy to do a TRUNCATE TABLE on each boot up), alternatively, you can use the same engine as your permanent tables (e.g. InnoDB).
Memory tables are extremely sucky anyway (In all released MySQL versions; better in Drizzle and some others) because they pad rows to the maximum length, which means you can't really start putting VARCHARs in them sensibly.
Unfortunately, you cannot yet set the innodb durability parameter on a per-table (or per-transaction) basis, so you must decide on a per-server basis how much durability you need - in your case, none, so you can set innodb_flush_log_at_trx_commit to 2 (or even 0, but it gains you little)
Comment: It's no longer true that MEMORY storage engine pads VARCHARs to full length. Recent versions of Percona MySQL server fixed that.
Comment: I'm fairly sure the statement was true for all GA mainline versions of MySQL at the time I wrote it. Many of the forks have fixed the memory ending padding.


Customize or remove space between ion row

Question: I am learning Ionic app. I got introduced to Grid thing, however, I am stuck at removing/modifying spaces between rows ( row number 2 and 3) as shown in the following screenshot:

I have following code in my HTML:
<ion-content padding>
    <ion-row>
      <ion-label> I am good I do not want any space.</ion-label>
    </ion-row>
  <ion-row>

        <ion-label *ngIf="!inverse"  no-margin>1 USD = 67 INR</ion-label>
        <ion-label *ngIf="inverse" no-margin>1 INR = {{(1/67) | number }} USD </ion-label>

      <button (click)="inverse=!inverse" ion-button clear class="iconWidth" color="dark">  <ion-icon name="swap" class="rotate"></ion-icon></button>

  </ion-row>
<ion-row>

Can you help me to get rid of space between this row and above

  <ion-label> Thanks</ion-label>
</ion-row>
</ion-content>

SCSS:
page-home {

  .rotate {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
    margin-bottom: 15px;
    }

  .inner{
    display: inline-block;
    width:70%;

    }
  .iconWidth{
    width:20%;
    }

}

How can I customize the gap between row 2 and row 3?
Answer: Use negative margin-top
html
<ion-row class="bottomRow">

Can you help me to get rid of space between this row and above

scss
 .bottomRow
{
  margin-top: -20px;
}

Stackblitz Example
Answer: What worked for me was going into the tag, linking it with class="foo" and then setting .foo{padding:0px}
Answer: try using no-padding and no-margin like this and on others you want off
  <ion-row no-padding>

Can you help me to get rid of space between this row and above

  <ion-label> Thanks</ion-label>

or
 .inner{
  display: inline-block;
  width:70%;
  margin-bottom: 0px;

    }


Rails auto convert query string params to integers

Question: I'm trying to implement a form of pagination using limit and offset query parameters. Is there a way to make sure the values are integers otherwise throw a 400 error, perhaps by using strong_parameters? It seems like the sort of thing that would be built in to rails, but I can't find anything.
I could just manually convert the query parameters, but I'd rather use something a bit more bullet proof if possible.
Comment: why not use [will_paginate](https://github.com/mislav/will_paginate) or [kamanari](https://github.com/amatsuda/kaminari) for pagination?
Comment: I'd prefer to use limit/offset over page numbers, and this is primarily a JSON api, which doesn't seem to be supported as well in either gem
Comment: the gems internally convert per_page/page_number to limit/offset anyway. Hence the suggestion. JSon API? you omitted that tiny little detail from the question.
Answer: Like the commenter @Litmus above, I would recommend using a Ruby gem such as kaminari to manage pagination.
But if you're set on rolling your own, and you're concerned about input sanitization, the simplest method to ensure the "offset" and "limit" parameters are integers might be a filter in your controller:
class YourController < ApplicationController

  before_filter :sanitize_page_params

  # ... other controller methods ...

  private

  def sanitize_page_params
    params[:offset] = params[:offset].to_i
    params[:limit] = params[:limit].to_i
  end

  # ... etc. ...

end

Note that strings such as "foo" will be converted to 0.
Comment: Little update since `before_filter` syntax were deprecated in Rails 5.0 and removed in Rails 5.1 :
Use `before_action` instead.
Comment: FYI. The code above will convert the params[:offset] value set to "-1" to -1. If this negative integer is then used in the ActiveRecord.offset() call, it will result in  a 'ActiveRecord::StatementInvalid: Mysql::Error' error
Comment: Steve Wilhelm makes a great point ^ If you use this, you may also want to check for negative numbers.
Answer: You basically need to convert your parameters manually. Ideally, abstract this into a controller-method to keep your actual method clean.
Class SomeController < ActionController
  before_filter: cleanup_pagination_params

  def cleanup_pagination_params
    params[:offset] = params[:offset].to_i
    params[:limit]  = params[:limit].to_i
  end

  # Your regular controller methods here
end

Answer: Try this: Repair numeric param values converted into string
repair_nested_params({id: '11', age: '25'}) # Sample

def repair_nested_params(obj)
  obj.each do |key, value|
    obj[key] = parse_string(value)
  end
end

def parse_string(value)
  return repair_nested_params(value) if value.is_a?(Hash)
  return value.map(&method(:repair_nested_params)) if value.is_a?(Array)
  return value unless value.is_a?(String)

  is_numeric = value.match?(/\A[-+]?\d*\.?\d+\z/)
  return value unless is_numeric

  (value.to_f % 1).positive? ? value.to_f : value.to_i
end


Why $R=\{(a,b)\mid a=b \mbox{ or } a=-b\}$ is not anti symmetric?

Question: Why $R=\{(a,b)\mid a=b \mbox{ or } a=-b\}$ is not anti symmetric?
I read because this is symmetric so it is not anti symmetric, but $R=\{(a,b) \mid a=b \}$ is both symmetric and anti symmetric.
Comment: Have you tried writing down what anti-symmetric means in this situation and tried finding a counterexample?
Comment: @vidyanathan thank you
Answer: It's not antisymmetric because $\langle 1,-1\rangle\in R$ and $\langle -1,1\rangle\in R$, but $1\ne -1$. That's a clear violation of the definition of antisymmetry. Remember, antisymmetry means that if $\langle a,b\rangle\in R$ and $\langle b,a\rangle\in R$, then $a=b$.
Note also that it is entirely possible for a relation to be both symmetric and antisymmetric. The relation of equality on any set is both symmetric and antisymmetic.
Answer: Suppose $X=\{-1,1\}$. We see that $R(-1,1)$ and $R(1,-1)$ which violates $R$ being an antisymmetric relation because $1\neq -1$.


Por que o código não está executando o laço for, mesmo o compilador não mostrando erro?

Question: Estava fazendo um exercício sobre vetores, em que o objetivo era construir um programa que recebia um número n pelo input que definiria o tamanho do vetor, para depois receber, também por input, outros n números para serem alocados nesse vetor.
Após isso deve-se utilizar um método para encontrar o maior número entre esses últimos. Mas o problema que encontrei está justamente na maneira que encontrei para pegar e alocar esses n números no meu vetor.
Após testar meu programa várias vezes vi que o método é chamado, mas o laço for, que estava antes nem é iniciado. Realmente não sei o que pode ser.

O código:
import java.util.Scanner;
//bubble sort array
public class EP6_1 {

    public static int maiorNumero(int array[]) {
        int resposta;
        for (int x = 0; x == array.length - 1; x++) {
            if (array[x] >= array[x+1]) {
                for ( int c = 0; c == array.length - 1; c++ ) { //c é o contador
                    int temp = array[c];
                    array[c] = array[c+1];
                    array[c+1] = temp;
                }
            }
        }
        resposta = array[array.length-1];
        return resposta ;
    }

    public static void main(String[] args) {

        Scanner leitor = new Scanner(System.in);

        int lista[];

        System.out.println("Digite o tamanho do vetor"); //numero de elementos
        int N = leitor.nextInt();                        //da lista

        lista = new int[N];

        for (int i = 0; i == N - 1; i++) { //i é o contador
            System.out.println("teste");
            lista[i] = leitor.nextInt();
        }
        System.out.println(">>>>>>>");
        System.out.println(maiorNumero(lista));

    }

}

Comment: Antes de ver o código, e está difícil de ver como imagem do seu IDE (por que não cola o código aqui e facilita nossa vida?) você tem uma ideia errada do que é um compilador, e talvez do que seja um programa. Não mostra porque não tem nenhum erro que o compilador possa detectar e que impeça a compilação, mas tem um dos infintos erros que um código pode ter, e faz parte do trabalho do programador achar quando o co0mpilador não acha por você. Com o código eu posso ver se dá para dizer mais alguma coisa.
Comment: Forneça o código de forma textual sempre, para que seja possivel nao somente visualizar, mas tambem execuar.
Comment: Perdão, essa é minha primeira postagem. Acabei de editar e colocar o código, mas acredito que também não ficou com a formatação desejada
Comment: Fazendo uma analogia - *bem* simplista - o compilador é como um "corretor ortográfico". Vc pode escrever um texto sem erros gramaticais - que o corretor considera correto - mas que só diz coisas sem sentido (e isso o corretor não detecta). Assim como pode escrever código sem erros de compilação (e portanto o compilador não reclama), mas com a lógica errada (não faz o que deveria).
Comment: Dicas para formatar o código: https://pt.stackoverflow.com/editing-help#code
Comment: No for onde está escrito `i == N - 1` troque por `i <= N - 1`
Comment: @Bruno_SMR Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (terá pontuação suficiente logo depois de aceitar uma resposta).
Answer: A condição do for é i == N - 1, portanto o laço executará sempre que essa condição for verdadeira. Ele não precisa executar se a condição de cara já for falsa. Logo antes você disse que i é igual a 0, portanto a condição só será verdadeira se o N for 1 (lógica básica matemática), em nenhuma outra situação isto é verdadeiro, então qualquer número que seja digitada e colocada em N que não seja 1 a condição será falsa e o laço não executará, nem uma vez sequer.
Provavelmente o que queria fazer seria algo assim:
for (int i = 0; i < N; i++)

Coloquei no GitHub para referência futura.
Isso pelo menos seria o que todo mundo faz. Dessa forma será verdadeiro sempre que o valor de i for menor que N, portanto faz sentido para um contador, ele vai de 0 até o valor antes no número total. Só cuidado para não fazer i < N - 1 porque isto não iria até o último item, ou fazer i <= N porque iria um além e daria erro. Poderia, mas não é ideal fazer i <= N - 1, está fazendo uma operação aritmética desnecessária e em algumas arquiteturas o <= é mais lento que o <.
Answer: O erro está na linha 35
Substitua:
for (int i=0; i == N - 1; i++) {

por
for (int i=0; i < N; i++) {

A variável i está comparando com N e na verdade ela tem que ser menor que N (i < N).
Outra questão é que o laço inicia em 0 e vai até ele ser menor a variável N. A partir do momento que ele for verificar e i for igual a N ele não executará o bloco. Então se deixar o i < N - 1; ele vai contar sempre um menos.
Comment: @Lucas não é muito legal induzir o autor a aceitar sua resposta, deixe que ele mesmo avalie qual das respostas é melhor, lembre-se de que o objetivo aqui não é aceites, é compartilhar conhecimento ;)
Comment: Ele *acha* que funcionou, mas fazendo `i < N - 1`, como vc sugeriu, o `for` vai percorrer um item a menos (e talvez ele não tenha percebido isso ainda). Então os negativos não são "por acaso". Já a outra resposta tem o código correto :-)
Comment: `new int[N]` cria um array com N elementos. Usando `N` igual a 5, o array tem 5 elementos (índices de 0 a 4). Fazendo o `for` com `i < N - 1`, ele vai parar no índice 3, deixando o último elemento (índice 4) de fora.
Comment: Resumindo o que o @hkotsubo disse, seu codigo fará com que laço ignore o ultimo item, acho que você é que nao entendeu seu proprio codigo.
Comment: Ah de fato, realmente é isso. Achava que colocando i == N - 1 faria a repetição até deixar i com esse valor. Obrigado
Comment: Não esqueça de marcar como resposta ;D
Comment: Eu só comentei para ele marcar como resposta pois dentre as duas respostas ele comentou só a minha, que por um acaso está recebendo votos negativos, tendo uma resposta mais objetiva e respondida antes.
Até porque esta é a primeira postagem dele e acredito que ele nem saiba que tem como marcar como resposta, minha intenção não foi induzir que a minha resposta é melhor e sim lembra-lo que tem esta opção.
Comment: Pelo que ele apresentou ele quer que o usuário digite o número que irá definir o tamanho do vetor. Se o usuário digitar 5, como no exemplo que ele usou, o tamanho do vetor, iniciado em 0, vai ser 6 e não 5 como o usuário pediu. Acredito que não leram o que ele pediu...


Rooks attacked by at most one other rook

Question: Some rooks are placed on an $n\times n$ board. Each rook is attacked by at most one other rook, and every unoccupied cell is attacked by some rook. What is the smallest $k$ such that no matter how we set up the board, every $k\times k$ subboard contains at least one rook?
$k=\lfloor n/2\rfloor$ is too small, because we can take the board with a rook on each square of the main diagonal. In this board the bottom-left (or top-right) $\lfloor n/2\rfloor\times\lfloor n/2\rfloor$ subboard does not contain any rook. Is it true that every $(\lfloor n/2\rfloor+1)\times (\lfloor n/2\rfloor+1)$ subboard must contain some rook?
Comment: Usually a rook is *not* considered to attack its own square. For clarity, you should say that every *unoccupied* square is attacked by a rook.
Comment: It's easy to place $4n$ rooks on a $3n\times3n$ chessboard so that each rook is attacked by exactly one other rook, every unoccupied square is attacked by at least two rooks, and there is a $2n\times2n$ subboard with no rooks.
Comment: For $n=5$, it's easy to leave an open $3\times3$ subboard and satisfy the other conditions with $6$ rooks.
Comment: @Bof As I understand the question, we are looking for the worst possible placement of the rooks, such that we are guaranteed that ever $k$X$k$ subboard contains at least one rook.
Comment: Is it correctly understood that you are looking for the smallest $k$ which can be guaranteed given any board that fulfills your two first sentences? Or are you looking for the smallest $k$ possible, given an optimal board?
Comment: @Jens Your first interpretation is correct.
Comment: In that case, a lower bound for $k$ would be $\sqrt {\frac{n^2}{2n}}$, i.e. the square root of the total area of the board divided by the total number of rooks possible on such a board.
Comment: @Jens Didn't the OP already show that $\frac n2$ is a lower bound for $k$? And doesn't my example show a lower bound of $\frac23n$?
Comment: I first read this what is the smallest k x k square so that we can set up the rooks that each k x k square is occupied by  a rook.  Most of you are interpretting it as what is the smallest k x k square so that no matter how we arrange the rook every k x k square is occupied.  Different questions.  Are you sure which interpretation is the intended?
Comment: I posted the other interpretation [here](http://math.stackexchange.com/questions/1897443/dense-board-with-sparse-rook-attacking), seeing that it might be of interest as well
Answer: $\lfloor n/2 \rfloor + 1$ is not enough. As @bof stated, you can have $2n/3 \times 2n/3$ subboard without any rooks: take this empty subboard in the bottom left corner. For the $n/3$ rows above the subboard, starting from the top left corner, put $2$ rooks in each row in a staggered fashion, ending above the top right corner of the empty subboard. Do a similar thing with the $n/3$ columns to the right of the empty subboard. Then every square is attacked by a rook while this large subboard remains empty.
However, this turns out to be the worst case. That is, every $(\lfloor 2n/3 \rfloor +1) \times (\lfloor 2n/3 \rfloor +1)$ subboard must contain at least one rook.
To prove this, suppose we had an empty $k \times k $ subboard for some $k > 2n/3$.  We first show that every row must have at least one rook.
If not, then there is a row with no rooks. Every square in this row must be attacked by some rook in the same column.  Now consider the squares of this row that are in the same $k$ columns as the empty $k \times k $ subboard. The attacking rooks must therefore be in the $n-k $ rows outside this empty subboard. Since each row can have at most $2$ rooks in it, there are at most $2 (n-k) < k $ attacking rooks here, so some square in the empty row is left unattacked. This gives a contradiction.
Hence there is at least one rook in every row. By symmetry, there is also at least one rook in every column. Of course, there can be at most $2$ rooks in any column. Let $r $ be the number of rows with $2$ rooks. The total number of rooks is then $n+r $.  By double-counting, there are also $r $ columns with two rooks in them.
Now these $n+r $ rooks cannot be in the $k \times k $ subboard.  Hence they are either in the $n-k $ rows outside the subboard, or the $n-k $ columns outside the subboard.
The $n-k $ rows can have at most $\max (n-k, r) $ rows among them with $2$ rooks, and hence contain at most $n-k + \max (n-k, r) $ rooks in total. By symmetry, the same is true of the $n-k $ columns. Hence the total number of rooks is at most
$$ 2 (n-k) + 2 \max (n-k, r)  \le 2 (n-k) + n-k + r = 3 (n-k) +r. $$
(Note that this would count twice any rook that is in both a different row and column from the subboard, but since we are getting an upper bound, it is okay to overcount some rooks.)
However, we know there are $n+r $ rooks. Thus $n+r \le 3 (n-k) +r $, which simplifies to $k \le 2n/3$, a contradiction.
Thus if $k > 2n/3$, every $k \times k $ subboard must contain at least one rook.


Confusion Matrix values of zero

Question: My question is almost exaclty the same as this one: Suspicious Amount of Zeros in Confusion Matrix, but no one seems to have responded so I figure I'll ask again.
I've got a LOO confusion matrix that looks like this resulting from LDA on 271 samples from these 4 areas:
Overall accuracy  Prior frequency.England   Prior frequency.France
   0.6407                   0.3815                   0.1111
Prior frequency.Scotland    Prior frequency.Wales
        0.3185                   0.1889

          Predicted (cv)
Actual     England France Scotland  Wales
  England   0.6602 0.0000   0.3204 0.0194
  France    0.0667 0.0000   0.6333 0.3000
  Scotland  0.1744 0.0116   0.6977 0.1163
  Wales     0.0392 0.0000   0.0784 0.8824

Here's a second confusion matrix function's output for the same analysis with more details:
Confusion Matrix and Statistics

          Reference
Prediction England France Scotland Wales
  England       68      0       33     2
  France         2      0       19     9
  Scotland      15      1       60    10
  Wales          2      0        4    45

Overall Statistics

               Accuracy : 0.6407
                 95% CI : (0.5804, 0.698)
    No Information Rate : 0.4296
    P-Value [Acc > NIR] : 2.392e-12

                  Kappa : 0.4821
 Mcnemar's Test P-Value : 2.183e-06

Statistics by Class:

                     Class: England Class: France Class: Scotland Class: Wales
Sensitivity                  0.7816      0.000000          0.5172       0.6818
Specificity                  0.8087      0.888476          0.8312       0.9706
Pos Pred Value               0.6602      0.000000          0.6977       0.8824
Neg Pred Value               0.8862      0.995833          0.6957       0.9041
Prevalence                   0.3222      0.003704          0.4296       0.2444
Detection Rate               0.2519      0.000000          0.2222       0.1667
Detection Prevalence         0.3815      0.111111          0.3185       0.1889
Balanced Accuracy            0.7952      0.444238          0.6742       0.8262

There are a total of 30 samples from France, so that the column of zeros is rather unnerving.  I'm a complete beginner at this, so I've really got no clue if this makes sense - I can't find anything about having too many zeros on this site or stats textbooks I'm using, so I'm hoping someone here can offer some insight.
If I'm interpreting this correctly, this would mean that no French sample was predicted to be from France (which is fine, I guess), but it just has warning bells going off in my head.  Is it possible that not a single sample would be present at the intersection between the French column (predicted) and the French Row (actual)?
Comment: Your diagnosis about no `France` samples being predicted as such is correct (= zero true positives for this class). Do you obtain the confusion matrix from the same data or different data as you trained your model on? Are your classes balanced/could you add the absolute values of your confusion matrix?
Comment: @geekoverdose - the first matrix was from the training set, but I've added the LOO matrix and another function's output with more information.  I can add the training set's matrix again if needed.  I'm afraid a quick scan of Google couldn't turn up what "absolute values" are in relation to confusion matrices, so I'd be more than happy to add them if you can elaborate on what they are. Thanks!
Comment: You already added the absolute values in the second confusion matrix ;) Now there is one `Scotland` sample that is classified as `France` (false positive for this class). Do I understand correctly that with "LOO" you mean "leave one out (cross validation)", and that you therefore test the model on one sample it has not seen before each time?
Comment: Correct on both accounts - in the initial post I had the training set confusion matrix that recorded no `France` values, so the results are very similar, but not exactly the same.
Answer: It could be that those results are in fact correct, and that they are caused by a strange/difficult distribution of samples for the France class.
As you use results from LOOCV it could be that your model is just not able to predict any unseen sample from samples it has seen during training. This could be caused by e.g. the France class having a strange/difficult to model distribution for LDA (one could construct such distributions for many classifiers), or that you have too little data for modelling such a distribution. Another explanation would be that just you got erroneous data in the first place (e.g. switched or wrong labels).
Consequently, you could/should now:

Double check that you did not get erroneous data if this is possible for you.
Use your domain specific knowledge about the data to check if the results for the France class could actually make sense (is there any reason that this class could be so different? Different recording conditions, different context, ...). Try to investigate the features and feature-target relation - maybe you find something that would explain your results.
Try other models. You will likely get very different results using e.g. a KNN or tree/forest based model instead. If this is true, this again tells you something about your data, and which be able to give you a better understanding of point 2.
Comment: Thanks for the insight - it actually makes sense for this to happen (regarding your second point), and I'll double check my coding even though I'm pretty sure it's correct (your first point).  Point three is a bit scary, but I'll give it a whirl.  This is exactly the kind of helpful answer I needed for beginner-level guidance!

Confusion Matrix values of zero


Persistência com Spring e Thymeleaf em múltipla tabelas no mesmo form

Question: Estou com outra visão
Como posso passar dois objetos no ModelAndView, de forma que ao chamar uma requisição para salvar consiga fazer essa distribuição de objetos para cada Entyti.
Tenho Entyti Cliente e Contato, na page preciso salvar os valores passados, sendo redistribuído conforme objeto mapeado no ModelAndView.
EX.
*{contato.email} - seria salvo no contato
 *{nome} - seria salvo no cliente;
Lembrando que estou usando Thymelealf no form.
Answer: Você pode referenciar o objeto e o atributo diretamente no elemento do formulário ao invés de definir apenas um th:object para todo o form, por exemplo:
<form class="form-horizontal" th:method="POST" th:action="@{/cadastrar}">

      <input type="text" class="form-control" id="email" th:field="${contato.email}"/>

      <input type="text" class="form-control" id="nome" th:field="${cliente.nome}"/>

      <button type="submit" class="btn btn-primary">Salvar</button>

</form>

Depois disso basta receber no método salvar do seu controller os dois objetos por parâmetro.


Query only creating 7 out of 10 tables.. assistance please?

Question: I have designed this query to create 10 tables - however it creates 7 and then stops. Im not sure why. I have exhausted all I know to look for. Here is the script - any help would be appreciated.
ALTER SESSION SET NLS_DATE_FORMAT = 'MM/DD/YYYY';

CREATE TABLE CUSTOMER (
CUSTOMER_ID INTEGER,
CUST_FNAME VARCHAR2(20),
CUST_LANME VARCHAR2(20),
CUST_ADDRESS VARCHAR2(20),
CUST_CITY VARCHAR2(20),
CUST_ZIPCODE VARCHAR2(10),
CUST_STATE VARCHAR2(15),
CUST_PHONE VARCHAR2(15),
CUST_EMAIL VARCHAR2(35),
CUST_cODE INTEGER,
POLICY_NUMBER VARCHAR2(20));

/* -- */

CREATE TABLE VEHICLE(
VIN_NUMBER VARCHAR2(30),
MANUFACTURER VARCHAR2(20),
MAKE VARCHAR2(15),
MODEL VARCHAR2(15),
YEAR VARCHAR2(4),
MILEAGE VARCHAR2(7),
CUSTOMER_ID VARCHAR2(10));

/* -- */

CREATE TABLE PART(
PART_ID VARCHAR2(20),
PART_DESCRIPTION VARCHAR2(35),
PART_ORGIN_PRICE NUMBER(10),
SUPPL_ID INTEGER);

/* -- */

CREATE TABLE PAYMENT(
PAYMT_ID VARCHAR2(15),
PAYMT_DATE DATE,
PAYMENT_METHOD VARCHAR2(10),
COMP_CODE INTEGER,
CUSOTMER_ID INTEGER,
BILL_NUMBER INTEGER);

/* -- */

CREATE TABLE REPAIR_LINE(
BILL_NUMBER INTEGER,
VIN_NUMBER INTEGER,
REPAIR_CODE INTEGER,
START_TIME DATE,
END_TIME DATE,
PARTS VARCHAR2(25),
EMP_ID INTEGER,
PART_ID INTEGER,
PART_PRICE NUMBER(10));

/* -- */

CREATE TABLE SUPPLIER(
SUPPL_ID INTEGER,
SUPPLY_NAME VARCHAR2(25),
SUPPLY_ADDRESS VARCHAR2(20),
SUPPLY_CITY VARCHAR2(20),
SUPPLY_ZIPCODE VARCHAR2(10),
SUPPLY_STATE VARCHAR2(15),
SUPPLY_EMAIL VARCHAR2(35),
SUPPLY_PHONE VARCHAR2(20));

/* -- */

CREATE TABLE INSURANCE(
COMP_CODE INTEGER,
COMP_NAME VARCHAR2(25),
COMP_ADDRESS VARCHAR2(20),
COMP_CITY VARCHAR2(20),
COMP_ZIPCODE VARCHAR2(10),
COMP_STATE VARCHAR2(15),
COMP_EMAIL VARCHAR2(35),
AGENT_PHONE VARCHAR2(20));

/* -- */

CREATE TABLE BILL(
BILL_NUMBER INTEGER,
BILL_DATE DATE,
B_AMOUNT_INSURED NUMBER(10),
B_AMOUNT_CUST NUMBER(10),
bILL_STATUS VARCHAR2(15));

/* -- */

CREATE TABLE REPAIR(
BILL_NUMBER INTEGER,
REPAIR_CODE INTEGER,
DATE DATE,
LABOR NUMBER,
TAX_RATE NUMBER,
TOT_BEFORETAX NUMBER,
TOTAL NUMBER(10),
REPAIR_TYPE VARCHAR2(15));

/* -- */

CREATE TABLE EMPLOYEE(
EMP_ID INTERGER,
EMP_FNAME VARCHAR2(25),
EMP_LNAME VARCHAR2(25),
EMP_ADDRESS VARCHAR2(20),
EMP_CITY VARCHAR2(20),
EMP_ZIPCODE VARCHAR2(10),
EMP_STATE VARCHAR2(15),
EMP_EMAIL VARCHAR2(35),
EMP_PAYRATE NUMBER(10),
EMP_PHONE VARCHAR2(20));

/* -- */
Comment: At least two have keywords as column names, which won't work; `YEAR` and `DATE` (and maybe `MODEL`?). But is it creating the first 7? What errors do you get? Where are you running the script?
Comment: Do you get any error messages?  How are you connecting to the DB and running the script?  Is there perhaps already a BILL table?
Answer: there are a couple of errors in the script:
in VEHICLE table, YEAR may be reserved word.  change it to something else.

in REPAIR table, DATE is a reserved word.  change it to something else.

in EMPLOYEE table, EMP_ID INTERGER ... spelling error.  change to INTEGER.

then, try it again.
Comment: `YEAR` actually isn't reserved, despite my earlier comment, but `DATE` is. Good spot on`INTERGER`.
Answer: DATE is a reserved word, so you can't use that as a column name, as you're trying to do in the REPAIR table. You'll get an ORA-00904, 'invalid identifier` error.
Your client should be telling you what errors are occurring. It isn't obvious why any of the others would have a problem; except, as BWS pointed out, you misspelled INTERGER (ORA-00902).  Showing the errors, or even which tables are and are not created, would help of course.


Is there a sequence of extensions of ZFC where the corresponding sequence of proof theoretic ordinals has $\omega_1^{CK}$ as least upper-bound

Question: I was reading this question on MO  where they define an infinite sequence of extensions of ZF by creating iteratively  a new theory which includes the consistency of the previous ones.  The definition in this question is ambiguous.
Independently from this particular definition I wonder if it possible  to build a sequence of extensions of ZFC (or ZF), in such a way that for any  recursive ordinal $\alpha$ there exists $\kappa$ such that $\text{pto}(\text{ZFC}_{\kappa})>\alpha$, where  $\text{pto}$ stays for proof theoretic ordinal and $\text{ZFC}_{\kappa}$ is the $\kappa$-th element of the sequence.
I know that the proof theoretic ordinal of ZFC is a recursive ordinal, but it is unknown  and the proof theoretic ordinals are known for theories up to $\Pi^1_2 -\text{CA}_0$. Anyway I am not asking for the explicit proof theoretic ordinals of that sequence, but only if they satisfy the property I have mentioned.
Comment: Which definition of proof-theoretic ordinal are you using?
Comment: this one: https://en.wikipedia.org/wiki/Ordinal_analysis#Definition
Comment: OK, that's the one I've used in my answer.
Comment: yes, I don't know alternative definition maybe you could write a link if  it is possible
Comment: Basically, the other type of definition is the least ordinal such that induction along that ordinal proves the consistency of the system. But this actually isn't very precise (see e.g. [here](https://mathoverflow.net/questions/333519/proof-theoretic-ordinals-inevitable-consistency)).
Answer: I'll assume that $\mathsf{ZFC}$ is at least $\Pi^1_1\vee\Sigma^1_1$-sound, and use the following definition of the proof-theoretic ordinal:

We let $pto(T)$ be the supremum of the lengths of primitive recursive well-orderings which $T$ proves are in fact well-ordered.

Here $T$ is an "appropriate" theory - for simplicity, let's say it's a computably axiomatizable $(\Pi^1_1\vee\Sigma^1_1)$-sound extension of $\mathsf{ZFC}$.
Then we can produce a uniformly primitive recursive family of theories $(T_i)_{i\in I}$ which provably in $\mathsf{ZFC}$ has the following nice properties:

Each $T_a$ is a consistent extension of $\mathsf{ZFC}$ by a single additional axiom.

$I$ is a linear order, and the $T_i$s are ordered by strength appropriately: if $a<_Ib$ then $T_b$ proves every axiom of $T_a$.

For each $\alpha<\omega_1^{CK}$ there is some $a\in I$ such that $T_a$ is $\Pi^1_1\vee\Sigma^1_1$-sound and proves the well-foundedness of some primitive recursive ordering of type $\alpha$.

This uses a couple tricks. First, we apply Barwise-Kreisel Compactness to get a primitive recursive linear ordering $(I,<_I)$ with no hyperarithmetic descending sequences whose well-founded part has type $\omega_1^{CK}$ (these are called Harrison orders). Now for $a\in I$ let $T_a$ be $\mathsf{ZFC}$ + "The initial segment of $I$ up to $a$ is well-founded." The only way $T_a$ could be inconsistent is if $\mathsf{ZFC}$ disproves the well-foundedness of $I_{<a}$. Since $\mathsf{ZFC}$ is $\Pi^1_1$-sound, this can only happen if $a$ is in the illfounded part of $I$; since $I$ has no hyperarithmetic descending sequences, there must be some $b$ in the illfounded part of $I$ such that $T_b$ is consistent (and hence each $T_c$ is consistent for $c<_Ib$). WLOG then $T_a$ is consistent for each $a\in I$ (otherwise replace $I$ with $I_{<b}$).
The only nontrivial point now is to prove that if $a$ is in the well-founded part of $I$ (and remember that has ordertype $\omega_1^{CK}$) then $T_a$ is $\Pi^1_1\vee\Sigma^1_1$-sound. To see this, suppose $T_a$ proves some false $\Pi^1_1\vee\Sigma^1_1$ sentence $\varphi$. Then $\mathsf{ZFC}$ proves the sentence "If $I_{<a}$ is well-founded then $\varphi$," which is a false $\Sigma^1_1\vee(\Pi^1_1\vee\Sigma_1^1)$-sentence, or a false $\Pi^1_1\vee\Sigma^1_1$-sentence. But this contradicts the $\Pi^1_1\vee\Sigma^1_1$-soundness of $\mathsf{ZFC}$.
This is an old argument, but I don't know who it's due to - it may well be folklore.
Comment: Thanks for the answer. Can you elaborate about applying Barwise-Kreisel Compactness or alternatively provide a reference.
Comment: @holmes Ash/Knight's book **Computable structures and the hyperarithmetic hierarchy** has a good chapter on it. Basically, the idea is to consider the set $T$ of computable infinitary sentences consisting of the sentence "This structure is primitive recursive" together with for each computable ordinal $\alpha$ the sentence "$\alpha$ embeds as an initial segment into this structure" (this takes some work to make precise; Ash/Knight do it with "computable" in place of "primitive recursive," but it makes no difference).
Comment: Since every computable ordinal has a primitive recursive copy, $\Sigma^1_1$-bounding says that every $\Delta^1_1$ subset of $T$ is satisfiable, and $T$ itself is $\Pi^1_1$. So by Barwise-Kreisel, $T$ has a model - which is a primitive recursive linear order with a well-founded part of length $\omega_1^{CK}$ (and in particular of the form $\omega+\omega_1^{CK}\cdot\eta+\alpha$ for some computable $\alpha$).


Flutter SingelChildScrollView for column is not working

Question: I have the following code in flutter. The first Expanded with flex 1 can be scrolled if needed but the next Expanded with flex 2 and the list of widgets (createButtons(answerList)) can not be scrolled and I can not figure out why? Both have the scrollable in them!
import 'package:flutter/material.dart';

import '../../backend/QuestionaireConstants/question.dart';
import '../../backend/utils/constants.dart';
import '../../backend/utils/setupcomingRoute.dart';
import '../../backend/widgets/button_content.dart';
import '../../backend/widgets/reusable_cart.dart';

int selectedAnswer = -1;
int counter = 0;

Color determineColor(int selection) {
  return selectedAnswer == selection ? Colors.white : Colors.black;
}

class SelectionWindow extends StatefulWidget {
  const SelectionWindow({Key? key}) : super(key: key);

  @override
  _SelectionWindowState createState() => _SelectionWindowState();
}

class _SelectionWindowState extends State<SelectionWindow> {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as List<Question>;
    int count = args[0].counter;
    int arraylen = args.length;
    List answerList = args[count].possibleAnswers;

    String upcomingRoute = setUpcomingRoute(count, arraylen, args);

    List<Widget> createButtons(list) {
      List<Widget> buttons = [];

      //creating single choice buttons
      for (var i = 0; i < list.length; i++) {
        buttons.add(
          Row(
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      selectedAnswer = i;
                    });
                  },
                  child: ReusableCard(
                    colour: selectedAnswer == i
                        ? Colors.blue.shade900
                        : Colors.blue.shade200,
                    cardChild: ButtonContent(
                      label: args[count].possibleAnswers[i],
                      textColour: determineColor(i),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }

      return buttons;
    }

    //showing error screen
    Future<void> _showMyDialog() async {
      return showDialog<void>(
        context: context,
        barrierDismissible: false, // user must tap button!
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Alert'),
            content: SingleChildScrollView(
              child: ListBody(
                children: const <Widget>[
                  Text('Please select one answer before continuing.'),
                ],
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text(
                  'Approve',
                  style: TextStyle(fontSize: 22),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }

    return Scaffold(
      appBar: AppBar(
        iconTheme: backwardsArrowBlack,
        automaticallyImplyLeading: false,
        title: appBarText,
        backgroundColor: Colors.blue.shade100,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.center,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Text(args[count].questionText,
                    style: multipleChoiceTextStyle),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Column(
              children: [
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: Column(
                    children: createButtons(answerList),
                  ),
                ),
                Expanded(
                  child: Align(
                    alignment: FractionalOffset.bottomCenter,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              if (args[0].counter > 0) {
                                args[0].counter -= 1;
                                args[count - 1].givenAnswers.clear();
                              }
                              Navigator.pop(context);
                            },
                            child: backwardsButton,
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              if (selectedAnswer == -1) {
                                _showMyDialog();
                              } else {
                                args[count].givenAnswers.add(args[count]
                                    .possibleAnswers[selectedAnswer]);
                                selectedAnswer = -1;
                                if (args[0].counter == arraylen - 1) {
                                  args[0].counter += 1;
                                  Navigator.pushNamed(context, '/endScreen',
                                          arguments: args)
                                      .then((_) => setState(() {}));
                                } else {
                                  args[0].counter += 1;
                                  Navigator.pushNamed(
                                    context,
                                    upcomingRoute,
                                    arguments: args,
                                  ).then((_) => setState(() {}));
                                }
                              }
                            },
                            child: forwardButton,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

The emulator shows the following error in case of having many answers in the list that are not fit in the page:
    ====================================================================================================
D/EGL_emulation(15191): app_time_stats: avg=10.35ms min=0.79ms max=89.84ms count=52
D/EGL_emulation(15191): app_time_stats: avg=104.68ms min=0.77ms max=1043.27ms count=11
D/EGL_emulation(15191): app_time_stats: avg=69.44ms min=11.30ms max=1017.83ms count=19
I/flutter (15191): type 'Null' is not a subtype of type 'FutureOr<int>'
D/EGL_emulation(15191): app_time_stats: avg=151.10ms min=0.54ms max=925.70ms count=12

======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 203 pixels on the bottom.

Comment: Can you try to lift your SingleChildScrollView up? As the first child in your Expanded
Comment: are you trying to  make scrollable for full body?
Comment: @YeasinSheikh not all body. The first and second Expanded. The first one works.
Comment: @targiasld not sure what you mean, but it is the first child in its Expanded children under column.
Comment: Can you simplify the widget that will reproduce the same error
Comment: There is no error. The problem is that in case of many answers in the list the scroll functionality is not there. So user can not click on forward symbol in that case.
Comment: ok, sorry. the error is
A RenderFlex overflowed by 203 pixels on the bottom.
Answer: This worked:
import 'package:flutter/material.dart';

import '../../backend/QuestionaireConstants/question.dart';
import '../../backend/utils/constants.dart';
import '../../backend/utils/setupcomingRoute.dart';
import '../../backend/widgets/button_content.dart';
import '../../backend/widgets/reusable_cart.dart';

int selectedAnswer = -1;
int counter = 0;

Color determineColor(int selection) {
  return selectedAnswer == selection ? Colors.white : Colors.black;
}

class SelectionWindow extends StatefulWidget {
  const SelectionWindow({Key? key}) : super(key: key);

  @override
  _SelectionWindowState createState() => _SelectionWindowState();
}

class _SelectionWindowState extends State<SelectionWindow> {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as List<Question>;
    int count = args[0].counter;
    int arraylen = args.length;
    List answerList = args[count].possibleAnswers;

    String upcomingRoute = setUpcomingRoute(count, arraylen, args);

    List<Widget> createButtons(list) {
      List<Widget> buttons = [];

      //creating single choice buttons
      for (var i = 0; i < list.length; i++) {
        buttons.add(
          Row(
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      selectedAnswer = i;
                    });
                  },
                  child: ReusableCard(
                    colour: selectedAnswer == i
                        ? Colors.blue.shade900
                        : Colors.blue.shade200,
                    cardChild: ButtonContent(
                      label: args[count].possibleAnswers[i],
                      textColour: determineColor(i),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }

      return buttons;
    }

    //showing error screen
    Future<void> _showMyDialog() async {
      return showDialog<void>(
        context: context,
        barrierDismissible: false, // user must tap button!
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Alert'),
            content: SingleChildScrollView(
              child: ListBody(
                children: const <Widget>[
                  Text('Please select one answer before continuing.'),
                ],
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text(
                  'Approve',
                  style: TextStyle(fontSize: 22),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }

    return Scaffold(
      appBar: AppBar(
        iconTheme: backwardsArrowBlack,
        automaticallyImplyLeading: false,
        title: appBarText,
        backgroundColor: Colors.blue.shade100,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.center,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Text(args[count].questionText,
                    style: multipleChoiceTextStyle),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: SingleChildScrollView(
              child:  Column(
                children: createButtons(answerList),
              ),
            ),
          ),
                Expanded(
                  child: Align(
                    alignment: FractionalOffset.bottomCenter,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              if (args[0].counter > 0) {
                                args[0].counter -= 1;
                                args[count - 1].givenAnswers.clear();
                              }
                              Navigator.pop(context);
                            },
                            child: backwardsButton,
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              if (selectedAnswer == -1) {
                                _showMyDialog();
                              } else {
                                args[count].givenAnswers.add(args[count]
                                    .possibleAnswers[selectedAnswer]);
                                selectedAnswer = -1;
                                if (args[0].counter == arraylen - 1) {
                                  args[0].counter += 1;
                                  Navigator.pushNamed(context, '/endScreen',
                                          arguments: args)
                                      .then((_) => setState(() {}));
                                } else {
                                  args[0].counter += 1;
                                  Navigator.pushNamed(
                                    context,
                                    upcomingRoute,
                                    arguments: args,
                                  ).then((_) => setState(() {}));
                                }
                              }
                            },
                            child: forwardButton,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
  }
}


Setting axios timeout value has no effect

Question: we have set the timeout in the code like
    axios.defaults.timeout === 3000;
......
 try {
        const aData = await axios.get(Url, {
            headers: {
                'Authorization': authToken.authHeaderValue,
            },
            httpAgent: new https.Agent({
                keepAlive: true
            }),
        });
....

However in the static code analysis(polaris synopsis) test it shows as
Discarding the result of operator "===" in "axios.defaults.timeout === 3000". What was this code intended to accomplish?

Is this setting or assignment of the variable discarded?
Comment: Instead of doing that you can use setTimeout function and inside that you can call add your axios code.
Answer: The === operator in Javascript is a boolean test, not an assignment.  The line of code:
axios.defaults.timeout === 3000;

has no effect.  Presumably, it was intended to set timeout, for example:
axios.defaults.timeout = 3000;

The erroneous syntax in question, using ===, evidently (from a comment) comes from a medium.com article (blog) by Ekebor Kelechi, Axios.defaults.timeout.  That article obviously has a mistake, intending to use =, as === by itself never has an effect in Javascript.
Comment: i referred to this post. https://kelechiekebor.medium.com/axios-defaults-timeout-4803b93d076d. to set the timeout
Comment: @reachjaango The article is mistaken.  I have updated my answer to mention it.


Switching between views not working for iPhone 5.1 (XCode 4.3.2)

Question: I'm trying to develop an iPhone app that uses 4 views(View-based app), and I want to navigate from one view to the other. It would be ideal if for example the Submit ID button automatically sent a message to UIViewController to switch to View 2, and selecting a cell in View 2 would load View 3.
See a screenshot of the Storyboard here.
I'm not sure how to do that, so I've tried using a separate button to switch between views, but that isn't working either and I can't figure out why.
You can have a look at the source code which I've uploaded to Dropbox.
Comment: You cant expect people to download, unzip and work through your whole project. Can you include more detail in your question? What is the view switching code you have tried to implement? You have a lot of push segues in your storyboard, but it is not possible to tell if your view controllers are embedded in a navigation controller. If you want to switch between 4 views in any order, should you use a tab bar controller?
Answer: First, I would suggest posting your code in your question. As appreciative as I'm sure other people are that you provided a dropbox link to the code, most people presumably have little interest in downloading the file to their computer, unzipping, and launching the project (me being one of them).
That being said, let's make sure you're clear on Storyboards and the general view controller hierarchy principles. You have, in your storyboard, four UIViewControllers dragged out into your workspace. So, you're not switching the views of a single UIViewController, telling it to switch from View1 to View2 to View3 and so on. You need to be telling the view controller hierarchy (which, in your case, probably needs to be managed by a UINavigationController), to push and/or pop view controller on and off its stack. It appears that you have some segues set up between your view controllers. Are you calling performSegueWithIdentifier:sender: in your code? Alternatively, you could hook up the Submit ID button to perform a push segue to View Controller 2 in much the same manner.
Once you have that working, you can override prepareForSegue:sender: to send information from ViewController1 to ViewController2 and so on.


Mudança de Abas

Question: Tenho um menu de abas que conforme vai selecionando as abas vai mudando o conteúdo.
Mudança das abas:

A minha dúvida é: "Como limpar os dados da aba anterior ao se selecionar outra aba?"
Imagem do menu:
Chamo o AlternarAbas() no menu onde é escolhida a opção desejada:

    Usuario
    Empresa
    Nota Fiscal
    Software

Os dados ao qual me refiro são os que o usuário digita. Ou seja, caso o usuário digite algo na área do incluir do Usuário e logo depois mudar para Empresa, os dados que ele informou no incluir sumirão!
imagem do incluir:
Funciona se for chamado por um iframe?

Answer: Para que possas alternar de aba e proceder à limpeza dos valores preenchidos no formulário via JavaScript, deverás fazer uso do método reset() que vai repor o formulário para os valores iniciais:
Exemplo no JSFiddle
O teu código alterado
O teu código foi alterado para incluir um novo parâmetro que diz respeito ao formulário:
function stAba(menu,conteudo,formulario)
{
  this.menu = menu;
  this.conteudo = conteudo;
  this.formulario = formulario;
}

var arAbas = new Array();
arAbas[0] = new stAba('td_usua', 'div_usua', 'form_usua');
arAbas[1] = new stAba('td_empr', 'div_empr', 'form_empr');
arAbas[2] = new stAba('td_nota', 'div_nota', 'form_nota');
arAbas[3] = new stAba('td_soft', 'div_soft', 'form_soft');

function AlternarAbas(menu, conteudo, formulario)
{
  for (i=0;i<arAbas.length;i++)
  {
   m = document.getElementById(arAbas[i].menu);
   m.className = 'menu';
   c = document.getElementById(arAbas[i].conteudo)
   c.style.display = 'none';
   f = document.getElementById(arAbas[i].formulario);
   f.reset();
  }
  m = document.getElementById(menu)
  m.className = 'menu-sel';
  c = document.getElementById(conteudo)
  c.style.display = '';
}

A chamada passa a ser:
// O terceiro parâmetro é o ID for formulário alvo.
AlternarAbas('td_usua','div_usua', 'form_usua');

Comment: Obrigado pela ajuda @Zuul era por isso mesmo que eu procurava! Mesmo não funcionando em meu código, eu decodifico ele para implementar. Mas a ideia era essa mesma que eu queria ^^

Mudança de Abas


Printing a scoreboard with a sliding arrow C++ beginner

Question: I am working on a program to code a game called Devil's Dice.  I have the logic of code working perfectly, but I am struggling to print the scoreboard to show the games progress.  The details of the assignment are below, followed by my code.  I don't know where to begin printing the scoreboard as shown in the image I linked.
In our version of Devil's Dice the rules will be as follows:
The player repeatedly rolls a 6-sided die until either a 1 is rolled or the player decides to "hold".

If the player rolls a 1, they lose any points accumulated this turn and the devil gets a turn.
If the player rolls any other number, it is added to their turn total and the player's turn continues.
If a player chooses to "hold", their current turn total is added to their score and the devil gets a turn.

Devil's Logic
If the score is tied or the devil is winning, he will keep rolling until he has at least 21 points (unless he has already reached 100 points)
If the player is winning, the devil will keep rolling until he has at least 30 points (unless he has already reached 100 points)
If the devil rolls a 1, he also loses the points he has accumulated on his turn
If the player chooses to "forfeit", they lose and the game is over.
The player must score 100 points before the devil manages to do so in order to win.
For example, the player, Ann, begins a turn with a roll of 5. Ann could hold and score 5 points, but chooses to roll again. Ann rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Ann rolls a 1, and must end her turn without scoring. The devil then rolls the sequence 4-5-3-5-5, chooses to hold, and adds his turn total of 22 points to his score.
There are a few other details about the game logic but i am confident i have it working correctly.  I am just wondering how to get a menu with a moving arrow as shown below.

My code looks like this:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main() { //just for a school grading program//
#ifdef JARVIS
    srand(0);
#else
    srand(time(NULL));
#endif
// Call your functions to play your game here...

    char userInput;
    int diceRoll;
    int turnScore = 0;
    int totalScore = 0;
    int devilScore = 0;
    bool isItDevilsTurn = false;
    bool winner = false;
    int devilWins = 0;
    int playerWins = 0;

    cout << "---- Welcome to Devil's Dice! ----" << endl;
    cout << "Hold[h], roll[r], or forfeit[f]: " << endl;

    while (!winner) {
        if (!isItDevilsTurn) {
            cin >> userInput;

            if (userInput == 'h')
            {
                totalScore = totalScore + turnScore;
                cout << "You banked " << turnScore << " points and have a total of " << totalScore << " points" << endl;
                isItDevilsTurn = true;
                turnScore = 0;
            }

            if (userInput == 'r')
            {
                diceRoll = rand() % 6 + 1;

                if (diceRoll > 1)
                {
                    cout << "You rolled a " << diceRoll << "!" << endl;
                    turnScore = turnScore + diceRoll;
                }
                else
                {
                    cout << "You rolled a 1 :(" << endl;
                    turnScore = 0;
                    isItDevilsTurn = true;

                }
            }

            if (totalScore >= 100) {
                winner = true;
                cout << "You Win!" << endl;
                playerWins = playerWins + 1;
            }

            if (userInput == 'f') {
                cout << "Game Over!" << endl;
            }

        }
        else
        {
            int devilGoal = 21;

            if (totalScore > devilScore)
            {
                devilGoal = 30;
            }

            while (isItDevilsTurn)
            {
                diceRoll = rand() % 6 + 1;
                if (diceRoll > 1 && turnScore < devilGoal)
                {
                    cout << "devil rolled " << diceRoll << endl;
                    turnScore = turnScore + diceRoll;

                }
                else if (diceRoll > 1 && turnScore > devilGoal)
                {
                    devilScore = devilScore + turnScore;
                    cout << "devil holds " << turnScore << " points and now has " << devilScore << " points" << endl;
                    isItDevilsTurn = false;
                    turnScore = 0;

                }
                else
                {
                    cout << "devil rolled a 1" << endl;
                    isItDevilsTurn = false;
                    turnScore = 0;
                }

                if (devilScore >= 100)
                {
                    cout << "Devil Wins!" << endl;
                    devilWins = devilWins + 1;
                    winner = true;
                }

            }
        }
    }

    cout << "Total Wins: " << playerWins << endl;
    cout << "Total Losses: " << devilWins << endl;

    fstream output("games.txt");
    output << playerWins << " " << devilWins << endl;
    return 0;

}

Comment: What's your actual question? Please be precise. You don't seem to be printing any part of the scoreboard yet.
Comment: i do not know how to print a scoreboard that looks like that.  And i do not know how to move the 'pointer' once i do.  Sorry for the confusion
Comment: My question is simply, how to use my existing code to print a scoreboard that matches the one shown with the --> moving to match the user and devil's score.
Comment: Your existing code doesn't print a scoreboard, you will need to write new code.
Answer: I'm sorry, I'm not too good with tabs, so you just make it looks like you need to. I used a ternary operator to understand if I need to write number or a tab in cuurent line
printf("\tPlayer\t\t\tDevil\n");
printf("\t------\t\t\t-----\n");
for(int i = 10; i >= 0; --i){
      printf((totalScore < (i+1)*10 && totalScore >=i*10) ? "%d >" : "\t", totalScore);
      printf("--%d", i*10);
      printf((turnScore < (i+1)*10 && turnScore >=i*10) ? "< %d" : "\t\t\t", turnScore);
      printf((devilTotal < (i+1)*10 && devilTotal >=i*10) ? "%d >" : "\t", devilTotal);
      printf("--%d", i*10);
      printf((devilTurn < (i+1)*10 && devilTurn >=i*10) ? "< %d" : "\t\t", devilTurn);
      printf("\n");
}

How it works? first printf() I evaluate totalScore, if it's less then next value and more than current I print it, otherwise just print tab. Second printf() prints current value. Third printf() evalutes turnScore, if it's less then next value and more than current I print it, otherwise just print 2 tabs.
Same for devil.
It would be the same with cin and cout, it's just that I feel more confident with printf(). If it looks right, all you need to do is work with alignments.


Finding all solutions $f$ of $\int_0^{\pi/2} f(\theta_i, \theta_o) \sin 2\theta_o d\theta_o=\sin^2\theta_i$ with conditions $f(a, b) = f(b,a) \geq 0$

Question: My problem is the following: I am looking for all possible functions $f(\theta_\text{i}, \theta_\text{o})$ with $f(\theta_\text{i}, \theta_\text{o}) \in \mathbb{R} \ \forall \ (\theta_\text{i}, \theta_\text{o}) \in [0, \pi/2]^2$ that verify the following equation and conditions:
$$\int_0^{\pi/2} f(\theta_\text{i}, \theta_\text{o}) \sin 2\theta_\text{o} \,  \text{d}\theta_\text{o} = \sin^2 \theta_\text{i}$$
$$f(\theta_\text{i}, \theta_\text{o}) = f(\theta_\text{o}, \theta_\text{i}) \quad \text{and} \quad f(\theta_\text{i},\theta_\text{o}) \geq 0 \ \forall \ (\theta_\text{i}, \theta_\text{o})$$
Even if the question is simple, I am struggling to start... I have tried integration by part, I also tried to derivate by $\theta_\text{i}$ in both sides, or the King's property... But I am going nowhere.
I will take any advice.
Comment: Where did this problem come from?
Comment: @TedShifrin I am studying physically based rendering, and this problem applies to a material reflectivity model that I am trying to develop. The special condition required corresponds to a special case of the Helmholtz reciprocity principle.
Comment: By integrating by parts, this can become: $$\sin^2(\theta_\text{i}) = f\left(\theta_\text{i}, \pi/2\right) + \int_0^{\pi/2} \frac{\partial f}{\partial \theta_\text{o}}(\theta_\text{i}, \theta_\text{o}) \sin^2(\theta_\text{o}) \,  \text{d}\theta_\text{o}$$ meaning that it's like an integral equation with a kernel except you'd solve for the kernel in a way? By that I mean it's of the form $u(x) - \int_a^b K(x,y) u(y) \mathrm{d} y = g(x)$ but you'd solve for $K$.
Comment: Ah it should be a $-$ in my first equation but five minutes have passed so I cannot edit it.
Comment: This suggests that $-\partial f/\partial\theta_0$ should be a delta function concentrated on the diagonal. This is not compatible with the desired symmetry of $f$.
Answer: Split the LHS integral from 0 to $\theta_i$ then from $\theta_i$ to $\frac{\pi}{2}$ and you also have : $\sin^2(\theta_i) = \int_{0}^{\theta_i} \sin(2
 \theta_o) d \theta_o$
Comment: So can there be any $f$ as the OP wishes?
Comment: @TedShifrin yes
Comment: Can you develop your point? I don't understand how the second integral vanishes.
Comment: Just bring it to the LHS , specifically to the integral going from 0 to $\theta_i$ you get a 0 on the RHS


Primefaces Calendar Listener - ERROR [io.undertow.request]

Question: I'm trying to use a listener on Calendar. I'm doing the following:

lista.xhtml

MovimentacaoBean
public void definePeriodo(){
  System.out.println("entrou");
}

and I'm getting the error below

2017-11-27 12:43:20,731 ERROR [io.undertow.request] (default task-10)
  UT005023: Exception handling request to
  /paginas/financeiro/lista.xhtml: java.lang.RuntimeException:
  java.lang.NullPointerException    at
  io.undertow.servlet.spec.RequestDispatcherImpl.forwardImpl(RequestDispatcherImpl.java:245)
    at
  io.undertow.servlet.spec.RequestDispatcherImpl.forwardImplSetup(RequestDispatcherImpl.java:147)
    at
  io.undertow.servlet.spec.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:111)
    at
  org.ocpsoft.rewrite.servlet.impl.HttpRewriteResultHandler.handleResult(HttpRewriteResultHandler.java:42)
    at
  org.ocpsoft.rewrite.servlet.RewriteFilter.rewrite(RewriteFilter.java:297)
    at
  org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:198)
    at
  io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at
  io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at
  io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at
  io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at
  io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at
  org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at
  org.wildfly.swarm.generated.FaviconErrorHandler.handleRequest(FaviconErrorHandler.java:62)
    at
  io.undertow.server.handlers.PathHandler.handleRequest(PathHandler.java:94)
    at
  io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at
  io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at
  io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at
  io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at
  io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at
  io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at
  io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at
  io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at
  org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at
  io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at
  io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at
  io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at
  io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at
  io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at
  io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at
  io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at
  io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at
  io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at
  io.undertow.server.Connectors.executeRootHandler(Connectors.java:211)
    at
  io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:809)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Update
If I use the same listener on other field (inputText with blur event for example), its works well!
Update I
I tried do this and did not work
public void definePeriodo(SelectEvent event){
    System.out.println("entrou");
}

Comment: What version of primefaces are you using? Try to use the most recent version if that's not the case.
Answer: I found my error..
My exception handler factory was causing this error....


Has there ever been 3 goals in the same match with the same scorer and assister?

Question: Has there ever been 3 (or more) goals in the same match with not only had the same scorer for each, but where all assisted by the same player?
In other-words a hat-trick for both goals and assists.
I'm only counting fully professional matches OR internationals.
Answer: Yes.
In a Premier League match between Tottenham Hotspur and Southampton, in September 2020, Son Heung-Min scored four goals for Tottenham, with Harry Kane assisting all four. You can find the match report here.


split string on a number of different characters

Question: I'd like to split a string using one or more separator characters.
E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].
At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.
def my_split(string, split_chars):
    if isinstance(string_L, basestring):
        string_L = [string_L]
    try:
        split_char = split_chars[0]
    except IndexError:
        return string_L

    res = []
    for s in string_L:
        res.extend(s.split(split_char))
    return my_split(res, split_chars[1:])

print my_split("a b.c", [' ', '.'])

Horrible! Any better suggestions?
Comment: is that "a b.c" ( a space b dot c )? Do you have more sample input?
Comment: Yes that's right. I've updated the question to be a bit clearer
Answer: >>> import re
>>> re.split('[ .]', 'a b.c')
['a', 'b', 'c']

Comment: And remember, that characters have to be in squere brackets []. I forgot about that and lost at least 20 minutes. With out brackets `split()` splits acording to whole string.
Answer: This one replaces all of the separators with the first separator in the list, and then "splits" using that character.
def split(string, divs):
    for d in divs[1:]:
        string = string.replace(d, divs[0])
    return string.split(divs[0])

output:
>>> split("a b.c", " .")
['a', 'b', 'c']

>>> split("a b.c", ".")
['a b', 'c']

I do like that 're' solution though.
Answer: Solution without re:
from itertools import groupby
sep = ' .,'
s = 'a b.c,d'
print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k]

An explanation is here https://stackoverflow.com/a/19211729/2468006
Answer: Not very fast but does the job:
def my_split(text, seps):
  for sep in seps:
    text = text.replace(sep, seps[0])
  return text.split(seps[0])


Laravel collection using map and contains

Question: I am having problem with available key in the map collection.
The available key use contains method. It should return true if the value of product id in $unavailableProducts does not contain in $products ($value->product_id == $product->id)
What did I do wrong?
    $unavailableProducts = $this->unavailableProducts();
    $products = $this->products->all();

    $allProducts = $products->map(function ($product) use($unavailableProducts) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => $unavailableProducts['result']->contains(function ($value, $key) use ($product) {
            if ($value->product_id == $product->id) {
                return false;
            }
            return true;
        }),
    ];
});

Comment: Are you sure `$unavailableProducts['result']` is a collection? If not, just wrap it: `collect($unavailableProducts['result'])`
Answer: First, make sure that $unavailableProductions['result'] is a collection.
Second, change your contains method like this:
$unavailableProducts = $this->unavailableProducts();
$products = $this->products->all();

$allProducts = $products->map(function ($product) use($unavailableProducts) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => $unavailableProducts['result']->contains('id', $product->id),
    ];
});

The $unavailableProducts['result']->contains('id', $product->id) will determine if the $unaviableProductions['result'] collection has a key id where the value is $product->id
Answer: You can try this approach
 $policyPackageDetails = PolicyPackage::where('isactive', '=', 1)->where('id', '=', $pid)
            ->with('policy_package_details')
            ->select('id',
                     'title',
                     'subtitle',
                     'shorttitle',
            )
            ->get();

        $policyPackageDetails = $policyPackageDetails ->map(function ($item){
            return collect([
                'id' => $item->id,
                'title' => $item->title,
                'subtitle' => $item->subtitle,
                'short_title' => $item->shorttitle,
                'policy_package_details' => $item->policy_package_details->map(function ($details){
                    return [
                        'attribute_name' => $details->attname,
                        'attribute_value' => $details->attvalue,
                    ];
                }),
            ]);
        });

here fetching data from relational models, remaining & filtering them, the output will be like
[
    {
        "id": 61,
        "title": " Health (Platinum)",
        "subtitle": "for 1 year",
        "short_title": "HL-SHP-1",
         "policy_package_details": [
            {
                "attribute_name": "in",
                "attribute_value": "180000"
            },
            {
                "attribute_name": "out",
                "attribute_value": "20000"
            }
        ]
    }
]