text:
package bean;

import modelo.Funcionario;
import dao.ContratoDao;
import dao.SeguroDao;
import dao.VeiculoDao;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import lib.Moeda;
import mensagem.Mensagem;
import mensagem.Message;
import modelo.ComoBox;
import modelo.Incendio;
import modelo.IncendioRisco;
import org.primefaces.context.RequestContext;
import sessao.SessionUtil;
import validacao.Validacao;

/**
 *
 * @author Helio
 */
@ManagedBean
@ViewScoped
public class IncendioBean implements Serializable
{
    private static final long serialVersionUID = 1L;
    private Incendio incendio = new Incendio();
    private IncendioRisco incendioRisco = new IncendioRisco();
    private ArrayList<IncendioRisco> riscos;
    private SeguroDao sd;
    private ArrayList<String> riscosIncendio;
    @ManagedProperty(value = "#{listaRespostas}")
    private ListaRespostas listaRespostas;
    private String info;
    private VeiculoDao veiculoDao;
    private final List<ComoBox> moeda;
    private float percentagemRetirar = 100-(5+0.6f);
    private HttpSession session = ( HttpSession ) FacesContext.getCurrentInstance().getExternalContext().getSession( true );
    @SuppressWarnings("LeakingThisInConstructor")
    public IncendioBean()
    {
        sd = new SeguroDao();
        veiculoDao = new VeiculoDao();
        moeda = veiculoDao.moedas();
        riscos = new ArrayList<>();
        riscosIncendio = new ArrayList<>();
         if(SessionUtil.obterValor("FR")!=null)//respostas
         {
            RequestContext.getCurrentInstance().execute("checkApolice('"+SessionUtil.obterValor(SessionUtil.APOLICE_CONTRATO_SEGURO)+"')");
             IncendioBean ib = ((IncendioBean) SessionUtil.obterValor("FR"));
             for (Field f : this.getClass().getDeclaredFields()) {
                 try {
                     f.setAccessible(true);
                     f.set(this, f.get(ib));
                 } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                 }
             }
             RequestContext.getCurrentInstance().execute("backAndcontine()");
         }
    }

    public IncendioBean(String isnull){
        sd = null;
        info = null;
        moeda = null;
    }

    public Incendio getIncendio()
    {
        return (incendio == null) ? incendio = new Incendio() : incendio;
    }

    public ArrayList<IncendioRisco> getRiscos() {
        return riscos;
    }

    public void setRiscos(ArrayList<IncendioRisco> riscos) {
        this.riscos = riscos;
    }

    public ArrayList<String> getRiscosIncendio() {
        return riscosIncendio;
    }

    public void setRiscosIncendio(ArrayList<String> riscosIncendio) {
        this.riscosIncendio = riscosIncendio;
    }

    public ListaRespostas getListaRespostas() {
        return listaRespostas;
    }

    public void setListaRespostas(ListaRespostas listaRespostas) {
        this.listaRespostas = listaRespostas;
    }

    public void setIncendio(Incendio incendio) {
        this.incendio = incendio;
    }

    public IncendioRisco getIncendioRisco()
    {
        return (incendioRisco == null) ? incendioRisco = new IncendioRisco() : incendioRisco;
    }

    public void setIncendioRisco(IncendioRisco incendioRisco) {
        this.incendioRisco = incendioRisco;
    }

    public void RiscoAviao(String param)
    {
        if(!incendioRisco.getAviaoTaxa().isEmpty()&&!incendioRisco.getAviaoValor().isEmpty())
        {
            incendioRisco.setAviaoPremio(caluclar(incendioRisco.getAviaoValor(),incendioRisco.getAviaoTaxa())+"");
            incendioRisco.setAviaoPremioMoeda(Moeda.format(caluclar(incendioRisco.getAviaoValor(),incendioRisco.getAviaoTaxa())));
        }
        else
        {
            incendioRisco.setAviaoPremio("");
            incendioRisco.setAviaoPremioMoeda("");
        }
    }

    public void RiscoColisao(String param)
    {
        if(!incendioRisco.getColisaoTaxa().isEmpty()&&!incendioRisco.getColisaoValor().isEmpty())
        {
            incendioRisco.setColisaoPremio(caluclar(incendioRisco.getColisaoValor(),incendioRisco.getColisaoTaxa())+"");
            incendioRisco.setColisaoPremioMoeda(Moeda.format(caluclar(incendioRisco.getColisaoValor(),incendioRisco.getColisaoTaxa())));
        }
        else
        {
            incendioRisco.setColisaoPremio("");
            incendioRisco.setColisaoPremioMoeda("");
        }
    }

    public void RiscoExplosao(String param)
    {
       if(!incendioRisco.getExplosaoTaxa().isEmpty()&&!incendioRisco.getExplosaoValor().isEmpty())
        {
            incendioRisco.setExplosaoPremio(""+caluclar(incendioRisco.getExplosaoValor(),incendioRisco.getExplosaoTaxa()));
            incendioRisco.setExplosaoPremioMoeda(Moeda.format(caluclar(incendioRisco.getExplosaoValor(),incendioRisco.getExplosaoTaxa())));
        }
       else
       {
           incendioRisco.setExplosaoPremio("");
           incendioRisco.setExplosaoPremioMoeda("");
       }
    }

    public void RiscoTerramoto(String param)
    {
        if(!incendioRisco.getTerramotoValor().isEmpty()&&!incendioRisco.getTerramotoTaxa().isEmpty())
        {
            incendioRisco.setTerramotoPremio(caluclar(incendioRisco.getTerramotoValor(),incendioRisco.getTerramotoTaxa())+"");
            incendioRisco.setTerramotoPremioMoeda(Moeda.format(caluclar(incendioRisco.getTerramotoValor(),incendioRisco.getTerramotoTaxa())));
        }
        else
        {
            incendioRisco.setTerramotoPremio("");
            incendioRisco.setTerramotoPremioMoeda("");
        }
    }

    public void RiscoTempestade(String param)
    {
        if(!incendioRisco.getTempestadeValor().isEmpty()&&!incendioRisco.getTempestadeTaxa().isEmpty())
        {
            incendioRisco.setTempestadePremio(""+caluclar(incendioRisco.getTempestadeValor(),incendioRisco.getTempestadeTaxa()));
            incendioRisco.setTempestadePremioMoeda(Moeda.format(caluclar(incendioRisco.getTempestadeValor(),incendioRisco.getTempestadeTaxa())));
        }
        else
        {
            incendioRisco.setTempestadePremio("");
            incendioRisco.setTempestadePremioMoeda("");
        }
    }

    public void RiscoAfundamento(String param)
    {
        if(!incendioRisco.getAfundamentoValor().isEmpty()&&!incendioRisco.getAfundamentoTaxa().isEmpty())
        {
            incendioRisco.setAfundamentoPremio(""+caluclar(incendioRisco.getAfundamentoValor(),incendioRisco.getAfundamentoTaxa()));
            incendioRisco.setAfundamentoPremioMoeda(Moeda.format(caluclar(incendioRisco.getAfundamentoValor(),incendioRisco.getAfundamentoTaxa())));
        }
        else
        {
           incendioRisco.setAfundamentoPremio("");
           incendioRisco.setAfundamentoPremioMoeda("");
        }
    }

    public void RiscoRiscoPolitico(String param)
    {
        if(!incendioRisco.getRiscoPoliticoValor().isEmpty()&&!incendioRisco.getRiscoPoliticoTaxa().isEmpty())
        {
            incendioRisco.setRiscoPoliticoPremio(""+caluclar(incendioRisco.getRiscoPoliticoValor(),incendioRisco.getRiscoPoliticoTaxa()));
            incendioRisco.setRiscoPoliticoPremioMoeda(Moeda.format(caluclar(incendioRisco.getRiscoPoliticoValor(),incendioRisco.getRiscoPoliticoTaxa())));
        }
        else
        {
            incendioRisco.setRiscoPoliticoPremio("");
            incendioRisco.setRiscoPoliticoPremioMoeda("");
        }
    }

    public void RiscoDanoMalicioso(String param)
    {
        if(!incendioRisco.getDanoValor().isEmpty()&&!incendioRisco.getDanoTaxa().isEmpty())
        {
            incendioRisco.setDanoPremio(""+caluclar(incendioRisco.getDanoValor(),incendioRisco.getDanoTaxa()));
            incendioRisco.setDanoPremioMoeda(Moeda.format(caluclar(incendioRisco.getDanoValor(),incendioRisco.getDanoTaxa())));
        }
        else
        {
            incendioRisco.setDanoPremio("");
            incendioRisco.setDanoPremioMoeda("");
        }
    }

    public void RiscoTumulto(String param)
    {
        if(!incendioRisco.getTumultoValor().isEmpty()&&!incendioRisco.getTumultoTaxa().isEmpty())
        {
            incendioRisco.setTumultoPremio(""+caluclar(incendioRisco.getTumultoValor(),incendioRisco.getTumultoTaxa()));
            incendioRisco.setTumultoPremioMoeda(Moeda.format(caluclar(incendioRisco.getTumultoValor(),incendioRisco.getTumultoTaxa())));
        }
        else
        {
            incendioRisco.setTumultoPremio("");
            incendioRisco.setTumultoPremioMoeda("");
        }
    }

    public void RiscoIncendioFlorestal(String param)
    {
        if(!incendioRisco.getIncendioFValor().isEmpty()&&!incendioRisco.getIncendioFTaxa().isEmpty())
        {
            incendioRisco.setIncendioFPremio(""+caluclar(incendioRisco.getIncendioFValor(),incendioRisco.getIncendioFTaxa()));
            incendioRisco.setIncendioFPremioMoeda(Moeda.format(caluclar(incendioRisco.getIncendioFValor(),incendioRisco.getIncendioFTaxa())));
        }
        else
        {
            incendioRisco.setIncendioFPremio("");
            incendioRisco.setIncendioFPremioMoeda("");
        }
    }

    public void RiscoExplosaoEspontanea(String param)
    {
        if(!incendioRisco.getExplosaoExTaxa().isEmpty()&&!incendioRisco.getExplosaoExValor().isEmpty())
        {
            incendioRisco.setExplosaoExPremio(""+caluclar(incendioRisco.getExplosaoExValor(),incendioRisco.getExplosaoExTaxa()));
            incendioRisco.setExplosaoExPremioMoeda(Moeda.format(caluclar(incendioRisco.getExplosaoExValor(),incendioRisco.getExplosaoExTaxa())));
        }
        else
        {
            incendioRisco.setExplosaoExPremio("");
            incendioRisco.setExplosaoExPremioMoeda("");
        }
    }

    public void RiscoRotura(String param)
    {
        if(!incendioRisco.getRoturaValor().isEmpty()&&!incendioRisco.getRoturaTaxa().isEmpty())
        {
            incendioRisco.setRoturaPremio(""+caluclar(incendioRisco.getRoturaValor(),incendioRisco.getRoturaTaxa()));
            incendioRisco.setRoturaPremioMoeda(Moeda.format(caluclar(incendioRisco.getRoturaValor(),incendioRisco.getRoturaTaxa())));
        }
        else
        {
            incendioRisco.setRoturaPremio("");
            incendioRisco.setRoturaPremioMoeda("");
        }
    }

    public void dadosIncendio(MultiRiscoBean multiRiscoBean)
    {
        if(session.getAttribute("S") != null && session.getAttribute("S").toString().split(";")[0].equalsIgnoreCase("mr"))
            calcularMultiRisco(multiRiscoBean);
        else
            calcular();
    }
    public void calcular()
    {
        riscos.clear();
        riscosIncendio.clear();
        @SuppressWarnings("UnusedAssignment")
        Float premioBruto = 0f, premioLiquido = 0f, totalSegurado = 0f;
        Float aviao = 0f,terramoto = 0f,colisao = 0f,tempestade = 0f,explosao = 0f,afundamento = 0f,politico = 0f,dano = 0f,
        tumulto = 0f,incendioF = 0f,explosaoF = 0f,rotura = 0f,aviao2 = 0f,terramoto2 = 0f,colisao2 = 0f,tempestade2 = 0f
        ,explosao2 = 0f,afundamento2 = 0f,politico2 = 0f,dano2 = 0f,tumulto2 = 0f,incendioF2 = 0f,explosaoF2 = 0f,rotura2 = 0f;
        if(verificarNumeroRegistro() == true && validaNumeroApolice() == true)
        {
            if (incendioRisco.getRiscoAviaoId().equals("true"))
            {
                aviao = (incendioRisco.getAviaoValor() != null && incendioRisco.getAviaoValor().length()>0) ? Float.valueOf(incendioRisco.getAviaoValor()) : -1f;
                aviao2 = (incendioRisco.getAviaoPremio() != null && incendioRisco.getAviaoPremio().length()>0) ? Float.valueOf(incendioRisco.getAviaoPremio()) : -1f;
                riscosIncendio.add("103;"+incendioRisco.getAviaoValor() + ";" + incendioRisco.getAviaoTaxa() + ";" + incendioRisco.getAviaoPremio());
            }
            if (incendioRisco.getColisaoId().equals("true")) {
                colisao = (incendioRisco.getColisaoValor() != null && incendioRisco.getColisaoValor().length()>0) ? Float.valueOf(incendioRisco.getColisaoValor()) : -1f;
                colisao2 = (incendioRisco.getColisaoPremio() != null && incendioRisco.getColisaoPremio().length()>0) ? Float.valueOf(incendioRisco.getColisaoPremio()) : -1f;
                riscosIncendio.add("104;"+incendioRisco.getColisaoValor() + ";" + incendioRisco.getColisaoTaxa() + ";" + incendioRisco.getColisaoPremio());
            }
            if (incendioRisco.getExplosaoId().equals("true")) {
                explosao = (incendioRisco.getExplosaoValor() != null && incendioRisco.getExplosaoValor().length()>0) ? Float.valueOf(incendioRisco.getExplosaoValor()) : -1f;
                explosao2 = (incendioRisco.getExplosaoPremio() != null && incendioRisco.getExplosaoPremio().length()>0) ? Float.valueOf(incendioRisco.getExplosaoPremio()) : -1f;
                riscosIncendio.add("105;"+incendioRisco.getExplosaoValor() + ";" + incendioRisco.getExplosaoTaxa() + ";" + incendioRisco.getExplosaoPremio());
            }
            if (incendioRisco.getTerramotoId().equals("true")) {
                terramoto2 = (incendioRisco.getTerramotoPremio() != null && incendioRisco.getTerramotoPremio().length()>0) ? Float.valueOf(incendioRisco.getTerramotoPremio()) : -1f;
                terramoto = (incendioRisco.getTerramotoValor() != null && incendioRisco.getTerramotoValor().length()>0) ? Float.valueOf(incendioRisco.getTerramotoValor()) : -1f;
                riscosIncendio.add("106;"+incendioRisco.getTerramotoValor() + ";" + incendioRisco.getTerramotoTaxa() + ";" + incendioRisco.getTerramotoPremio());
            }
            if (incendioRisco.getTempestadeId().equals("true")) {
                tempestade = (incendioRisco.getTempestadeValor() != null && incendioRisco.getTempestadeValor().length()>0) ? Float.valueOf(incendioRisco.getTempestadeValor()) : -1f;
                tempestade2 = (incendioRisco.getTempestadePremio() != null && incendioRisco.getTempestadePremio().length()>0) ? Float.valueOf(incendioRisco.getTempestadePremio()) : -1f;
                riscosIncendio.add("107;"+incendioRisco.getTempestadeValor() + ";" + incendioRisco.getTempestadeTaxa() + ";" + incendioRisco.getTempestadePremio());
            }
            if (incendioRisco.getAfundamentoId().equals("true")) {
                afundamento = (incendioRisco.getAfundamentoValor() != null && incendioRisco.getAfundamentoValor().length()>0) ? Float.valueOf(incendioRisco.getAfundamentoValor()) : -1f;
                afundamento2 = (incendioRisco.getAfundamentoPremio() != null && incendioRisco.getAfundamentoPremio().length()>0) ? Float.valueOf(incendioRisco.getAfundamentoPremio()) : -1f;
                riscosIncendio.add("108;"+incendioRisco.getAfundamentoValor() + ";" + incendioRisco.getAfundamentoTaxa() + ";" + incendioRisco.getAfundamentoPremio());
            }
            if (incendioRisco.getRiscoPoliticoId().equals("true")) {
                politico = (incendioRisco.getRiscoPoliticoValor() != null && incendioRisco.getRiscoPoliticoValor().length()>0) ? Float.valueOf(incendioRisco.getRiscoPoliticoValor()) : -1f;
                politico2 = (incendioRisco.getRiscoPoliticoPremio() != null && incendioRisco.getRiscoPoliticoPremio().length()>0) ? Float.valueOf(incendioRisco.getRiscoPoliticoPremio()) : -1f;
                riscosIncendio.add("109;"+incendioRisco.getRiscoPoliticoValor() + ";" + incendioRisco.getRiscoPoliticoTaxa() + ";" + incendioRisco.getRiscoPoliticoPremio());
            }
            if (incendioRisco.getDanoId().equals("true")) {
                dano = (incendioRisco.getDanoValor() != null && incendioRisco.getDanoValor().length()>0) ? Float.valueOf(incendioRisco.getDanoValor()) : -1f;
                dano2 = (incendioRisco.getDanoPremio() != null && incendioRisco.getDanoPremio().length()>0) ? Float.valueOf(incendioRisco.getDanoPremio()) : -1f;
                riscosIncendio.add("110;"+incendioRisco.getDanoValor() + ";" + incendioRisco.getDanoTaxa() + ";" + incendioRisco.getDanoPremio());
            }
            if (incendioRisco.getTumultoId().equals("true")) {
                tumulto = (incendioRisco.getTumultoValor() != null && incendioRisco.getTumultoValor().length()>0) ? Float.valueOf(incendioRisco.getTumultoValor()) : -1f;
                tumulto2 = (incendioRisco.getTumultoPremio() != null && incendioRisco.getTumultoPremio().length()>0) ? Float.valueOf(incendioRisco.getTumultoPremio()) : -1f;
                riscosIncendio.add("111;"+incendioRisco.getTumultoValor() + ";" + incendioRisco.getTumultoTaxa() + ";" + incendioRisco.getTumultoPremio());
            }
            if (incendioRisco.getIncendioFId().equals("true")) {
                incendioF = (incendioRisco.getIncendioFValor() != null && incendioRisco.getIncendioFValor().length()>0) ? Float.valueOf(incendioRisco.getIncendioFValor()) : -1f;
                incendioF2 = (incendioRisco.getIncendioFPremio() != null && incendioRisco.getIncendioFPremio().length()>0) ? Float.valueOf(incendioRisco.getIncendioFPremio()) : -1f;
                riscosIncendio.add("112;"+incendioRisco.getIncendioFValor() + ";" + incendioRisco.getIncendioFTaxa() + ";" + incendioRisco.getIncendioFPremio());
            }
            if (incendioRisco.getExplosaoExId().equals("true")) {
                explosaoF = (incendioRisco.getExplosaoExValor() != null && incendioRisco.getExplosaoExValor().length()>0) ? Float.valueOf(incendioRisco.getExplosaoExValor()) : -1f;
                explosaoF2 = (incendioRisco.getExplosaoExPremio() != null && incendioRisco.getExplosaoExPremio().length()>0) ? Float.valueOf(incendioRisco.getExplosaoExPremio()) : -1f;
                riscosIncendio.add("113;"+incendioRisco.getExplosaoExValor() + ";" + incendioRisco.getExplosaoExTaxa() + ";" + incendioRisco.getExplosaoExPremio());
            }
            if (incendioRisco.getRoturaId().equals("true")) {
                rotura = (incendioRisco.getRoturaValor() != null && incendioRisco.getRoturaValor().length()>0) ? Float.valueOf(incendioRisco.getRoturaValor()) : -1f;
                rotura2 = (incendioRisco.getRoturaPremio() != null && incendioRisco.getRoturaPremio().length()>0) ? Float.valueOf(incendioRisco.getRoturaPremio()) : -1f;
                riscosIncendio.add("114;"+incendioRisco.getRoturaValor() + ";" + incendioRisco.getRoturaTaxa() + ";" + incendioRisco.getRoturaPremio());
            }

            System.err.println("ffff "+riscosIncendio.size()+"       "+Arrays.toString(riscosIncendio.toArray()));

                totalSegurado = aviao + colisao + explosao + terramoto + tempestade + afundamento + politico + dano + tumulto + incendioF + explosaoF + rotura;
                premioLiquido = aviao2 + colisao2 + explosao2 + terramoto2 + tempestade2 + afundamento2 + politico2 + dano2 + tumulto2 + incendioF2 + explosaoF2 + rotura2;

            if(totalSegurado ==0/*||aviao  == -1 || colisao  == -1 || explosao  == -1 || terramoto  == -1 || tempestade  == -1 || afundamento  == -1 || politico  == -1 || dano  == -1 || tumulto  == -1 || incendioF  == -1 || explosaoF  == -1 || rotura== -1
                    ||aviao2  == -1 || colisao2  == -1 || explosao2  == -1 || terramoto2  == -1 || tempestade2  == -1 || afundamento2  == -1 || politico2  == -1 || dano2  == -1 || tumulto2  == -1 || incendioF2  == -1 || explosaoF2  == -1 || rotura2 ==-1*/)
            {
                Mensagem.addErrorMsg("Selecione pelo menos um risco adicional");
                RequestContext.getCurrentInstance().update("Incendio:msg");
            }
            else
            {
                premioBruto = (percentagemRetirar * premioLiquido)/100;
                incendio.setTotalSegurado(String.valueOf(totalSegurado));
                incendio.setTotalSeguradoFormatado(Moeda.format(totalSegurado));
                incendio.setPremioBruto(String.valueOf(premioBruto));
                incendio.setPremioBrutoFormatado(Moeda.format(premioBruto));
                incendio.setPremioLiquido(String.valueOf(premioLiquido));
                incendio.setPremioLiquidoFormatado(Moeda.format(premioLiquido));

                construirArrays();
                if(incendio.getParede().size()>0&&incendio.getPavimento().size()>0&&incendio.getTecto().size()>0)
                {
                    System.out.println(incendio.toString());
                    SessionUtil.definirParametro("FR", this);
                    SessionUtil.definirParametro("respostas", listaRespostas);
                    RequestContext.getCurrentInstance().execute("IncendioAvancar()");
                }
                else
                {
                    Mensagem.addWarningMsg("Selecione pelo menos um tipo de cobertura para pavimento, parede e teto.");
                    RequestContext.getCurrentInstance().update("Incendio:msg");
                }
            }

        }

    }

    public boolean verificarNumeroRegistro()
    {
        @SuppressWarnings("UnusedAssignment")
        boolean valido = false;
        FacesContext context = FacesContext.getCurrentInstance();
        if(incendio.getNumeroRegistro() != null && !incendio.getNumeroRegistro().equals(""))
        {
            valido = ContratoDao.isNumRegistroVago(incendio.getNumeroRegistro());
            if(valido == false)
            {
                info = "Número de registro já existe";
                 RequestContext.getCurrentInstance().addCallbackParam("registro", "já existe");
                 Mensagem.addErrorMsg("Número de registro já existe");
                 RequestContext.getCurrentInstance().update("Incendio:msg");
            }
            else
            {
                valido = true;
                 RequestContext.getCurrentInstance().update("Incendio:msg");
            }
        }
        else
        {
            Message.addWarningMsg("Informe o número de registro", "Incendio", "msg");
            RequestContext.getCurrentInstance().execute("topoIncendio()");
            valido = false;
        }
        return valido;
    }

    private void construirArrays() {
        construirPavimentos();
        construirParede();
        construirTecto();
    }

    private void construirParede() {
        if(this.incendio.isParedeBetao())
        {
            this.incendio.getParede().add("60;"+5);
        }
        if(this.incendio.isParedeTijolo())
        {
            this.incendio.getParede().add("60;"+6);
        }
    }

    private void construirTecto() {
        if(this.incendio.isTectoChapaFibrocimento())
        {
            this.incendio.getTecto().add("59;"+58);
        }
        if(this.incendio.isTectoChapaZinco())
        {
            this.incendio.getTecto().add("59;57");
        }
        if(this.incendio.isTectoPlacabetao())
        {
            this.incendio.getTecto().add("59;59");
        }
        if(this.incendio.isTectoTelha())
        {
            this.incendio.getTecto().add("59;56");
        }
    }

    private void construirPavimentos() {
        if(this.incendio.isPavimentoAzuleijo())
        {
            this.incendio.getPavimento().add("58;"+9);
        }
        if(this.incendio.isPavimentoBaro())
        {
            this.incendio.getPavimento().add("58;"+7);
        }
        if(this.incendio.isPavimentoBetao())
        {
            this.incendio.getPavimento().add("58;"+31);
        }
        if(this.incendio.isPavimentoCerramica())
        {
            this.incendio.getPavimento().add("58;"+10);
        }
        if(this.incendio.isPavimentoMarmore())
        {
            this.incendio.getPavimento().add("58;"+8);
        }
    }

    private Float caluclar(String objValor, String objTaxa) {
        Float vPremio= Float.valueOf(objValor) * (Float.valueOf(objTaxa)/100);
        return vPremio;
    }

    public void calcularMultiRisco(MultiRiscoBean multiRiscoBean)
    {
        riscos.clear();
        riscosIncendio.clear();
        @SuppressWarnings("UnusedAssignment")
        Float premioBruto = 0f, premioLiquido = 0f, totalSegurado = 0f;
        Float aviao = 0f,terramoto = 0f,colisao = 0f,tempestade = 0f,explosao = 0f,afundamento = 0f,politico = 0f,dano = 0f,
        tumulto = 0f,incendioF = 0f,explosaoF = 0f,rotura = 0f,aviao2 = 0f,terramoto2 = 0f,colisao2 = 0f,tempestade2 = 0f
        ,explosao2 = 0f,afundamento2 = 0f,politico2 = 0f,dano2 = 0f,tumulto2 = 0f,incendioF2 = 0f,explosaoF2 = 0f,rotura2 = 0f;
        if (incendioRisco.getRiscoAviaoId().equals("true"))
        {
            aviao = (incendioRisco.getAviaoValor() != null && incendioRisco.getAviaoValor().length()>0) ? Float.valueOf(incendioRisco.getAviaoValor()) : -1f;
            aviao2 = (incendioRisco.getAviaoPremio() != null && incendioRisco.getAviaoPremio().length()>0) ? Float.valueOf(incendioRisco.getAviaoPremio()) : -1f;
            riscosIncendio.add("103;"+incendioRisco.getAviaoValor() + ";" + incendioRisco.getAviaoTaxa() + ";" + incendioRisco.getAviaoPremio());
        }
        if (incendioRisco.getColisaoId().equals("true")) {
            colisao = (incendioRisco.getColisaoValor() != null && incendioRisco.getColisaoValor().length()>0) ? Float.valueOf(incendioRisco.getColisaoValor()) : -1f;
            colisao2 = (incendioRisco.getColisaoPremio() != null && incendioRisco.getColisaoPremio().length()>0) ? Float.valueOf(incendioRisco.getColisaoPremio()) : -1f;
            riscosIncendio.add("104;"+incendioRisco.getColisaoValor() + ";" + incendioRisco.getColisaoTaxa() + ";" + incendioRisco.getColisaoPremio());
        }
        if (incendioRisco.getExplosaoId().equals("true")) {
            explosao = (incendioRisco.getExplosaoValor() != null && incendioRisco.getExplosaoValor().length()>0) ? Float.valueOf(incendioRisco.getExplosaoValor()) : -1f;
            explosao2 = (incendioRisco.getExplosaoPremio() != null && incendioRisco.getExplosaoPremio().length()>0) ? Float.valueOf(incendioRisco.getExplosaoPremio()) : -1f;
            riscosIncendio.add("105;"+incendioRisco.getExplosaoValor() + ";" + incendioRisco.getExplosaoTaxa() + ";" + incendioRisco.getExplosaoPremio());
        }
        if (incendioRisco.getTerramotoId().equals("true")) {
            terramoto2 = (incendioRisco.getTerramotoPremio() != null && incendioRisco.getTerramotoPremio().length()>0) ? Float.valueOf(incendioRisco.getTerramotoPremio()) : -1f;
            terramoto = (incendioRisco.getTerramotoValor() != null && incendioRisco.getTerramotoValor().length()>0) ? Float.valueOf(incendioRisco.getTerramotoValor()) : -1f;
            riscosIncendio.add("106;"+incendioRisco.getTerramotoValor() + ";" + incendioRisco.getTerramotoTaxa() + ";" + incendioRisco.getTerramotoPremio());
        }
        if (incendioRisco.getTempestadeId().equals("true")) {
            tempestade = (incendioRisco.getTempestadeValor() != null && incendioRisco.getTempestadeValor().length()>0) ? Float.valueOf(incendioRisco.getTempestadeValor()) : -1f;
            tempestade2 = (incendioRisco.getTempestadePremio() != null && incendioRisco.getTempestadePremio().length()>0) ? Float.valueOf(incendioRisco.getTempestadePremio()) : -1f;
            riscosIncendio.add("107;"+incendioRisco.getTempestadeValor() + ";" + incendioRisco.getTempestadeTaxa() + ";" + incendioRisco.getTempestadePremio());
        }
        if (incendioRisco.getAfundamentoId().equals("true")) {
            afundamento = (incendioRisco.getAfundamentoValor() != null && incendioRisco.getAfundamentoValor().length()>0) ? Float.valueOf(incendioRisco.getAfundamentoValor()) : -1f;
            afundamento2 = (incendioRisco.getAfundamentoPremio() != null && incendioRisco.getAfundamentoPremio().length()>0) ? Float.valueOf(incendioRisco.getAfundamentoPremio()) : -1f;
            riscosIncendio.add("108;"+incendioRisco.getAfundamentoValor() + ";" + incendioRisco.getAfundamentoTaxa() + ";" + incendioRisco.getAfundamentoPremio());
        }
        if (incendioRisco.getRiscoPoliticoId().equals("true")) {
            politico = (incendioRisco.getRiscoPoliticoValor() != null && incendioRisco.getRiscoPoliticoValor().length()>0) ? Float.valueOf(incendioRisco.getRiscoPoliticoValor()) : -1f;
            politico2 = (incendioRisco.getRiscoPoliticoPremio() != null && incendioRisco.getRiscoPoliticoPremio().length()>0) ? Float.valueOf(incendioRisco.getRiscoPoliticoPremio()) : -1f;
            riscosIncendio.add("109;"+incendioRisco.getRiscoPoliticoValor() + ";" + incendioRisco.getRiscoPoliticoTaxa() + ";" + incendioRisco.getRiscoPoliticoPremio());
        }
        if (incendioRisco.getDanoId().equals("true")) {
            dano = (incendioRisco.getDanoValor() != null && incendioRisco.getDanoValor().length()>0) ? Float.valueOf(incendioRisco.getDanoValor()) : -1f;
            dano2 = (incendioRisco.getDanoPremio() != null && incendioRisco.getDanoPremio().length()>0) ? Float.valueOf(incendioRisco.getDanoPremio()) : -1f;
            riscosIncendio.add("110;"+incendioRisco.getDanoValor() + ";" + incendioRisco.getDanoTaxa() + ";" + incendioRisco.getDanoPremio());
        }
        if (incendioRisco.getTumultoId().equals("true")) {
            tumulto = (incendioRisco.getTumultoValor() != null && incendioRisco.getTumultoValor().length()>0) ? Float.valueOf(incendioRisco.getTumultoValor()) : -1f;
            tumulto2 = (incendioRisco.getTumultoPremio() != null && incendioRisco.getTumultoPremio().length()>0) ? Float.valueOf(incendioRisco.getTumultoPremio()) : -1f;
            riscosIncendio.add("111;"+incendioRisco.getTumultoValor() + ";" + incendioRisco.getTumultoTaxa() + ";" + incendioRisco.getTumultoPremio());
        }
        if (incendioRisco.getIncendioFId().equals("true")) {
            incendioF = (incendioRisco.getIncendioFValor() != null && incendioRisco.getIncendioFValor().length()>0) ? Float.valueOf(incendioRisco.getIncendioFValor()) : -1f;
            incendioF2 = (incendioRisco.getIncendioFPremio() != null && incendioRisco.getIncendioFPremio().length()>0) ? Float.valueOf(incendioRisco.getIncendioFPremio()) : -1f;
            riscosIncendio.add("112;"+incendioRisco.getIncendioFValor() + ";" + incendioRisco.getIncendioFTaxa() + ";" + incendioRisco.getIncendioFPremio());
        }
        if (incendioRisco.getExplosaoExId().equals("true")) {
            explosaoF = (incendioRisco.getExplosaoExValor() != null && incendioRisco.getExplosaoExValor().length()>0) ? Float.valueOf(incendioRisco.getExplosaoExValor()) : -1f;
            explosaoF2 = (incendioRisco.getExplosaoExPremio() != null && incendioRisco.getExplosaoExPremio().length()>0) ? Float.valueOf(incendioRisco.getExplosaoExPremio()) : -1f;
            riscosIncendio.add("113;"+incendioRisco.getExplosaoExValor() + ";" + incendioRisco.getExplosaoExTaxa() + ";" + incendioRisco.getExplosaoExPremio());
        }
        if (incendioRisco.getRoturaId().equals("true")) {
            rotura = (incendioRisco.getRoturaValor() != null && incendioRisco.getRoturaValor().length()>0) ? Float.valueOf(incendioRisco.getRoturaValor()) : -1f;
            rotura2 = (incendioRisco.getRoturaPremio() != null && incendioRisco.getRoturaPremio().length()>0) ? Float.valueOf(incendioRisco.getRoturaPremio()) : -1f;
            riscosIncendio.add("114;"+incendioRisco.getRoturaValor() + ";" + incendioRisco.getRoturaTaxa() + ";" + incendioRisco.getRoturaPremio());
        }

        System.err.println("ffff "+riscosIncendio.size()+"       "+Arrays.toString(riscosIncendio.toArray()));

            totalSegurado = aviao + colisao + explosao + terramoto + tempestade + afundamento + politico + dano + tumulto + incendioF + explosaoF + rotura;
            premioLiquido = aviao2 + colisao2 + explosao2 + terramoto2 + tempestade2 + afundamento2 + politico2 + dano2 + tumulto2 + incendioF2 + explosaoF2 + rotura2;

        if(totalSegurado ==0/*||aviao  == -1 || colisao  == -1 || explosao  == -1 || terramoto  == -1 || tempestade  == -1 || afundamento  == -1 || politico  == -1 || dano  == -1 || tumulto  == -1 || incendioF  == -1 || explosaoF  == -1 || rotura== -1
                ||aviao2  == -1 || colisao2  == -1 || explosao2  == -1 || terramoto2  == -1 || tempestade2  == -1 || afundamento2  == -1 || politico2  == -1 || dano2  == -1 || tumulto2  == -1 || incendioF2  == -1 || explosaoF2  == -1 || rotura2 ==-1*/)
        {
            Mensagem.addWarningMsg("Selecione pelo menos um risco adicional");
            RequestContext.getCurrentInstance().update("Incendio:msg");
        }
        else
        {
            premioBruto =(percentagemRetirar *premioLiquido)/100;
            incendio.setTotalSegurado(String.valueOf(totalSegurado));
            incendio.setTotalSeguradoFormatado(Moeda.format(totalSegurado));
            incendio.setPremioBruto(String.valueOf(premioBruto));
            incendio.setPremioBrutoFormatado(Moeda.format(premioBruto));
            incendio.setPremioLiquido(String.valueOf(premioLiquido));
            incendio.setPremioLiquidoFormatado(Moeda.format(premioLiquido));

            construirArrays();
            if(incendio.getParede().size()>0&&incendio.getPavimento().size()>0&&incendio.getTecto().size()>0)
            {
                System.out.println(incendio.toString());
                SessionUtil.definirParametro("FR", this);
                SessionUtil.definirParametro("FR2", "true2");
                SessionUtil.definirParametro("respostas", listaRespostas);

                multiRiscoBean.validar();
            }
            else
            {
                Mensagem.addWarningMsg("Selecione pelo menos um tipo de cobertura, parede ou teto.");
                RequestContext.getCurrentInstance().update("Incendio:msg");
            }
        }
    }

   public boolean validaNumeroApolice()
   {
        if(SessionUtil.obterValor(SessionUtil.APOLICE_CONTRATO_SEGURO) != null && !SessionUtil.obterValor(SessionUtil.APOLICE_CONTRATO_SEGURO).equals("N"))
        {
            incendio.setNumeroApolice(SessionUtil.obterValor(SessionUtil.APOLICE_CONTRATO_SEGURO).toString());
            return true;
        }
        else
           return incendio.getNumeroApolice() != null && !incendio.getNumeroApolice().equals("");
   }
}


text:
package com.graphhopper.jsprit.core.testutils;

public class NewActivityFactory {

    private NewActivityFactory() {
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sun.org.apache.bcel.internal.generic;

import com.sun.org.apache.bcel.internal.Const;
import com.sun.org.apache.bcel.internal.ExceptionConst;

/**
 * GETSTATIC - Fetch static field from class
 *
Stack: ..., -> ..., value

 * OR
 *
Stack: ..., -> ..., value.word1, value.word2

 *
 */
public class GETSTATIC extends FieldInstruction implements PushInstruction, ExceptionThrower {

    /**
     * Empty constructor needed for Instruction.readInstruction.
     * Not to be used otherwise.
     */
    GETSTATIC() {
    }

    public GETSTATIC(final int index) {
        super(Const.GETSTATIC, index);
    }

    @Override
    public int produceStack( final ConstantPoolGen cpg ) {
        return getFieldSize(cpg);
    }

    @Override
    public Class<?>[] getExceptions() {
        return ExceptionConst.createExceptions(ExceptionConst.EXCS.EXCS_FIELD_AND_METHOD_RESOLUTION,
            ExceptionConst.INCOMPATIBLE_CLASS_CHANGE_ERROR);
    }

    /**
     * Call corresponding visitor method(s). The order is:
     * Call visitor methods of implemented interfaces first, then
     * call methods according to the class hierarchy in descending order,
     * i.e., the most specific visitXXX() call comes last.
     *
     * @param v Visitor object
     */
    @Override
    public void accept( final Visitor v ) {
        v.visitStackProducer(this);
        v.visitPushInstruction(this);
        v.visitExceptionThrower(this);
        v.visitTypedInstruction(this);
        v.visitLoadClass(this);
        v.visitCPInstruction(this);
        v.visitFieldOrMethod(this);
        v.visitFieldInstruction(this);
        v.visitGETSTATIC(this);
    }
}


text:
package org.eclipse.om2m.commons.exceptions;

import org.eclipse.om2m.commons.constants.ResponseStatusCode;

/**
 * Represent a requested resource that has not been found by the CSE.
 *
 */
public class ResourceNotFoundException extends Om2mException {

	private static final long serialVersionUID = 97051750274646057L;

	public ResourceNotFoundException() {
		super("Resource not found", ResponseStatusCode.NOT_FOUND);
	}

	public ResourceNotFoundException(String message){
		super(message, ResponseStatusCode.NOT_FOUND);
	}

	public ResourceNotFoundException(String message, Throwable cause){
		super(message, cause, ResponseStatusCode.NOT_FOUND);
	}

}


text:
package net.cattaka.util.cathandsgendroid.annotation;

public @interface AsyncInterfaceAttrs {
    boolean forceSync() default false;

    boolean ignore() default false;
}


text:
Welcome to the Dart API reference documentation, covering the official Dart API
libraries. Some of the most fundamental Dart libraries include:

  * [dart:core](dart-core/dart-core-library.html): Core functionality such as strings, numbers, collections, errors, dates, and URIs.
  * [dart:html](dart-html/dart-html-library.html): DOM manipulation for web apps.
  * [dart:io](dart-io/dart-io-library.html): I/O for command-line apps.

Except for `dart:core`, you must import a library before you can use it. Here's
an example of importing `dart:html` and `dart:math`:

```dart
import 'dart:html';
import 'dart:math';
```

You can install more libraries using the pub package manager. For information
on finding, using, and publishing libraries with pub, see
[pub.dartlang.org](https://pub.dartlang.org).

The main site for learning and using Dart is
[www.dartlang.org](https://www.dartlang.org). Check out these additional pages:

  * [Tutorials](https://www.dartlang.org/docs/tutorials/)
  * [Programmer's Guide](https://www.dartlang.org/docs/)
  * [Samples](https://www.dartlang.org/samples/)
  * [A Tour of the Dart Libraries](https://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html)

This API reference is automatically generated from the source code in the
[Dart project](https://github.com/dart-lang/sdk). If you'd like to contribute to
this documentation, see
[Contributing](https://github.com/dart-lang/sdk/wiki/Contributing).


text:
class LimitedUse < Module
  def initialize(limit)
    @limit = limit
    super() do
      define_singleton_method(:included) do |parent|
        count = 0
        parent.public_instance_methods.each do |method|
          define_method(method) do |*args|
            fail 'Over use limit' if (count += 1) > limit
            super(*args)
          end
        end #parent._
      end #define_.
    end #super_
  end

  def to_s; "LimitedUse.new(#{@limit})" end
end

class ShortLived
  include LimitedUse.new(3)
end
p ShortLived.ancestors

limited = ShortLived.new
puts Array.new(3){ limited.to_s }
begin
  limited.to_s
rescue Exception => err
  p err.message
end


text:
export function manageContentPageState() {
  return {
    toolbarTitle: '',
    channelList: [],
    channelListLoading: false,
    taskList: [],
    wizardState: importExportWizardState(),
  };
}

// Monolithic object that stores state needed for all import/export flows
export function importExportWizardState() {
  return {
    // 0. can be set at any time
    status: '',
    // 1. set after clicking "import" or "export", and changes throughout flow
    pageName: '',
    // 2. set after choosing REMOTEEXPORT or LOCALIMPORT
    driveList: [],
    // 3. set after choosing a USB drive or Kolibri Studio
    transferType: '',
    availableChannels: [],
    selectedDrive: {},
    availableSpace: null,
    // 4. set after choosing channel
    transferredChannel: {},
    currentTopicNode: {},
    path: [],
    pathCache: {},
    nodesForTransfer: {
      included: [],
      omitted: [],
      // totalFileSize and totalResources are defined as getters
    },
  };
}


text:
package com.amazonaws.services.cloudwatch.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.cloudwatch.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * Range StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RangeStaxUnmarshaller implements Unmarshaller<Range, StaxUnmarshallerContext> {

    public Range unmarshall(StaxUnmarshallerContext context) throws Exception {
        Range range = new Range();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return range;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("StartTime", targetDepth)) {
                    range.setStartTime(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                    continue;
                }

                if (context.testExpression("EndTime", targetDepth)) {
                    range.setEndTime(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return range;
                }
            }
        }
    }

    private static RangeStaxUnmarshaller instance;

    public static RangeStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new RangeStaxUnmarshaller();
        return instance;
    }
}


text:
package org.locationtech.geomesa.fs.storage.orc.utils

import java.sql.Timestamp

import com.vividsolutions.jts.geom.{Geometry, Point}
import org.apache.hadoop.hive.ql.io.sarg.{PredicateLeaf, SearchArgument, SearchArgumentFactory}
import org.apache.orc.TypeDescription
import org.locationtech.geomesa.filter.{Bounds, FilterHelper}
import org.locationtech.geomesa.fs.storage.orc.OrcFileSystemStorage
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.filter.Filter

object OrcSearchArguments {

  /**
    * Creates a push-down predicate for Orc files based on a CQL filter
    *
    * @param sft simple feature type
    * @param description orc file description
    * @param filter cql filter
    * @return
    */
  def apply(sft: SimpleFeatureType,
            description: TypeDescription,
            filter: Filter): Option[(SearchArgument, Array[String])] = {
    import org.apache.orc.TypeDescription.Category._

    val predicates = FilterHelper.propertyNames(filter, sft).distinct.flatMap { prop =>
      val binding = sft.getDescriptor(prop).getType.getBinding
      val preds = if (classOf[Geometry].isAssignableFrom(binding)) {
        if (classOf[Point] == binding) {
          FilterHelper.extractGeometries(filter, prop).values.map(addPoint(prop, _))
        } else {
          // orc doesn't support push-down predicates against complex fields
          Seq.empty
        }
      } else {
        val category = description.getChildren.get(sft.indexOf(prop)).getCategory
        val typeAndConversion = category match {
          case BOOLEAN   => Some(PredicateLeaf.Type.BOOLEAN, (v: Any) => v)
          case INT       => Some(PredicateLeaf.Type.LONG, (v: Any) => v.asInstanceOf[java.lang.Integer].longValue)
          case LONG      => Some(PredicateLeaf.Type.LONG, (v: Any) => v)
          case FLOAT     => Some(PredicateLeaf.Type.FLOAT, (v: Any) => v.asInstanceOf[java.lang.Float].doubleValue)
          case DOUBLE    => Some(PredicateLeaf.Type.FLOAT, (v: Any) => v)
          case STRING    => Some(PredicateLeaf.Type.STRING, (v: Any) => v)
          case TIMESTAMP => Some(PredicateLeaf.Type.TIMESTAMP, (v: Any) => new Timestamp(v.asInstanceOf[java.util.Date].getTime))
          case BINARY | LIST | MAP => None // orc doesn't support push-down predicates against complex fields
          case BYTE | CHAR | SHORT | DATE | DECIMAL | VARCHAR | STRUCT =>
            throw new IllegalArgumentException(s"SimpleFeature TypeDefinition should not have type '$category'")
        }
        typeAndConversion.toSeq.flatMap { case (typ, conversion) =>
          FilterHelper.extractAttributeBounds(filter, prop, binding).values.flatMap(add(prop, _, typ, conversion))
        }
      }

      if (preds.isEmpty) {
        Seq.empty
      } else {
        Seq(preds)
      }
    }

    if (predicates.isEmpty) { None } else {
      val arg = SearchArgumentFactory.newBuilder
      if (predicates.length > 1) {
        arg.startAnd()
      }
      predicates.foreach { preds =>
        if (preds.length == 1) {
          preds.head.apply(arg)
        } else {
          arg.startOr()
          preds.foreach(_.apply(arg))
          arg.end()
        }
      }
      if (predicates.length > 1) {
        arg.end()
      }
      // note: column name array does not matter at all
      Some((arg.build, Array.empty))
    }
  }

  private def add(prop: String,
                  bounds: Bounds[_],
                  typ: PredicateLeaf.Type,
                  convert: (Any) => Any): Option[(SearchArgument.Builder) => Unit] = {
    if (bounds.isRange) {
      if (bounds.isBoundedBothSides) {
        // between seems to be endpoint inclusive, so should not have any false negatives regardless of bounds inclusiveness
        Some((arg) => arg.between(prop, typ, convert(bounds.lower.value.get), convert(bounds.upper.value.get)))
      } else if (bounds.isBounded) {
        if (bounds.upper.value.isDefined) {
          if (bounds.upper.inclusive) {
            Some((arg) => arg.lessThanEquals(prop, typ, convert(bounds.upper.value.get)))
          } else {
            Some((arg) => arg.lessThan(prop, typ, convert(bounds.upper.value.get)))
          }
        } else if (bounds.lower.inclusive) {
          Some((arg) => arg.startNot().lessThan(prop, typ, convert(bounds.lower.value.get)).end())
        } else {
          Some((arg) => arg.startNot().lessThanEquals(prop, typ, convert(bounds.lower.value.get)).end())
        }
      } else {
        None
      }
    } else {
      Some((arg) => arg.equals(prop, typ, convert(bounds.lower.value.get)))
    }
  }

  private def addPoint(prop: String, bounds: Geometry): (SearchArgument.Builder) => Unit = {
    val x = OrcFileSystemStorage.geometryXField(prop)
    val y = OrcFileSystemStorage.geometryYField(prop)
    val envelope = bounds.getEnvelopeInternal

    (arg) => {
      arg.startAnd()
      if (envelope.getMinX == envelope.getMaxX) {
        arg.equals(x, PredicateLeaf.Type.FLOAT, envelope.getMinX)
      } else {
        arg.between(x, PredicateLeaf.Type.FLOAT, envelope.getMinX, envelope.getMaxX)
      }
      if (envelope.getMinY == envelope.getMaxY) {
        arg.equals(y, PredicateLeaf.Type.FLOAT, envelope.getMinY)
      } else {
        arg.between(y, PredicateLeaf.Type.FLOAT, envelope.getMinY, envelope.getMaxY)
      }
      arg.end()
    }
  }
}


text:
<?php
date_default_timezone_set('Australia/Adelaide');
$servername = "vdb1a.pair.com";
$username 	= "sygcom_72";
$password 	= "GxQ7ASdm";
$dbname 	= "sygcom_diesel";

ini_set('memory_limit', '128M');
@set_time_limit(-1);

$dir = "datafeed/watches";
$dh  = opendir($dir);

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
	exit;
}
if ($_GET["start"]=="FIRST"):
	echo "aa";
	while (false !== ($filename = readdir($dh))) {
		echo "
".$filename;
		if($filename !='.' and $filename !='..' and (strpos($filename,'.jpg'))):
			$curr_dt=date('Y-m-d H:i:s');
			$ins_sql="insert ignore into prod_image_watches(filename,created_dt) values('$filename','$curr_dt')";
			$conn->query($ins_sql);
			echo "
 $cnt".$ins_sql;
			//exit;
			$cnt++;
		endif;
	};
else:
	$sql="select * from prod_image_watches where processed='No' limit 100";
	$result = $conn->query($sql);
	if ($result->num_rows ==0) :
		echo "Process Over";
	else:
		while($row = $result->fetch_assoc()) {
			$filename=$row["filename"];
			//echo "
file: " . $row["filename"]. " :  Processed: " . $row["processed"];
			process_file($filename);
			$upd_sql="Update prod_image_tshirt set processed='Yes' where filename='$filename'";
			//echo "
 ".$upd_sql;
			$conn->query($upd_sql);
			if(!file_exists("datafeed_watches_processed/".$filename)):
				move_file($filename);
			endif;
			$upd_sql="update prod_image_tshirt set processed='Moved' where filename='$filename'";
			$conn->query($upd_sql);

		}
	endif;
	$conn->close();
	//header('Location: http://au.diesel.com/resize_0229.php');
	exit;
endif;
function move_file($filename){
	$src="datafeed/watches/".$filename;
	$dest="datafeed_watches_processed/".$filename;
	rename($src,$dest);
}
function process_file($filename){
	//echo "
 ".$filename;
	if($filename !='.' and $filename !='..'):
		$file_arr=explode("_",$filename);
		$folder_name=$file_arr[0].$file_arr[1];
		//echo "
 $folder_name
";
		//print_r($file_arr);
		if (!file_exists('prod_images_watch/'.$folder_name)):
				mkdir('prod_images_watch/'.$folder_name);
		endif;

		// Get new sizes
		$dir = "datafeed/watches";
		//$dh  = opendir($dir);
		$file_path=$dir."/".$filename;
		list($width, $height) = getimagesize($file_path);
		$arr=Array();
		$arr["popup"]=Array("width"=>228,"height"=>304);
		$arr["zoom"]=Array("width"=>1500,"height"=>2000);
		$arr["color_swatch"]=Array("width"=>65,"height"=>87);
		$arr["prod_swatch"]=Array("width"=>41,"height"=>55);
		$arr["detail"]=Array("width"=>412,"height"=>549);
		$source = imagecreatefromjpeg($file_path);
		list($width, $height) = getimagesize($file_path);

		foreach($arr as $image_type=>$dimention){
			//echo "
 $image_type : ";
			$temp_folder_name=$image_type;
			$temp_folder_path='prod_images_watch/'.$folder_name."/".$temp_folder_name;
			if (!file_exists($temp_folder_path)):
				mkdir($temp_folder_path);
			endif;
			$curr_width=$dimention["width"];
			$curr_height=$dimention["height"];
			//echo "
 $image_type - $curr_width - $curr_height";
			$temp_image = imagecreatetruecolor($curr_width, $curr_height);
			//imagecopyresized($temp_image,$source, 0, 0, 0, 0, $curr_width, $curr_height, $width, $height);
			imagecopyresampled($temp_image,$source, 0, 0, 0, 0,$curr_width, $curr_height, $width, $height);
			imagejpeg($temp_image,$temp_folder_path."/".$filename,100);
			imagedestroy($temp_image);
		}
	endif;
}

?>


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.serverless.v1.service.function.function_version import FunctionVersionList

class FunctionList(ListResource):
    """ PLEASE NOTE that this class contains beta products that are subject to
    change. Use them with caution. """

    def __init__(self, version, service_sid):
        """
        Initialize the FunctionList

        :param Version version: Version that contains the resource
        :param service_sid: The SID of the Service that the Function resource is associated with

        :returns: twilio.rest.serverless.v1.service.function.FunctionList
        :rtype: twilio.rest.serverless.v1.service.function.FunctionList
        """
        super(FunctionList, self).__init__(version)

        # Path Solution
        self._solution = {'service_sid': service_sid, }
        self._uri = '/Services/{service_sid}/Functions'.format(**self._solution)

    def stream(self, limit=None, page_size=None):
        """
        Streams FunctionInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param int limit: Upper limit for the number of records to return. stream()
                          guarantees to never return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, stream() will attempt to read the
                              limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.serverless.v1.service.function.FunctionInstance]
        """
        limits = self._version.read_limits(limit, page_size)

        page = self.page(page_size=limits['page_size'], )

        return self._version.stream(page, limits['limit'])

    def list(self, limit=None, page_size=None):
        """
        Lists FunctionInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param int limit: Upper limit for the number of records to return. list() guarantees
                          never to return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, list() will attempt to read the limit
                              with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.serverless.v1.service.function.FunctionInstance]
        """
        return list(self.stream(limit=limit, page_size=page_size, ))

    def page(self, page_token=values.unset, page_number=values.unset,
             page_size=values.unset):
        """
        Retrieve a single page of FunctionInstance records from the API.
        Request is executed immediately

        :param str page_token: PageToken provided by the API
        :param int page_number: Page Number, this value is simply for client state
        :param int page_size: Number of records to return, defaults to 50

        :returns: Page of FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionPage
        """
        data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })

        response = self._version.page(method='GET', uri=self._uri, params=data, )

        return FunctionPage(self._version, response, self._solution)

    def get_page(self, target_url):
        """
        Retrieve a specific page of FunctionInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionPage
        """
        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return FunctionPage(self._version, response, self._solution)

    def create(self, friendly_name):
        """
        Create the FunctionInstance

        :param unicode friendly_name: A string to describe the Function resource

        :returns: The created FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        data = values.of({'FriendlyName': friendly_name, })

        payload = self._version.create(method='POST', uri=self._uri, data=data, )

        return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], )

    def get(self, sid):
        """
        Constructs a FunctionContext

        :param sid: The SID of the Function resource to fetch

        :returns: twilio.rest.serverless.v1.service.function.FunctionContext
        :rtype: twilio.rest.serverless.v1.service.function.FunctionContext
        """
        return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )

    def __call__(self, sid):
        """
        Constructs a FunctionContext

        :param sid: The SID of the Function resource to fetch

        :returns: twilio.rest.serverless.v1.service.function.FunctionContext
        :rtype: twilio.rest.serverless.v1.service.function.FunctionContext
        """
        return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Serverless.V1.FunctionList>'

class FunctionPage(Page):
    """ PLEASE NOTE that this class contains beta products that are subject to
    change. Use them with caution. """

    def __init__(self, version, response, solution):
        """
        Initialize the FunctionPage

        :param Version version: Version that contains the resource
        :param Response response: Response from the API
        :param service_sid: The SID of the Service that the Function resource is associated with

        :returns: twilio.rest.serverless.v1.service.function.FunctionPage
        :rtype: twilio.rest.serverless.v1.service.function.FunctionPage
        """
        super(FunctionPage, self).__init__(version, response)

        # Path Solution
        self._solution = solution

    def get_instance(self, payload):
        """
        Build an instance of FunctionInstance

        :param dict payload: Payload response from the API

        :returns: twilio.rest.serverless.v1.service.function.FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Serverless.V1.FunctionPage>'

class FunctionContext(InstanceContext):
    """ PLEASE NOTE that this class contains beta products that are subject to
    change. Use them with caution. """

    def __init__(self, version, service_sid, sid):
        """
        Initialize the FunctionContext

        :param Version version: Version that contains the resource
        :param service_sid: The SID of the Service to fetch the Function resource from
        :param sid: The SID of the Function resource to fetch

        :returns: twilio.rest.serverless.v1.service.function.FunctionContext
        :rtype: twilio.rest.serverless.v1.service.function.FunctionContext
        """
        super(FunctionContext, self).__init__(version)

        # Path Solution
        self._solution = {'service_sid': service_sid, 'sid': sid, }
        self._uri = '/Services/{service_sid}/Functions/{sid}'.format(**self._solution)

        # Dependents
        self._function_versions = None

    def fetch(self):
        """
        Fetch the FunctionInstance

        :returns: The fetched FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        payload = self._version.fetch(method='GET', uri=self._uri, )

        return FunctionInstance(
            self._version,
            payload,
            service_sid=self._solution['service_sid'],
            sid=self._solution['sid'],
        )

    def delete(self):
        """
        Deletes the FunctionInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._version.delete(method='DELETE', uri=self._uri, )

    def update(self, friendly_name):
        """
        Update the FunctionInstance

        :param unicode friendly_name: A string to describe the Function resource

        :returns: The updated FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        data = values.of({'FriendlyName': friendly_name, })

        payload = self._version.update(method='POST', uri=self._uri, data=data, )

        return FunctionInstance(
            self._version,
            payload,
            service_sid=self._solution['service_sid'],
            sid=self._solution['sid'],
        )

    @property
    def function_versions(self):
        """
        Access the function_versions

        :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
        :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
        """
        if self._function_versions is None:
            self._function_versions = FunctionVersionList(
                self._version,
                service_sid=self._solution['service_sid'],
                function_sid=self._solution['sid'],
            )
        return self._function_versions

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Serverless.V1.FunctionContext {}>'.format(context)

class FunctionInstance(InstanceResource):
    """ PLEASE NOTE that this class contains beta products that are subject to
    change. Use them with caution. """

    def __init__(self, version, payload, service_sid, sid=None):
        """
        Initialize the FunctionInstance

        :returns: twilio.rest.serverless.v1.service.function.FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        super(FunctionInstance, self).__init__(version)

        # Marshaled Properties
        self._properties = {
            'sid': payload.get('sid'),
            'account_sid': payload.get('account_sid'),
            'service_sid': payload.get('service_sid'),
            'friendly_name': payload.get('friendly_name'),
            'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
            'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
            'url': payload.get('url'),
            'links': payload.get('links'),
        }

        # Context
        self._context = None
        self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], }

    @property
    def _proxy(self):
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions.  All instance actions are proxied to the context

        :returns: FunctionContext for this FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionContext
        """
        if self._context is None:
            self._context = FunctionContext(
                self._version,
                service_sid=self._solution['service_sid'],
                sid=self._solution['sid'],
            )
        return self._context

    @property
    def sid(self):
        """
        :returns: The unique string that identifies the Function resource
        :rtype: unicode
        """
        return self._properties['sid']

    @property
    def account_sid(self):
        """
        :returns: The SID of the Account that created the Function resource
        :rtype: unicode
        """
        return self._properties['account_sid']

    @property
    def service_sid(self):
        """
        :returns: The SID of the Service that the Function resource is associated with
        :rtype: unicode
        """
        return self._properties['service_sid']

    @property
    def friendly_name(self):
        """
        :returns: The string that you assigned to describe the Function resource
        :rtype: unicode
        """
        return self._properties['friendly_name']

    @property
    def date_created(self):
        """
        :returns: The ISO 8601 date and time in GMT when the Function resource was created
        :rtype: datetime
        """
        return self._properties['date_created']

    @property
    def date_updated(self):
        """
        :returns: The ISO 8601 date and time in GMT when the Function resource was last updated
        :rtype: datetime
        """
        return self._properties['date_updated']

    @property
    def url(self):
        """
        :returns: The absolute URL of the Function resource
        :rtype: unicode
        """
        return self._properties['url']

    @property
    def links(self):
        """
        :returns: The URLs of nested resources of the Function resource
        :rtype: unicode
        """
        return self._properties['links']

    def fetch(self):
        """
        Fetch the FunctionInstance

        :returns: The fetched FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        return self._proxy.fetch()

    def delete(self):
        """
        Deletes the FunctionInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._proxy.delete()

    def update(self, friendly_name):
        """
        Update the FunctionInstance

        :param unicode friendly_name: A string to describe the Function resource

        :returns: The updated FunctionInstance
        :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
        """
        return self._proxy.update(friendly_name, )

    @property
    def function_versions(self):
        """
        Access the function_versions

        :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
        :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList
        """
        return self._proxy.function_versions

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Serverless.V1.FunctionInstance {}>'.format(context)


text:
module Closet
  module Bury
    module InstanceMethods

      def bury( options = { dependent: true } )
        begin
          self.bury!( dependent: options.with_indifferent_access[:dependent] )
        rescue
          false
        end
      end

      def bury!( options= { dependent: true } )
        if options.with_indifferent_access[:dependent]
          ActiveRecord::Base.transaction do
            run_callbacks( :bury ) do
              flag_as_buried
            end
          end
        else
          flag_as_buried
        end
      end

      def buried?
        self.reload && self.buried_at != nil
      end

      private

      def flag_as_buried
        update_columns(buried_at: Time.now)
      end

    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Stefan Bertels Blog</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//StefanBertels.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//StefanBertels.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://StefanBertels.github.io" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Stefan Bertels Blog" href="https://StefanBertels.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

Analog

                    A 1-post collection

        Page 1 of 1

Nebengeräusche

Beim Abspielen von Audiodateien oder Webradiostreams auf einem älteren Raspberry Pi 1 (B) habe ich mit einem analog angeschlossenen Kopfhörer leise Nebengeräusche festgestellt. Aufg »

             on Raspbian,  Raspberry Pi,  Audio,  Analog
            <time class="post-date" datetime="2016-02-13">13 February 2016</time>

        Page 1 of 1

Stefan Bertels Blog © 2016

Proudly published with HubPress


text:
<?php

namespace Kunstmaan\RedirectBundle\Tests\Entity;

use Kunstmaan\RedirectBundle\Entity\Redirect;
use PHPUnit_Framework_TestCase;
use Symfony\Component\Validator\Context\ExecutionContext;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilder;

/**
 * Class RedirectTest
 * @package Tests\Kunstmaan\RedirectBundle\Entity
 */
class RedirectTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Redirect
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new Redirect;
    }

    public function testGetSetDomain()
    {
        $this->object->setDomain('domain.com');
        $this->assertEquals('domain.com', $this->object->getDomain());
    }

    public function testGetSetOrigin()
    {
        $this->object->setOrigin('origin');
        $this->assertEquals('origin', $this->object->getOrigin());
    }

    public function testGetSetTarget()
    {
        $this->object->setTarget('target');
        $this->assertEquals('target', $this->object->getTarget());
    }

    public function testGetSetPermanent()
    {
        $this->object->setPermanent(true);
        $this->assertTrue($this->object->isPermanent());
    }

    /**
     *  Shouldn't this validation method go in an entity validator class?
     */
    public function testValidateEntityCallsContext()
    {
        $violationBuilder = $this->getMockBuilder(ConstraintViolationBuilder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $violationBuilder->expects($this->once())
            ->method('atPath')
            ->will($this->returnValue($violationBuilder));

        $violationBuilder->expects($this->once())
            ->method('addViolation')
            ->will($this->returnValue(true));

        $context = $this->getMockBuilder(ExecutionContext::class)
            ->disableOriginalConstructor()
            ->getMock();

        $context->expects($this->once())
            ->method('buildViolation')
            ->will($this->returnValue($violationBuilder));

        $this->object->setOrigin('riches');
        $this->object->setTarget('riches');
        $this->object->validate($context);
    }

    public function testValidateEntityDoesntCallContext()
    {
        $violationBuilder = $this->getMockBuilder(ConstraintViolationBuilder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $violationBuilder->expects($this->never())
            ->method('atPath')
            ->will($this->returnValue($violationBuilder));

        $violationBuilder->expects($this->never())
            ->method('addViolation')
            ->will($this->returnValue(true));

        $context = $this->getMockBuilder(ExecutionContext::class)
            ->disableOriginalConstructor()
            ->getMock();

        $context->expects($this->never())
            ->method('buildViolation')
            ->will($this->returnValue($violationBuilder));

        $this->object->setOrigin('rags');
        $this->object->setTarget('riches');
        $this->object->validate($context);
    }
}


text:
layout: post
status: publish
published: true
title: Generate random string of characters in PHP
author: Pawel
author_login: admin
author_email: pawel@pawelmartuszewski.co.uk
author_url: http://www.pawelmartuszewski.co.uk
excerpt: In this very short tutorial, I am going to show you how to ceate a flexible
  php function. This function will allow you to generate random string of your choosen
  characters and your choosen length. Let's create the php function!
wordpress_id: 1429
wordpress_url: http://www.pawelmartuszewski.co.uk/?p=1429
date: 2010-02-13 22:54:04.000000000 +00:00
categories:
- Tutorials
- PHP / MySQL
tags:
- PHP
comments:
- id: 325
  author: Dan
  author_email: daniel4443@gmail.com
  author_url: ''
  date: '2010-03-14 00:53:42 +0000'
  date_gmt: '2010-03-13 23:53:42 +0000'
  content: Exactly what I was looking for! Thanks man!
- id: 522
  author: Teiya
  author_email: rss@fd.mk.ua
  author_url: http://www.google.com/
  date: '2011-05-07 17:46:49 +0100'
  date_gmt: '2011-05-07 16:46:49 +0100'
  content: Thanks for sharing. Awayls good to find a real expert.
---
In this very short tutorial, I am going to show you how to ceate a flexible php function. This function will allow you to generate random string of your choosen characters and your choosen length. Let's create the php function!
Demo

Starting our function

<?php

function random_string($chars, $length) {

Assigning strings to variables

// Assign strings to variables
$lc = 'abcdefghijklmnopqrstuvwxyz'; // lowercase
$uc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // uppercase
$nr = '1234567890'; // numbers
$sp = '^@*+-+%()!?'; //special characters

Creating switch for different chars selection

// Set cases for our characters
switch ($chars) {

case 'lower': $chars = $lc; break;

case 'upper': $chars = $uc; break;

case 'numbers': $chars = $nr; break;

case 'special': $chars = $sp; break;

case 'all': $chars = $lc.$up.$nr.$sp; break;

}

You can specify more cases to suit your needs if it comes to character selection.

Processing (core of our function)

// Length of character list
$chars_length = (strlen($chars) - 1);

// Start our string
$string = $chars{rand(0, $chars_length)};

// Generate random string
for ($i = 1; $i < $length; $i = strlen($string))

{

// Take random character from our list
$random = $chars{rand(0, $chars_length)};

// Make sure the same two characters don't appear next to each other
if ($random != $string{$i - 1}) $string .=  $random;

}

Return variable

//return our generated string
return $string;

}

Echoing our function with different parameters

<?php

echo random_string('lower',20); // generates lowercase string - 20 chars length
echo random_string('upper',20); // generates uppercase string - 20 chars length
echo random_string('numbers',10); // generates numbers string - 10 chars length
echo random_string('special',40); // generates special chars string - 40 chars length
echo random_string('all',50); // generates all chars string - 50 chars length

Well, you've got the idea.

Feel free to share yours techniques to generate random string in php. Don't forget to share it with others and subscribe to my newsletter!


text:
using Meebey.SmartIrc4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Xml;

namespace PegBot.Plugins
{
    class RSSReader : BotPlugin
    {
        private int updateTime = 10;
        private Timer RSSTimer;

        public RSSReader(IrcClient irc)
            : base(irc, "RSSReader")
        {
            RSSTimer = new Timer(1000 * 60 * updateTime);
            RSSTimer.Elapsed += new ElapsedEventHandler(RSSTimer_Elapsed);
            RSSTimer.Start();

            RegisterCommand(".rss add", "<short-name> <rss-url>", "Add rss watcher on <rss-url>", OnAdd, arg => arg.Split(' ').Length >= 2);
            RegisterCommand(".rss remove", "<short-name>", "Remove rss watcher", OnRemove);
            RegisterCommand(".rss list", "Print list of rss feeds active in this channel", OnList, false);
        }

        private void OnAdd(string arg, string channel, string nick, string replyTo)
        {
            Dictionary<string, string[]> Feeds = GetSetting(channel) as Dictionary<string, string[]> ?? new Dictionary<string, string[]>();
            string url = arg.Split(' ').Last();
            string id = arg.Substring(0, arg.Length - url.Length);

            if (Feeds.Keys.Contains(id))
                Feeds.Remove(id);
            string[] rssdata = new string[] {url, String.Empty };
            Feeds.Add(id, rssdata);
            SetSetting(channel, Feeds);
        }

        private void OnRemove(string arg, string channel, string nick, string replyTo)
        {
            Dictionary<string, string[]> Feeds = GetSetting(channel) as Dictionary<string, string[]>;
            if (Feeds != null && Feeds.Remove(arg))
                SetSetting(channel, Feeds);
        }

        private void OnList(string arg, string channel, string nick, string replyTo)
        {
            Dictionary<string, string[]> Feeds = GetSetting(channel) as Dictionary<string, string[]>;
            if (Feeds == null || Feeds.Count == 0)
                irc.SendMessage(SendType.Message, replyTo, "No rss-feeds in this channel");
            else
                foreach (string text in Feeds.Keys)
                    irc.SendMessage(SendType.Message, replyTo, "rss-feed: " + text);
        }

        void RSSTimer_Elapsed(object sender, ElapsedEventArgs args)
        {
            var oldCallback = ServicePointManager.ServerCertificateValidationCallback;
            ServicePointManager.ServerCertificateValidationCallback = PluginUtils.ValidateServerCertificate;
            foreach (string channel in EnabledChannels)
            {
                Dictionary<string, string[]> Feeds = GetSetting(channel) as Dictionary<string, string[]> ?? new Dictionary<string, string[]>();
                foreach (string key in Feeds.Keys)
                {
                    try
                    {
                        SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(Feeds[key][0]));
                        foreach (SyndicationItem item in feed.Items)
                        {
                            if (String.IsNullOrEmpty(Feeds[key][1]))
                                Feeds[key][1] = item.Title.Text;
                            if (Feeds[key][1] == item.Title.Text)
                                break;
                            else
                                irc.SendMessage(SendType.Message, channel, item.Title.Text + " Author: " + item.Authors.First().Name);
                        }
                        Feeds[key][1] = feed.Items.First().Title.Text;
                    }
                    catch (Exception e)
                    {
                        PluginUtils.Log(e.Message, "RSS: " + Feeds[key][0], e.StackTrace);
                    };
                    SetSetting(channel, Feeds);
                }
            }
            ServicePointManager.ServerCertificateValidationCallback = oldCallback;
        }
    }
}


text:
sndcld is a music downloader for soundcloud written in C.
It is meant as an exercise and shouldn't be used for illegal purposes.

## Features
- [x] Download arbitrary tracks on soundcloud
- [x] Choose output filename interactively or with CLI arguments
- [ ] Handle playlists
- [x] If filename is not given, use URL to guess

## Dependencies
The only dependencies are libcurl (with SSL support) and CMake to build the project.

## TODO
- [x] Automatic build with CMake